path
stringlengths 7
265
| concatenated_notebook
stringlengths 46
17M
|
---|---|
docs/geemap_complete/applications/template.ipynb | ###Markdown
[](https://colab.research.google.com/github/giswqs/GEE-Courses/blob/master/docs/geemap_complete/applications/template.ipynb)Uncomment and execute the following code block to install geemap if needed.
###Code
# !pip install geemap
###Output
_____no_output_____ |
boards/Pynq-Z1/base/notebooks/board/board_btns_leds.ipynb | ###Markdown
Buttons and LEDs demonstrationThis demo shows how to use push-buttons (BTN0-3), LEDs (LD0-3), and RGB LEDs (LD4-5) on the board. You can do the following to control the LEDs or RGB LEDs: Button 0 pressed: RGB LEDs change color. Button 1 pressed: LEDs shift from right to left (LD0 -> LD3). Button 2 pressed: LEDs shift from left to right (LD3 -> LD0). Button 3 pressed: Turns off all the LEDS and ends this demo.
###Code
from time import sleep
from pynq.overlays.base import BaseOverlay
base = BaseOverlay("base.bit")
Delay1 = 0.3
Delay2 = 0.1
color = 0
rgbled_position = [4,5]
for led in base.leds:
led.on()
while (base.buttons[3].read()==0):
if (base.buttons[0].read()==1):
color = (color+1) % 8
for led in rgbled_position:
base.rgbleds[led].write(color)
base.rgbleds[led].write(color)
sleep(Delay1)
elif (base.buttons[1].read()==1):
for led in base.leds:
led.off()
sleep(Delay2)
for led in base.leds:
led.toggle()
sleep(Delay2)
elif (base.buttons[2].read()==1):
for led in reversed(base.leds):
led.off()
sleep(Delay2)
for led in reversed(base.leds):
led.toggle()
sleep(Delay2)
print('End of this demo ...')
for led in base.leds:
led.off()
for led in rgbled_position:
base.rgbleds[led].off()
###Output
End of this demo ...
###Markdown
Buttons and LEDs demonstrationThis demo shows how to use push-buttons (BTN0-3), LEDs (LD0-3), and RGB LEDs (LD4-5) on the PYNQ-Z1. You can do the following to control the LEDs or RGB LEDs: Button 0 pressed: RGB LEDs change color. Button 1 pressed: LEDs shift from right to left (LD0 -> LD3). Button 2 pressed: LEDs shift from left to right (LD3 -> LD0). Button 3 pressed: Turns off all the LEDS and ends this demo.
###Code
from time import sleep
from pynq.overlays.base import BaseOverlay
base = BaseOverlay("base.bit")
Delay1 = 0.3
Delay2 = 0.1
color = 0
rgbled_position = [4,5]
for led in base.leds:
led.on()
while (base.buttons[3].read()==0):
if (base.buttons[0].read()==1):
color = (color+1) % 8
for led in rgbled_position:
base.rgbleds[led].write(color)
base.rgbleds[led].write(color)
sleep(Delay1)
elif (base.buttons[1].read()==1):
for led in base.leds:
led.off()
sleep(Delay2)
for led in base.leds:
led.toggle()
sleep(Delay2)
elif (base.buttons[2].read()==1):
for led in reversed(base.leds):
led.off()
sleep(Delay2)
for led in reversed(base.leds):
led.toggle()
sleep(Delay2)
print('End of this demo ...')
for led in base.leds:
led.off()
for led in rgbled_position:
base.rgbleds[led].off()
###Output
End of this demo ...
|
big-data/hadoop-streaming.ipynb | ###Markdown
Hadoop – Streaminghttps://www.tutorialspoint.com/hadoop/hadoop_streaming.htmThe code in the above tutorial doesn't work (incorrect, Python 2.7) on the Bitnami Hadoop VM version 3.3.0 (October 2020).Use the following code as `mapper.py` and `reducer.py`:
###Code
#!/usr/bin/env python3
import sys
for line in sys.stdin:
words = line.strip().split(' ')
for word in words:
print(f'{word}\t1')
#!/usr/bin/env python3
import sys
counts = {}
for line in sys.stdin:
word, count = line.strip().split('\t')
try:
count = int(count)
counts[word] = counts.get(word, 0) + count
except:
pass
for (word, count) in counts.items():
print(f'{word}\t{count}')
###Output
_____no_output_____ |
examples/Load_example_datasets.ipynb | ###Markdown
Load datasets used in the manuscript "A Swiss-Army Knife for Hierarchical Modeling of Biological Systems" (Yu et al.)
###Code
import ddot
from ddot import Ontology
###Output
_____no_output_____
###Markdown
Gene-disease associations from Monarch Initiative
###Code
# Retrieve a table of gene-disease associations from the Monarch Initiative (reformatted and stored on NDEx)
monarch, _ = ddot.ndex_to_sim_matrix(
ndex_url=ddot.MONARCH_DISEASE_GENE_SLIM_URL,
input_fmt='cx',
output_fmt='sparse')
monarch.head()
# Example: get the known genes for "Caffey Disease"
seed = monarch.loc[monarch['disease']=='caffey_disease', 'gene'].tolist()
print('Seed:', seed)
###Output
Seed: ['COL1A1', 'A4GALT']
###Markdown
Human gene-gene similarity network
###Code
# Install the simplejson package (it is recommend you run this in a separate bash terminal, not in this Jupyter notebook. If you want to use a conda virtual environment, then you first need to activate the environment)
! pip install simplejson
## Download human gene-gene similarity network from NDEx
## -- WARNING: This network is very large (19,009-by-19,009 matrix).
## -- *** Requires ~6 GB of RAM to download and process ***
## -- *** ~4 GB of data is downloaded from NDEx, which takes ~10 min for a fast internet connection ***
## -- This requires the simplejson package (see previous cell)
sim, sim_names = ddot.ndex_to_sim_matrix(
ndex_url=ddot.HUMAN_GENE_SIMILARITIES_URL,
input_fmt='cx_matrix',
output_fmt='matrix')
import pandas as pd
sim = pd.DataFrame(sim, columns=sim_names, index=sim_names)
sim.head()
###Output
NDEx download and CX parse time (sec): 356.6890811920166
Dim: (19009, 19009)
Bytes: 2890736648
Iterate through CX and construct array time (sec): 14.676801204681396
###Markdown
The Gene Ontology
###Code
# Read Gene Ontology from NDEx.
# -- This version has been pre-processed to contain a non-redundant set of GO terms and connections that are relevant to human genes (see Process_the_Gene_Ontology.ipynb)
go_human = Ontology.from_ndex(ddot.GO_HUMAN_URL)
print(go_human)
###Output
19015 genes, 19343 terms, 215488 gene-term relations, 36362 term-term relations
node_attributes: ['Branch', 'Vis:Shape', 'name', 'Vis:Fill Color', 'Vis:Border Paint', 'Term_Description']
edge_attributes: ['Vis:Visible']
###Markdown
Fanconi Anemia gene ontology (FanGO)
###Code
fango = Ontology.from_ndex(ddot.FANGO_URL)
print(fango)
###Output
349 genes, 110 terms, 349 gene-term relations, 109 term-term relations
node_attributes: ['Hidden', 'Similarity_to_seed', 'Seed', 'is_collect_node', 'Display:Aligned_Term', 'Display:Aligned_FDR', 'Display:Aligned_Term_Description', 'name', 'Vis:Border Paint', 'Display:Parent weight', 'Display:Aligned_Similarity', 'Parent weight', 'Original_Name', 'ndex:internalLink', 'Aligned_Term', 'Aligned_Term_Description', 'Aligned_FDR', 'Vis:Shape', 'Vis:Fill Color', 'Aligned_Similarity']
edge_attributes: ['Vis:EDGE_TARGET_ARROW_SHAPE', 'Vis:EDGE_SOURCE_ARROW_SHAPE', 'CLIXO_score', 'Vis:Visible']
###Markdown
Other disease gene ontologies (based on gene-disease associations in Monarch Initiative)
###Code
import pandas as pd
df = pd.read_table('disease_gene_ontologies.txt', header=0, index_col=False)
df = df.set_index('Disease')
df.head()
# Example: get the URL to view the disease "hydronephrosis" on HiView
print(df.loc['hydronephrosis', 'HiView_URL'])
###Output
http://hiview.ucsd.edu/1b21bc44-f775-11e8-aaa6-0ac135e8bacf?type=public&server=http://public.ndexbio.org
|
Notebook/SPA WIkidata.ipynb | ###Markdown
Exempel hämta 5 poster från WIkidata som är kopplade till SPA (WD egenskap [P4819](https://www.wikidata.org/wiki/Property:P4819?uselang=sv)) med Python * se även [video](https://youtu.be/3FeZP8lqW7g)* SPARQL https://w.wiki/4HnJ* denna [Notebook](https://github.com/salgo60/spa2Commons/blob/main/Notebook/SPA%20WIkidata.ipynb) och relaterad [salgo60/spa2Commons/issues/9](https://github.com/salgo60/spa2Commons/issues/9)
###Code
# pip install sparqlwrapper
# https://rdflib.github.io/sparqlwrapper/
import sys
from SPARQLWrapper import SPARQLWrapper, JSON
endpoint_url = "https://query.wikidata.org/sparql"
query = """#title Wikidata med egneskap SPA = P4819
SELECT ?item ?itemLabel ?SPA_P4819
{
?item wdt:P4819 ?SPA_P4819
SERVICE wikibase:label { bd:serviceParam wikibase:language "[AUTO_LANGUAGE],en". }
}
ORDER BY DESC(?itemLabel)
limit 5"""
def get_results(endpoint_url, query):
user_agent = "WDQS-example Python/%s.%s" % (sys.version_info[0], sys.version_info[1])
# TODO adjust user agent; see https://w.wiki/CX6
sparql = SPARQLWrapper(endpoint_url, agent=user_agent)
sparql.setQuery(query)
sparql.setReturnFormat(JSON)
return sparql.query().convert()
results = get_results(endpoint_url, query)
for result in results["results"]["bindings"]:
print(result)
###Output
{'item': {'type': 'uri', 'value': 'http://www.wikidata.org/entity/Q307693'}, 'SPA_P4819': {'type': 'literal', 'value': 'sj9PGLAlnmUAAAAAABUkSQ'}, 'itemLabel': {'xml:lang': 'en', 'type': 'literal', 'value': 'Öyvind Fahlström'}}
{'item': {'type': 'uri', 'value': 'http://www.wikidata.org/entity/Q289555'}, 'SPA_P4819': {'type': 'literal', 'value': 'ciLMGSqrYjAAAAAAAAAbsw'}, 'itemLabel': {'xml:lang': 'en', 'type': 'literal', 'value': 'Östen Warnerbring'}}
{'item': {'type': 'uri', 'value': 'http://www.wikidata.org/entity/Q298317'}, 'SPA_P4819': {'type': 'literal', 'value': '5TJc-sPXaKAAAAAAAAAnbg'}, 'itemLabel': {'xml:lang': 'en', 'type': 'literal', 'value': 'Östen Undén'}}
{'item': {'type': 'uri', 'value': 'http://www.wikidata.org/entity/Q298308'}, 'SPA_P4819': {'type': 'literal', 'value': 'TNQaWo324IAAAAAAAADNrA'}, 'itemLabel': {'xml:lang': 'en', 'type': 'literal', 'value': 'Östen Bergstrand'}}
{'item': {'type': 'uri', 'value': 'http://www.wikidata.org/entity/Q8079017'}, 'SPA_P4819': {'type': 'literal', 'value': 'sj9PGLAlnmUAAAAAABhuEA'}, 'itemLabel': {'xml:lang': 'en', 'type': 'literal', 'value': 'Örjan Lüning'}}
|
1b_prep_ltr_knn_search.ipynb | ###Markdown
Gera três dicionarios em que a chave é o item_id e os valores são title, price e domain_id
###Code
item_title_map = item_data[['item_id', 'title']].drop_duplicates()
item_title_map = item_title_map.set_index("item_id").squeeze().to_dict()
item_price_map = item_data[['item_id', 'price']].drop_duplicates()
item_price_map = item_price_map.set_index("item_id").squeeze().to_dict()
item_domain_map = item_data[['item_id', 'domain_id']].drop_duplicates()
item_domain_map = item_domain_map.set_index("item_id").squeeze().to_dict()
###Output
_____no_output_____
###Markdown
knn Importa os indices do knnDados de treino: features dos word embedings dos nomes dos items
###Code
%%time
import nmslib
index = nmslib.init()
index.loadIndex('22a_sbert_neuralmind.nms')
###Output
_____no_output_____
###Markdown
Importa as features dos word embedings dos nomes dos items e cria um dicionário associando cada item_id aos valores
###Code
embs_np = joblib.load("22a_embs_np.pkl.z")
item_emb_map = {t: embs_np[i] for i, t in enumerate(item_data['item_id'].values)}
k=50
###Output
_____no_output_____
###Markdown
train Estruturacao dos dados adicionando info do item (join manual) e novas features
###Code
%%time
data = []
seq_index = 0
for hist, bought in tqdm.tqdm(train[['user_history', 'item_bought']].values):
recall = False
last_ts = None
seq = 0
ts = 0
rep = dict()
for item in json.loads(hist):
i = item['event_info']
# Adiciona o id, titulo, preco e domain_id do produto comprado
item['bought_id'] = bought
item['bought_title'] = item_title_map[bought]
item['bought_price'] = item_price_map[bought]
item['bought_domain'] = item_domain_map[bought]
# Adiciona info do produto visto:
# titulo, preco, domain_id, dummy do produto visto igual ao comprado, dummy pt
if item['event_type'] == 'view':
item['item_title'] = item_title_map[i]
item['item_price'] = item_price_map[i]
item['item_domain'] = item_domain_map[i]
item['has_bought'] = int(bought == i)
item['pt'] = int('MLB' in item['item_domain']) if item['item_domain'] else np.nan
item['viewed'] = 1
# Adiciona features do word embeding do nome do item
rep[i] = item_emb_map[i]
# Indice do item do usuario e entre usuarios
item['seq_pos'] = seq
item['seq_index'] = seq_index
seq += 1
data.append(item)
lrep = list(rep.values())
if len(lrep) == 0:
view_embedding_mean = embs_search_np[seq_index, :] #search para quem nao tem views
else:
view_embedding_mean = np.mean(lrep, axis=0)
for neighbor in index.knnQuery(view_embedding_mean, k=k)[0]: #features dos nomes dos itens
item = dict()
i = neighbor
# Adiciona informacoes dos itens similares
item['event_info'] = neighbor
item['event_type'] = 'knn'
item['bought_id'] = bought
item['bought_title'] = item_title_map[bought]
item['bought_price'] = item_price_map[bought]
item['bought_domain'] = item_domain_map[bought]
item['item_title'] = item_title_map[i]
item['item_price'] = item_price_map[i]
item['item_domain'] = item_domain_map[i]
item['has_bought'] = int(bought == i)
item['pt'] = int('MLB' in item['item_domain']) if item['item_domain'] else np.nan
item['seq_pos'] = -1
item['seq_index'] = seq_index
item['viewed'] = 0
data.append(item)
seq_index += 1
df = pd.DataFrame(data)
del data, embs_search_np
gc.collect()
df['event_timestamp'] = pd.to_datetime(df['event_timestamp']).dt.tz_localize(None)
df[df['event_type'] != 'search'].to_parquet("./data/22_train_view_melted.parquet",engine='fastparquet', compression=None)
df[df['event_type'] == 'search'].to_parquet("./data/22_train_search_melted.parquet",engine='fastparquet', compression=None)
df.head()
%%time
data = []
seq_index = 0
for hist, bought in tqdm.tqdm(train[['user_history', 'item_bought']].values):
recall = False
last_ts = None
seq = 0
ts = 0
rep = dict()
for item in hist:
i = item['event_info']
item['bought_id'] = bought
item['bought_title'] = item_title_map[bought]
item['bought_price'] = item_price_map[bought]
item['bought_domain'] = item_domain_map[bought]
if item['event_type'] == 'view':
item['item_title'] = item_title_map[i]
item['item_price'] = item_price_map[i]
item['item_domain'] = item_domain_map[i]
item['has_bought'] = int(bought == i)
item['pt'] = int('MLB' in item['item_domain']) if item['item_domain'] else np.nan
print(item)
data.append(item)
pd.DataFrame(data).head()
###Output
_____no_output_____
###Markdown
test Estruturacao dos dados adicionando info do item (join manual) e novas features
###Code
embs_search_np = joblib.load("22a_embs_search_test_np.pkl.z")
# last k item matches bought item
data = []
seq_index = 0
for hist in tqdm.tqdm(test['user_history'].values):
last_ts = None
seq = 0
ts = 0
rep = dict()
for item in json.loads(hist):
i = item['event_info']
if item['event_type'] == 'view':
item['item_title'] = item_title_map[i]
item['item_price'] = item_price_map[i]
item['item_domain'] = item_domain_map[i]
item['pt'] = int('MLB' in item['item_domain']) if item['item_domain'] else np.nan
item['viewed'] = 1
rep[i] = item_emb_map[i]
item['seq_pos'] = seq
item['seq_index'] = seq_index
seq += 1
data.append(item)
lrep = list(rep.values())
if len(lrep) == 0:
view_embedding_mean = embs_search_np[seq_index, :]
else:
view_embedding_mean = np.mean(lrep, axis=0)
for neighbor in index.knnQuery(view_embedding_mean, k=k)[0]:
item = dict()
i = neighbor
item['event_info'] = neighbor
item['event_type'] = 'knn'
item['item_title'] = item_title_map[i]
item['item_price'] = item_price_map[i]
item['item_domain'] = item_domain_map[i]
item['pt'] = int('MLB' in item['item_domain']) if item['item_domain'] else np.nan
item['seq_pos'] = -1
item['seq_index'] = seq_index
item['viewed'] = 0
data.append(item)
seq_index += 1
df = pd.DataFrame(data)
del data, embs_search_np, embs_np, item_emb_map
gc.collect()
df['event_timestamp'] = pd.to_datetime(df['event_timestamp']).dt.tz_localize(None)
df[df['event_type'] != 'search'].to_parquet("./data/22_test_view_melted.parquet",engine='fastparquet', compression=None)
df[df['event_type'] == 'search'].to_parquet("./data/22_test_search_melted.parquet",engine='fastparquet', compression=None)
df.head()
###Output
_____no_output_____
###Markdown
knn
###Code
%%time
import nmslib
index = nmslib.init()
index.loadIndex('22a_sbert_neuralmind.nms')
embs_np = joblib.load("22a_embs_np.pkl.z")
item_emb_map = {t: embs_np[i] for i, t in enumerate(item_data['item_id'].values)}
embs_search_np = joblib.load("22a_embs_search_np.pkl.z")
k=50
###Output
_____no_output_____
###Markdown
train
###Code
%%time
data = []
seq_index = 0
for hist, bought in tqdm.tqdm(train[['user_history', 'item_bought']].values):
recall = False
last_ts = None
seq = 0
ts = 0
rep = dict()
for item in json.loads(hist):
i = item['event_info']
item['bought_id'] = bought
item['bought_title'] = item_title_map[bought]
item['bought_price'] = item_price_map[bought]
item['bought_domain'] = item_domain_map[bought]
if item['event_type'] == 'view':
item['item_title'] = item_title_map[i]
item['item_price'] = item_price_map[i]
item['item_domain'] = item_domain_map[i]
item['has_bought'] = int(bought == i)
item['pt'] = int('MLB' in item['item_domain']) if item['item_domain'] else np.nan
item['viewed'] = 1
rep[i] = item_emb_map[i]
item['seq_pos'] = seq
item['seq_index'] = seq_index
seq += 1
data.append(item)
lrep = list(rep.values())
if len(lrep) == 0:
view_embedding_mean = embs_search_np[seq_index, :] #search para quem nao tem views
else:
view_embedding_mean = np.mean(lrep, axis=0)
for neighbor in index.knnQuery(view_embedding_mean, k=k)[0]:
item = dict()
i = neighbor
item['event_info'] = neighbor
item['event_type'] = 'knn'
item['bought_id'] = bought
item['bought_title'] = item_title_map[bought]
item['bought_price'] = item_price_map[bought]
item['bought_domain'] = item_domain_map[bought]
item['item_title'] = item_title_map[i]
item['item_price'] = item_price_map[i]
item['item_domain'] = item_domain_map[i]
item['has_bought'] = int(bought == i)
item['pt'] = int('MLB' in item['item_domain']) if item['item_domain'] else np.nan
item['seq_pos'] = -1
item['seq_index'] = seq_index
item['viewed'] = 0
data.append(item)
seq_index += 1
df = pd.DataFrame(data)
del data, embs_search_np
gc.collect()
df['event_timestamp'] = pd.to_datetime(df['event_timestamp']).dt.tz_localize(None)
df[df['event_type'] != 'search'].to_parquet("./data/22_train_view_melted.parquet",engine='fastparquet', compression=None)
df[df['event_type'] == 'search'].to_parquet("./data/22_train_search_melted.parquet",engine='fastparquet', compression=None)
df.head()
###Output
_____no_output_____
###Markdown
test
###Code
embs_search_np = joblib.load("22a_embs_search_test_np.pkl.z")
# last k item matches bought item
data = []
seq_index = 0
for hist in tqdm.tqdm(test['user_history'].values):
last_ts = None
seq = 0
ts = 0
rep = dict()
for item in json.loads(hist):
i = item['event_info']
if item['event_type'] == 'view':
item['item_title'] = item_title_map[i]
item['item_price'] = item_price_map[i]
item['item_domain'] = item_domain_map[i]
item['pt'] = int('MLB' in item['item_domain']) if item['item_domain'] else np.nan
item['viewed'] = 1
rep[i] = item_emb_map[i]
item['seq_pos'] = seq
item['seq_index'] = seq_index
seq += 1
data.append(item)
lrep = list(rep.values())
if len(lrep) == 0:
view_embedding_mean = embs_search_np[seq_index, :]
else:
view_embedding_mean = np.mean(lrep, axis=0)
for neighbor in index.knnQuery(view_embedding_mean, k=k)[0]:
item = dict()
i = neighbor
item['event_info'] = neighbor
item['event_type'] = 'knn'
item['item_title'] = item_title_map[i]
item['item_price'] = item_price_map[i]
item['item_domain'] = item_domain_map[i]
item['pt'] = int('MLB' in item['item_domain']) if item['item_domain'] else np.nan
item['seq_pos'] = -1
item['seq_index'] = seq_index
item['viewed'] = 0
data.append(item)
seq_index += 1
df = pd.DataFrame(data)
del data, embs_search_np, embs_np, item_emb_map
gc.collect()
df['event_timestamp'] = pd.to_datetime(df['event_timestamp']).dt.tz_localize(None)
df[df['event_type'] != 'search'].to_parquet("./data/22_test_view_melted.parquet",engine='fastparquet', compression=None)
df[df['event_type'] == 'search'].to_parquet("./data/22_test_search_melted.parquet",engine='fastparquet', compression=None)
df.head()
###Output
_____no_output_____ |
DeepLabV3+_ResNet_Backend.ipynb | ###Markdown
###Code
from tensorflow.keras.layers import Conv2D,BatchNormalization,UpSampling2D,Concatenate,Activation,AveragePooling2D
import os
from tensorflow.keras.layers import Input,Conv2DTranspose
from tensorflow.keras.applications import ResNet50
from tensorflow.keras.models import Model
###Output
_____no_output_____
###Markdown
**DeepLabV3Plus**> Indented block
###Code
#Pyramid pooling aspp
#image_pooling->1d conv-->dilated conv with b8=>16=>32
def ASPP(inputs):
#First entire shape pooling
shape=inputs.shape
y_pool=AveragePooling2D(pool_size=(shape[1],shape[2]),name='average_pooling')(inputs)
y_pool=Conv2D(filters=256,kernel_size=1,use_bias=False,padding='same')(y_pool)
y_pool=BatchNormalization()(y_pool)
y_pool=Activation(activation='relu')(y_pool)
y_pool=UpSampling2D(size=(shape[1],shape[2]),interpolation='bilinear')(y_pool)
#print(y_pool.shape)
#Now 1-d Channelwise convolution
y_1=Conv2D(filters=256,kernel_size=1,use_bias=False,padding='same',dilation_rate=1)(inputs)
y_1=BatchNormalization()(y_1)
y_1=Activation(activation='relu')(y_1)
#Now with dilationrate=6
y_6=Conv2D(filters=256,kernel_size=3,use_bias=False,padding='same',dilation_rate=6)(inputs)
y_6=BatchNormalization()(y_6)
y_6=Activation(activation='relu')(y_6)
#Now with dilationrate=12
y_12=Conv2D(filters=256,kernel_size=3,use_bias=False,padding='same',dilation_rate=12)(inputs)
y_12=BatchNormalization()(y_12)
y_12=Activation(activation='relu')(y_12)
#Now with dilation rate=18
y_18=Conv2D(filters=256,kernel_size=3,use_bias=False,padding='same',dilation_rate=18)(inputs)
y_18=BatchNormalization()(y_18)
y_18=Activation(activation='relu')(y_18)
y=Concatenate()([y_pool,y_1,y_6,y_12,y_18])
#1-d convolution application
y=Conv2D(filters=256,kernel_size=1,padding='same',dilation_rate=1,use_bias=False)(y)
y=BatchNormalization()(y)
y=Activation(activation='relu')(y)
#print(y.shape)
return y
def DeepLabv3plus(shape):
"""
input shape is given as a tuple generate a deeplabv3 model
"""
input=Input(shape)
base_model=ResNet50(include_top=False,weights='imagenet',input_tensor=input)
image_features=base_model.get_layer('conv4_block6_out').output
#Now we will perform atrous asymmetric pyramid pooling
x_a=ASPP(image_features)
x_a=UpSampling2D(size=(4,4),interpolation='bilinear')(x_a)
#Now we will get low level features from our resnet model
x_b=base_model.get_layer('conv2_block2_out').output
print(x_b.shape)
x_b=Conv2D(filters=48,kernel_size=1,padding='same',use_bias=False)(x_b)
x_b=BatchNormalization()(x_b)
x_b=Activation(activation='relu')(x_b)
print(x_b.shape)
#Now we will concatenate
x=Concatenate()([x_a,x_b])
#print(x.shape)
#Now apply convolutional layer with 3*3 filter 2 times
x=Conv2D(filters=256,kernel_size=1,padding='same',use_bias=False)(x)
x=BatchNormalization()(x)
x=Activation(activation='relu')(x)
x=Conv2D(filters=256,kernel_size=1,padding='same',use_bias=False)(x)
x-BatchNormalization()(x)
x=Activation(activation='relu')(x)
x=UpSampling2D(size=(4,4),interpolation='bilinear')(x)
#print(x.shape)
#outputs
x=Conv2D(1,(1,1),name='output_layer')(x)
x=Activation(activation='sigmoid')(x)
#print(x.shape)
#Model
model=Model(inputs=input,outputs=x)
return model
if __name__=='__main__':
shape=(256,256,3)
model=DeepLabv3plus(shape)
#model.summary()
a_model=ResNet50(include_top=False,weights='imagenet',input_shape=(256,256,3))
a_model.summary()
###Output
Model: "resnet50"
__________________________________________________________________________________________________
Layer (type) Output Shape Param # Connected to
==================================================================================================
input_21 (InputLayer) [(None, 256, 256, 3 0 []
)]
conv1_pad (ZeroPadding2D) (None, 262, 262, 3) 0 ['input_21[0][0]']
conv1_conv (Conv2D) (None, 128, 128, 64 9472 ['conv1_pad[0][0]']
)
conv1_bn (BatchNormalization) (None, 128, 128, 64 256 ['conv1_conv[0][0]']
)
conv1_relu (Activation) (None, 128, 128, 64 0 ['conv1_bn[0][0]']
)
pool1_pad (ZeroPadding2D) (None, 130, 130, 64 0 ['conv1_relu[0][0]']
)
pool1_pool (MaxPooling2D) (None, 64, 64, 64) 0 ['pool1_pad[0][0]']
conv2_block1_1_conv (Conv2D) (None, 64, 64, 64) 4160 ['pool1_pool[0][0]']
conv2_block1_1_bn (BatchNormal (None, 64, 64, 64) 256 ['conv2_block1_1_conv[0][0]']
ization)
conv2_block1_1_relu (Activatio (None, 64, 64, 64) 0 ['conv2_block1_1_bn[0][0]']
n)
conv2_block1_2_conv (Conv2D) (None, 64, 64, 64) 36928 ['conv2_block1_1_relu[0][0]']
conv2_block1_2_bn (BatchNormal (None, 64, 64, 64) 256 ['conv2_block1_2_conv[0][0]']
ization)
conv2_block1_2_relu (Activatio (None, 64, 64, 64) 0 ['conv2_block1_2_bn[0][0]']
n)
conv2_block1_0_conv (Conv2D) (None, 64, 64, 256) 16640 ['pool1_pool[0][0]']
conv2_block1_3_conv (Conv2D) (None, 64, 64, 256) 16640 ['conv2_block1_2_relu[0][0]']
conv2_block1_0_bn (BatchNormal (None, 64, 64, 256) 1024 ['conv2_block1_0_conv[0][0]']
ization)
conv2_block1_3_bn (BatchNormal (None, 64, 64, 256) 1024 ['conv2_block1_3_conv[0][0]']
ization)
conv2_block1_add (Add) (None, 64, 64, 256) 0 ['conv2_block1_0_bn[0][0]',
'conv2_block1_3_bn[0][0]']
conv2_block1_out (Activation) (None, 64, 64, 256) 0 ['conv2_block1_add[0][0]']
conv2_block2_1_conv (Conv2D) (None, 64, 64, 64) 16448 ['conv2_block1_out[0][0]']
conv2_block2_1_bn (BatchNormal (None, 64, 64, 64) 256 ['conv2_block2_1_conv[0][0]']
ization)
conv2_block2_1_relu (Activatio (None, 64, 64, 64) 0 ['conv2_block2_1_bn[0][0]']
n)
conv2_block2_2_conv (Conv2D) (None, 64, 64, 64) 36928 ['conv2_block2_1_relu[0][0]']
conv2_block2_2_bn (BatchNormal (None, 64, 64, 64) 256 ['conv2_block2_2_conv[0][0]']
ization)
conv2_block2_2_relu (Activatio (None, 64, 64, 64) 0 ['conv2_block2_2_bn[0][0]']
n)
conv2_block2_3_conv (Conv2D) (None, 64, 64, 256) 16640 ['conv2_block2_2_relu[0][0]']
conv2_block2_3_bn (BatchNormal (None, 64, 64, 256) 1024 ['conv2_block2_3_conv[0][0]']
ization)
conv2_block2_add (Add) (None, 64, 64, 256) 0 ['conv2_block1_out[0][0]',
'conv2_block2_3_bn[0][0]']
conv2_block2_out (Activation) (None, 64, 64, 256) 0 ['conv2_block2_add[0][0]']
conv2_block3_1_conv (Conv2D) (None, 64, 64, 64) 16448 ['conv2_block2_out[0][0]']
conv2_block3_1_bn (BatchNormal (None, 64, 64, 64) 256 ['conv2_block3_1_conv[0][0]']
ization)
conv2_block3_1_relu (Activatio (None, 64, 64, 64) 0 ['conv2_block3_1_bn[0][0]']
n)
conv2_block3_2_conv (Conv2D) (None, 64, 64, 64) 36928 ['conv2_block3_1_relu[0][0]']
conv2_block3_2_bn (BatchNormal (None, 64, 64, 64) 256 ['conv2_block3_2_conv[0][0]']
ization)
conv2_block3_2_relu (Activatio (None, 64, 64, 64) 0 ['conv2_block3_2_bn[0][0]']
n)
conv2_block3_3_conv (Conv2D) (None, 64, 64, 256) 16640 ['conv2_block3_2_relu[0][0]']
conv2_block3_3_bn (BatchNormal (None, 64, 64, 256) 1024 ['conv2_block3_3_conv[0][0]']
ization)
conv2_block3_add (Add) (None, 64, 64, 256) 0 ['conv2_block2_out[0][0]',
'conv2_block3_3_bn[0][0]']
conv2_block3_out (Activation) (None, 64, 64, 256) 0 ['conv2_block3_add[0][0]']
conv3_block1_1_conv (Conv2D) (None, 32, 32, 128) 32896 ['conv2_block3_out[0][0]']
conv3_block1_1_bn (BatchNormal (None, 32, 32, 128) 512 ['conv3_block1_1_conv[0][0]']
ization)
conv3_block1_1_relu (Activatio (None, 32, 32, 128) 0 ['conv3_block1_1_bn[0][0]']
n)
conv3_block1_2_conv (Conv2D) (None, 32, 32, 128) 147584 ['conv3_block1_1_relu[0][0]']
conv3_block1_2_bn (BatchNormal (None, 32, 32, 128) 512 ['conv3_block1_2_conv[0][0]']
ization)
conv3_block1_2_relu (Activatio (None, 32, 32, 128) 0 ['conv3_block1_2_bn[0][0]']
n)
conv3_block1_0_conv (Conv2D) (None, 32, 32, 512) 131584 ['conv2_block3_out[0][0]']
conv3_block1_3_conv (Conv2D) (None, 32, 32, 512) 66048 ['conv3_block1_2_relu[0][0]']
conv3_block1_0_bn (BatchNormal (None, 32, 32, 512) 2048 ['conv3_block1_0_conv[0][0]']
ization)
conv3_block1_3_bn (BatchNormal (None, 32, 32, 512) 2048 ['conv3_block1_3_conv[0][0]']
ization)
conv3_block1_add (Add) (None, 32, 32, 512) 0 ['conv3_block1_0_bn[0][0]',
'conv3_block1_3_bn[0][0]']
conv3_block1_out (Activation) (None, 32, 32, 512) 0 ['conv3_block1_add[0][0]']
conv3_block2_1_conv (Conv2D) (None, 32, 32, 128) 65664 ['conv3_block1_out[0][0]']
conv3_block2_1_bn (BatchNormal (None, 32, 32, 128) 512 ['conv3_block2_1_conv[0][0]']
ization)
conv3_block2_1_relu (Activatio (None, 32, 32, 128) 0 ['conv3_block2_1_bn[0][0]']
n)
conv3_block2_2_conv (Conv2D) (None, 32, 32, 128) 147584 ['conv3_block2_1_relu[0][0]']
conv3_block2_2_bn (BatchNormal (None, 32, 32, 128) 512 ['conv3_block2_2_conv[0][0]']
ization)
conv3_block2_2_relu (Activatio (None, 32, 32, 128) 0 ['conv3_block2_2_bn[0][0]']
n)
conv3_block2_3_conv (Conv2D) (None, 32, 32, 512) 66048 ['conv3_block2_2_relu[0][0]']
conv3_block2_3_bn (BatchNormal (None, 32, 32, 512) 2048 ['conv3_block2_3_conv[0][0]']
ization)
conv3_block2_add (Add) (None, 32, 32, 512) 0 ['conv3_block1_out[0][0]',
'conv3_block2_3_bn[0][0]']
conv3_block2_out (Activation) (None, 32, 32, 512) 0 ['conv3_block2_add[0][0]']
conv3_block3_1_conv (Conv2D) (None, 32, 32, 128) 65664 ['conv3_block2_out[0][0]']
conv3_block3_1_bn (BatchNormal (None, 32, 32, 128) 512 ['conv3_block3_1_conv[0][0]']
ization)
conv3_block3_1_relu (Activatio (None, 32, 32, 128) 0 ['conv3_block3_1_bn[0][0]']
n)
conv3_block3_2_conv (Conv2D) (None, 32, 32, 128) 147584 ['conv3_block3_1_relu[0][0]']
conv3_block3_2_bn (BatchNormal (None, 32, 32, 128) 512 ['conv3_block3_2_conv[0][0]']
ization)
conv3_block3_2_relu (Activatio (None, 32, 32, 128) 0 ['conv3_block3_2_bn[0][0]']
n)
conv3_block3_3_conv (Conv2D) (None, 32, 32, 512) 66048 ['conv3_block3_2_relu[0][0]']
conv3_block3_3_bn (BatchNormal (None, 32, 32, 512) 2048 ['conv3_block3_3_conv[0][0]']
ization)
conv3_block3_add (Add) (None, 32, 32, 512) 0 ['conv3_block2_out[0][0]',
'conv3_block3_3_bn[0][0]']
conv3_block3_out (Activation) (None, 32, 32, 512) 0 ['conv3_block3_add[0][0]']
conv3_block4_1_conv (Conv2D) (None, 32, 32, 128) 65664 ['conv3_block3_out[0][0]']
conv3_block4_1_bn (BatchNormal (None, 32, 32, 128) 512 ['conv3_block4_1_conv[0][0]']
ization)
conv3_block4_1_relu (Activatio (None, 32, 32, 128) 0 ['conv3_block4_1_bn[0][0]']
n)
conv3_block4_2_conv (Conv2D) (None, 32, 32, 128) 147584 ['conv3_block4_1_relu[0][0]']
conv3_block4_2_bn (BatchNormal (None, 32, 32, 128) 512 ['conv3_block4_2_conv[0][0]']
ization)
conv3_block4_2_relu (Activatio (None, 32, 32, 128) 0 ['conv3_block4_2_bn[0][0]']
n)
conv3_block4_3_conv (Conv2D) (None, 32, 32, 512) 66048 ['conv3_block4_2_relu[0][0]']
conv3_block4_3_bn (BatchNormal (None, 32, 32, 512) 2048 ['conv3_block4_3_conv[0][0]']
ization)
conv3_block4_add (Add) (None, 32, 32, 512) 0 ['conv3_block3_out[0][0]',
'conv3_block4_3_bn[0][0]']
conv3_block4_out (Activation) (None, 32, 32, 512) 0 ['conv3_block4_add[0][0]']
conv4_block1_1_conv (Conv2D) (None, 16, 16, 256) 131328 ['conv3_block4_out[0][0]']
conv4_block1_1_bn (BatchNormal (None, 16, 16, 256) 1024 ['conv4_block1_1_conv[0][0]']
ization)
conv4_block1_1_relu (Activatio (None, 16, 16, 256) 0 ['conv4_block1_1_bn[0][0]']
n)
conv4_block1_2_conv (Conv2D) (None, 16, 16, 256) 590080 ['conv4_block1_1_relu[0][0]']
conv4_block1_2_bn (BatchNormal (None, 16, 16, 256) 1024 ['conv4_block1_2_conv[0][0]']
ization)
conv4_block1_2_relu (Activatio (None, 16, 16, 256) 0 ['conv4_block1_2_bn[0][0]']
n)
conv4_block1_0_conv (Conv2D) (None, 16, 16, 1024 525312 ['conv3_block4_out[0][0]']
)
conv4_block1_3_conv (Conv2D) (None, 16, 16, 1024 263168 ['conv4_block1_2_relu[0][0]']
)
conv4_block1_0_bn (BatchNormal (None, 16, 16, 1024 4096 ['conv4_block1_0_conv[0][0]']
ization) )
conv4_block1_3_bn (BatchNormal (None, 16, 16, 1024 4096 ['conv4_block1_3_conv[0][0]']
ization) )
conv4_block1_add (Add) (None, 16, 16, 1024 0 ['conv4_block1_0_bn[0][0]',
) 'conv4_block1_3_bn[0][0]']
conv4_block1_out (Activation) (None, 16, 16, 1024 0 ['conv4_block1_add[0][0]']
)
conv4_block2_1_conv (Conv2D) (None, 16, 16, 256) 262400 ['conv4_block1_out[0][0]']
conv4_block2_1_bn (BatchNormal (None, 16, 16, 256) 1024 ['conv4_block2_1_conv[0][0]']
ization)
conv4_block2_1_relu (Activatio (None, 16, 16, 256) 0 ['conv4_block2_1_bn[0][0]']
n)
conv4_block2_2_conv (Conv2D) (None, 16, 16, 256) 590080 ['conv4_block2_1_relu[0][0]']
conv4_block2_2_bn (BatchNormal (None, 16, 16, 256) 1024 ['conv4_block2_2_conv[0][0]']
ization)
conv4_block2_2_relu (Activatio (None, 16, 16, 256) 0 ['conv4_block2_2_bn[0][0]']
n)
conv4_block2_3_conv (Conv2D) (None, 16, 16, 1024 263168 ['conv4_block2_2_relu[0][0]']
)
conv4_block2_3_bn (BatchNormal (None, 16, 16, 1024 4096 ['conv4_block2_3_conv[0][0]']
ization) )
conv4_block2_add (Add) (None, 16, 16, 1024 0 ['conv4_block1_out[0][0]',
) 'conv4_block2_3_bn[0][0]']
conv4_block2_out (Activation) (None, 16, 16, 1024 0 ['conv4_block2_add[0][0]']
)
conv4_block3_1_conv (Conv2D) (None, 16, 16, 256) 262400 ['conv4_block2_out[0][0]']
conv4_block3_1_bn (BatchNormal (None, 16, 16, 256) 1024 ['conv4_block3_1_conv[0][0]']
ization)
conv4_block3_1_relu (Activatio (None, 16, 16, 256) 0 ['conv4_block3_1_bn[0][0]']
n)
conv4_block3_2_conv (Conv2D) (None, 16, 16, 256) 590080 ['conv4_block3_1_relu[0][0]']
conv4_block3_2_bn (BatchNormal (None, 16, 16, 256) 1024 ['conv4_block3_2_conv[0][0]']
ization)
conv4_block3_2_relu (Activatio (None, 16, 16, 256) 0 ['conv4_block3_2_bn[0][0]']
n)
conv4_block3_3_conv (Conv2D) (None, 16, 16, 1024 263168 ['conv4_block3_2_relu[0][0]']
)
conv4_block3_3_bn (BatchNormal (None, 16, 16, 1024 4096 ['conv4_block3_3_conv[0][0]']
ization) )
conv4_block3_add (Add) (None, 16, 16, 1024 0 ['conv4_block2_out[0][0]',
) 'conv4_block3_3_bn[0][0]']
conv4_block3_out (Activation) (None, 16, 16, 1024 0 ['conv4_block3_add[0][0]']
)
conv4_block4_1_conv (Conv2D) (None, 16, 16, 256) 262400 ['conv4_block3_out[0][0]']
conv4_block4_1_bn (BatchNormal (None, 16, 16, 256) 1024 ['conv4_block4_1_conv[0][0]']
ization)
conv4_block4_1_relu (Activatio (None, 16, 16, 256) 0 ['conv4_block4_1_bn[0][0]']
n)
conv4_block4_2_conv (Conv2D) (None, 16, 16, 256) 590080 ['conv4_block4_1_relu[0][0]']
conv4_block4_2_bn (BatchNormal (None, 16, 16, 256) 1024 ['conv4_block4_2_conv[0][0]']
ization)
conv4_block4_2_relu (Activatio (None, 16, 16, 256) 0 ['conv4_block4_2_bn[0][0]']
n)
conv4_block4_3_conv (Conv2D) (None, 16, 16, 1024 263168 ['conv4_block4_2_relu[0][0]']
)
conv4_block4_3_bn (BatchNormal (None, 16, 16, 1024 4096 ['conv4_block4_3_conv[0][0]']
ization) )
conv4_block4_add (Add) (None, 16, 16, 1024 0 ['conv4_block3_out[0][0]',
) 'conv4_block4_3_bn[0][0]']
conv4_block4_out (Activation) (None, 16, 16, 1024 0 ['conv4_block4_add[0][0]']
)
conv4_block5_1_conv (Conv2D) (None, 16, 16, 256) 262400 ['conv4_block4_out[0][0]']
conv4_block5_1_bn (BatchNormal (None, 16, 16, 256) 1024 ['conv4_block5_1_conv[0][0]']
ization)
conv4_block5_1_relu (Activatio (None, 16, 16, 256) 0 ['conv4_block5_1_bn[0][0]']
n)
conv4_block5_2_conv (Conv2D) (None, 16, 16, 256) 590080 ['conv4_block5_1_relu[0][0]']
conv4_block5_2_bn (BatchNormal (None, 16, 16, 256) 1024 ['conv4_block5_2_conv[0][0]']
ization)
conv4_block5_2_relu (Activatio (None, 16, 16, 256) 0 ['conv4_block5_2_bn[0][0]']
n)
conv4_block5_3_conv (Conv2D) (None, 16, 16, 1024 263168 ['conv4_block5_2_relu[0][0]']
)
conv4_block5_3_bn (BatchNormal (None, 16, 16, 1024 4096 ['conv4_block5_3_conv[0][0]']
ization) )
conv4_block5_add (Add) (None, 16, 16, 1024 0 ['conv4_block4_out[0][0]',
) 'conv4_block5_3_bn[0][0]']
conv4_block5_out (Activation) (None, 16, 16, 1024 0 ['conv4_block5_add[0][0]']
)
conv4_block6_1_conv (Conv2D) (None, 16, 16, 256) 262400 ['conv4_block5_out[0][0]']
conv4_block6_1_bn (BatchNormal (None, 16, 16, 256) 1024 ['conv4_block6_1_conv[0][0]']
ization)
conv4_block6_1_relu (Activatio (None, 16, 16, 256) 0 ['conv4_block6_1_bn[0][0]']
n)
conv4_block6_2_conv (Conv2D) (None, 16, 16, 256) 590080 ['conv4_block6_1_relu[0][0]']
conv4_block6_2_bn (BatchNormal (None, 16, 16, 256) 1024 ['conv4_block6_2_conv[0][0]']
ization)
conv4_block6_2_relu (Activatio (None, 16, 16, 256) 0 ['conv4_block6_2_bn[0][0]']
n)
conv4_block6_3_conv (Conv2D) (None, 16, 16, 1024 263168 ['conv4_block6_2_relu[0][0]']
)
conv4_block6_3_bn (BatchNormal (None, 16, 16, 1024 4096 ['conv4_block6_3_conv[0][0]']
ization) )
conv4_block6_add (Add) (None, 16, 16, 1024 0 ['conv4_block5_out[0][0]',
) 'conv4_block6_3_bn[0][0]']
conv4_block6_out (Activation) (None, 16, 16, 1024 0 ['conv4_block6_add[0][0]']
)
conv5_block1_1_conv (Conv2D) (None, 8, 8, 512) 524800 ['conv4_block6_out[0][0]']
conv5_block1_1_bn (BatchNormal (None, 8, 8, 512) 2048 ['conv5_block1_1_conv[0][0]']
ization)
conv5_block1_1_relu (Activatio (None, 8, 8, 512) 0 ['conv5_block1_1_bn[0][0]']
n)
conv5_block1_2_conv (Conv2D) (None, 8, 8, 512) 2359808 ['conv5_block1_1_relu[0][0]']
conv5_block1_2_bn (BatchNormal (None, 8, 8, 512) 2048 ['conv5_block1_2_conv[0][0]']
ization)
conv5_block1_2_relu (Activatio (None, 8, 8, 512) 0 ['conv5_block1_2_bn[0][0]']
n)
conv5_block1_0_conv (Conv2D) (None, 8, 8, 2048) 2099200 ['conv4_block6_out[0][0]']
conv5_block1_3_conv (Conv2D) (None, 8, 8, 2048) 1050624 ['conv5_block1_2_relu[0][0]']
conv5_block1_0_bn (BatchNormal (None, 8, 8, 2048) 8192 ['conv5_block1_0_conv[0][0]']
ization)
conv5_block1_3_bn (BatchNormal (None, 8, 8, 2048) 8192 ['conv5_block1_3_conv[0][0]']
ization)
conv5_block1_add (Add) (None, 8, 8, 2048) 0 ['conv5_block1_0_bn[0][0]',
'conv5_block1_3_bn[0][0]']
conv5_block1_out (Activation) (None, 8, 8, 2048) 0 ['conv5_block1_add[0][0]']
conv5_block2_1_conv (Conv2D) (None, 8, 8, 512) 1049088 ['conv5_block1_out[0][0]']
conv5_block2_1_bn (BatchNormal (None, 8, 8, 512) 2048 ['conv5_block2_1_conv[0][0]']
ization)
conv5_block2_1_relu (Activatio (None, 8, 8, 512) 0 ['conv5_block2_1_bn[0][0]']
n)
conv5_block2_2_conv (Conv2D) (None, 8, 8, 512) 2359808 ['conv5_block2_1_relu[0][0]']
conv5_block2_2_bn (BatchNormal (None, 8, 8, 512) 2048 ['conv5_block2_2_conv[0][0]']
ization)
conv5_block2_2_relu (Activatio (None, 8, 8, 512) 0 ['conv5_block2_2_bn[0][0]']
n)
conv5_block2_3_conv (Conv2D) (None, 8, 8, 2048) 1050624 ['conv5_block2_2_relu[0][0]']
conv5_block2_3_bn (BatchNormal (None, 8, 8, 2048) 8192 ['conv5_block2_3_conv[0][0]']
ization)
conv5_block2_add (Add) (None, 8, 8, 2048) 0 ['conv5_block1_out[0][0]',
'conv5_block2_3_bn[0][0]']
conv5_block2_out (Activation) (None, 8, 8, 2048) 0 ['conv5_block2_add[0][0]']
conv5_block3_1_conv (Conv2D) (None, 8, 8, 512) 1049088 ['conv5_block2_out[0][0]']
conv5_block3_1_bn (BatchNormal (None, 8, 8, 512) 2048 ['conv5_block3_1_conv[0][0]']
ization)
conv5_block3_1_relu (Activatio (None, 8, 8, 512) 0 ['conv5_block3_1_bn[0][0]']
n)
conv5_block3_2_conv (Conv2D) (None, 8, 8, 512) 2359808 ['conv5_block3_1_relu[0][0]']
conv5_block3_2_bn (BatchNormal (None, 8, 8, 512) 2048 ['conv5_block3_2_conv[0][0]']
ization)
conv5_block3_2_relu (Activatio (None, 8, 8, 512) 0 ['conv5_block3_2_bn[0][0]']
n)
conv5_block3_3_conv (Conv2D) (None, 8, 8, 2048) 1050624 ['conv5_block3_2_relu[0][0]']
conv5_block3_3_bn (BatchNormal (None, 8, 8, 2048) 8192 ['conv5_block3_3_conv[0][0]']
ization)
conv5_block3_add (Add) (None, 8, 8, 2048) 0 ['conv5_block2_out[0][0]',
'conv5_block3_3_bn[0][0]']
conv5_block3_out (Activation) (None, 8, 8, 2048) 0 ['conv5_block3_add[0][0]']
==================================================================================================
Total params: 23,587,712
Trainable params: 23,534,592
Non-trainable params: 53,120
__________________________________________________________________________________________________
|
Wine.ipynb | ###Markdown
Let's view our quality samples in a scatterplot fashion. Maybe we might find some outliers From our initial corr matrix we were able to see that alcohol has a good influence on the quality of the wine- Let's try to visualize using a boxplot
###Code
fig = px.box(
wines_df,
x = 'quality',
y = 'alcohol',
color = 'quality',
boxmode="overlay"
)
fig.show()
###Output
_____no_output_____
###Markdown
From this visualization we can sort of get the intuition that having a higher quality means probably having higher alcohol content Let's try to visualize what factors affect alcohol content Interestingly, having a high alcohol content means having a low density as depicted in our visualization
###Code
wines_df[['alcohol', 'density']].corr()
fig = sns.jointplot(data = wines_df,y ='density', x = 'alcohol', kind='scatter', hue='quality', palette='rainbow')
###Output
_____no_output_____
###Markdown
Next we will try chlorides
###Code
wines_df[['chlorides', 'alcohol']].corr()
fig = sns.jointplot(data = wines_df, y = 'chlorides', x = 'alcohol', kind='reg', palette='rainbow')
###Output
_____no_output_____
###Markdown
Mostly it is falling in the range of 0.1 so not really much help there Next let's try to analyze the effect of volatile acidity on the quality
###Code
wines_df[['volatile acidity', 'quality']].corr()
vol_vs_quality = px.box(
wines_df,
x = 'quality',
y = 'volatile acidity',
color = 'quality',
boxmode="overlay"
)
vol_vs_quality.show()
###Output
_____no_output_____
###Markdown
From this boxplot it is kind of clear that having a lower volatile acidity results in higher quality! So let's try to see what factors affect the volatile acidity itself! Citric Acid
###Code
wines_df[['volatile acidity', 'citric acid']].corr()
volatile_acid_vs_citric_acid = sns.lmplot(data = wines_df, x = 'volatile acidity', y = 'citric acid')
plt.show()
wines_df
wines_df[['total sulfur dioxide', 'quality']].corr()
so_vs_quality = px.box(
wines_df,
x = 'quality',
y = 'total sulfur dioxide',
color = 'quality',
boxmode="overlay"
)
so_vs_quality.show()
###Output
_____no_output_____
###Markdown
Next we try to analyze the effect of free sulfur dioxide on total sulfur dioxide
###Code
wines_df[['free sulfur dioxide', 'total sulfur dioxide']].corr()
px.scatter(wines_df, x = 'free sulfur dioxide', y = 'total sulfur dioxide', color = 'quality')
###Output
_____no_output_____
###Markdown
Preprocessing Preparing the features and the labels Recall during our visualization we were seeing some outliers.- Outlier removal is indeed a part of the preprocessing pipeline so let's do it Importing our own zscore filter Note: Smaller size datasets might not really help that much and might lead to worse performance. As in this case probably
###Code
from preprocessing.ZScore import ZScore
transformer = ZScore(df = wines_df, threshold = 3)
wines_df = transformer.transform()
y = wines_df['quality']
X = wines_df.drop(['quality'], axis = 1)
X = np.array(X)
y = np.array(y)
###Output
_____no_output_____
###Markdown
Scaling the values to mean to zero and variance to 1
###Code
scaler = StandardScaler()
X = scaler.fit_transform(X)
###Output
_____no_output_____
###Markdown
Let's have a look at the class distribution
###Code
wines_df['quality'].value_counts()
###Output
_____no_output_____
###Markdown
It is pretty clear that certain classes are under-represented in our dataset so it might lead to a higher error while actually seeing unseen samples So we oversample our data!
###Code
from imblearn.over_sampling import SMOTE
smote=SMOTE()
X,y=smote.fit_resample(X,y)
from collections import Counter
resamp_data = {}
resamp_data = Counter(y)
resamp_data
###Output
_____no_output_____
###Markdown
Now that is better for our classification for sure! Training
###Code
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 42)
###Output
_____no_output_____
###Markdown
Competitions! 1. Decision Tree scikit-learn
###Code
clf_pruned = DecisionTreeClassifier()
start = time.time()
clf_pruned.fit(X_train, y_train)
end = time.time()
print("Inference time: {}".format(end - start))
y_pred = clf_pruned.predict(X_test)
accuracy_score(y_test, y_pred)
###Output
_____no_output_____
###Markdown
ours
###Code
from tree.DecisionTreeClassifier import DecisionTreeClassifier
clf = DecisionTreeClassifier(max_depth = 25)
start = time.time()
clf.fit(X_train, y_train)
end = time.time()
print("Inference time: {}".format(end - start))
###Output
Inference time: 195.0911889076233
###Markdown
Saving the model
###Code
clf.save("decision-tree.pth")
###Output
_____no_output_____
###Markdown
Load it again!
###Code
clf = DecisionTreeClassifier(max_depth = 25)
clf.load("decision-tree.pth")
y_pred = clf.predict(X_test)
accuracy_score(y_pred, y_test)
###Output
_____no_output_____
###Markdown
2. Random Forest This wasn't implemented in python. Just using scikit-learn seemed enough
###Code
rf = RandomForestClassifier(n_estimators = 100)
rf.fit(X_train, y_train)
y_pred = rf.predict(X_test)
accuracy_score(y_pred, y_test)
###Output
_____no_output_____
###Markdown
3. SVM
###Code
from sklearn.svm import SVC
clf = SVC(C = 10, gamma = 1, kernel='rbf') # Rbf Kernel
#Train the model using the training sets
clf.fit(X_train, y_train)
#Predict the response for test dataset
y_pred = clf.predict(X_test)
accuracy_score(y_pred, y_test)
###Output
_____no_output_____
###Markdown
4. Naive Bayes ours
###Code
model = NBClassifier()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
accuracy_score(y_pred, y_test)
###Output
_____no_output_____
###Markdown
scikit-learn
###Code
from sklearn.naive_bayes import GaussianNB
nb = GaussianNB()
nb.fit(X_train, y_train)
y_pred = nb.predict(X_test)
accuracy_score(y_pred, y_test)
###Output
_____no_output_____
###Markdown
Cross-ValidationA basic dry run has been done where we can see the metrics. Now let's try to use some of that KFold magic to find how robust our models really are!
###Code
from sklearn.model_selection import RepeatedStratifiedKFold
rskf = RepeatedStratifiedKFold(n_splits=3, n_repeats=2, random_state=42)
def test(model, X_test, y_test):
y_pred = model.predict(X_test)
return accuracy_score(y_pred, y_test)
rf_scores = []
dt_scores = []
dt_scikit_scores = []
nb_scores = []
nb_scikit_scores = []
rf_train_scores = []
dt_train_scores = []
dt_train_scikit_scores = []
nb_train_scores = []
nb_train_scikit_scores = []
start = time.time()
for train_index, test_index in rskf.split(X, y):
X_train, X_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]
## Scikit-learn random forest
rf.fit(X_train, y_train)
## Scikit-learn decision forest
clf_pruned.fit(X_train, y_train)
## Our implementation of decision tree
clf.fit(X_train, y_train)
## Gaussian NB
nb.fit(X_train, y_train)
## Our implementation of Gaussian NB
model.fit(X_train, y_train)
## Appending the scores for later visualizations
rf_scores.append(test(rf, X_test, y_test))
nb_scores.append(test(model, X_test, y_test))
nb_scikit_scores.append(test(nb, X_test, y_test))
dt_scikit_scores.append(test(clf_pruned, X_test, y_test))
dt_scores.append(test(clf, X_test, y_test))
## Appending training visualizations
rf_train_scores.append(test(rf, X_train, y_train))
nb_train_scores.append(test(model, X_train, y_train))
nb_train_scikit_scores.append(test(nb, X_train, y_train))
dt_train_scikit_scores.append(test(clf_pruned, X_train, y_train))
dt_train_scores.append(test(clf, X_train, y_train))
end = time.time()
print("Cross validation time: {}".format(end - start))
import plotly.graph_objects as go
test_fig = go.Figure()
test_fig.add_trace(go.Scatter(y = dt_scores, name = 'Decision Tree (Ours)'))
test_fig.add_trace(go.Scatter(y = dt_scikit_scores, name = 'Decision Tree (Scikit-Learn)'))
test_fig.add_trace(go.Scatter(y = rf_scores, name = 'Random Forest (Scikit-Learn)'))
test_fig.add_trace(go.Scatter(y = nb_scores, name = 'Gaussian NB (Ours)'))
test_fig.add_trace(go.Scatter(y = nb_scikit_scores, name = 'Gaussian NB (Scikit-Learn)'))
test_fig.update_layout(title = "Test scores")
test_fig.show()
training_fig = go.Figure()
training_fig.add_trace(go.Scatter(y = dt_train_scores, name = 'Decision Tree (Ours)'))
training_fig.add_trace(go.Scatter(y = dt_train_scikit_scores, name = 'Decision Tree (Scikit-Learn)'))
training_fig.add_trace(go.Scatter(y = rf_train_scores, name = 'Random Forest (Scikit-Learn)'))
training_fig.add_trace(go.Scatter(y = nb_train_scores, name = 'Gaussian NB (Ours)'))
training_fig.add_trace(go.Scatter(y = nb_train_scikit_scores, name = 'Gaussian NB (Scikit-Learn)'))
training_fig.update_layout(title = "Training scores")
training_fig.show()
test_fig = go.Figure()
test_fig.add_trace(go.Scatter(y = rf_scores, name = 'Random Forest (Scikit-Learn)'))
###Output
_____no_output_____
###Markdown
Random forest clearly outperforms as it is a better approach than using a single decision tree which could possibly to lead to overfitting Let's try to do some feature engineering and see what can we do to improve our metrics
###Code
wines_df
wines_df.corr()
###Output
_____no_output_____
###Markdown
EJEMPLO DE REGRESIÓN CON KNN<img src="https://www.neuraldojo.org/media/red_wine.png" alt="Markdown Monster icon" style="float: left; margin-right: 10px;" width="100%"/> 1.- Importación de las librerías y datos
###Code
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
from sklearn.model_selection import train_test_split
wine = pd.read_csv('winequality-red.csv', sep=';')
###Output
_____no_output_____
###Markdown
2.- Preparación de los datos 2.1 Inspección de los datos
###Code
wine.head()
wine.shape
wine.info()
wine.describe()
wine.isnull().sum()
targets = wine['quality'].value_counts()
targets
sns.barplot(x = targets.index, y=targets)
plt.figure(figsize=(15,8))
sns.heatmap(wine.corr(), annot=True)
###Output
_____no_output_____
###Markdown
2.2 Dividimos los datos en Entrenamiento y Test (Train Test Split)
###Code
#dividimos nuestro data set dos grupos preliminares de para entrenamiento y test, el dataset de test lo dejamos para el final de evaluación
test = wine.iloc[-299:,:]
wine_ = wine.iloc[0:1300,:]
#revisemos que estamos trabajando con todos los datos
print(test.shape)
print(wine_.shape)
# Para este ejemplo, vamos a usar la masa, ancho y altura para cada fruta
X = wine_.iloc[:,:-1]
y = wine_['quality']
# Utilizaremos la division por defecto 75% 25%
X_train, X_valid, y_train, y_valid = train_test_split(X, y, random_state=0)
###Output
_____no_output_____
###Markdown
3.- Preparamos y Entrenamos el Modelo
###Code
#Entrenamos el modelo utilizando diferentes valores de n_neighbors
from sklearn.neighbors import KNeighborsClassifier
scores = []
for n_neighbors in range(1,11):
knn = KNeighborsClassifier(n_neighbors = n_neighbors)
knn.fit(X,y)
scores.append(knn.score(X_valid, y_valid))
###Output
_____no_output_____
###Markdown
4.- Evaluamos el Modelo
###Code
#Graficamos los scores obtenidos para diferntes valores de K n_neighbors
plt.plot(scores)
plt.title("Wine Scores")
plt.xlabel("KNN")
plt.ylabel("Score")
print(scores)
###Output
[1.0, 0.8246153846153846, 0.7876923076923077, 0.7076923076923077, 0.6738461538461539, 0.6338461538461538, 0.6215384615384615, 0.6369230769230769, 0.6030769230769231, 0.6215384615384615]
###Markdown
4.1 Seleccionamos el modelo con los parametros que mejor score obtuvimos
###Code
knn_final = KNeighborsClassifier(n_neighbors = 5)
knn_final.fit(X,y)
###Output
_____no_output_____
###Markdown
4.1 Evaluamos con los datos de test
###Code
print("Entrenamiento:",knn_final.score(X_train,y_train))
print("Evaluación:",knn_final.score(X_valid,y_valid))
print("Test:",knn_final.score(test.iloc[:,:-1],test['quality']))
###Output
Entrenamiento: 0.6707692307692308
Evaluación: 0.6738461538461539
Test: 0.44481605351170567
###Markdown
Import modules
###Code
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
###Output
_____no_output_____
###Markdown
Import wine datasets from Scikit-learn built-in datasets
###Code
from sklearn import datasets
X,y = datasets.load_wine(return_X_y=True)
# split data
from sklearn.model_selection import train_test_split
seed = 123
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size = 0.3, stratify = y, random_state = seed)
###Output
_____no_output_____
###Markdown
KNN
###Code
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.neighbors import KNeighborsClassifier as KNN
from sklearn.metrics import accuracy_score
from sklearn.model_selection import GridSearchCV
# use pipeline
steps = [('scaler', StandardScaler()), ('knn',KNN() )]
pipeline = Pipeline(steps)
# use GridSearchCV
params_knn = {'knn__n_neighbors' : np.arange(1,20)}
cv = GridSearchCV(pipeline, param_grid=params_knn, cv=5)
cv.fit(X_train,y_train)
print('Best params : {}'.format(cv.best_params_))
print('Best score : {}'.format(cv.best_score_))
y_pred = cv.predict(X_test)
print('KNN accuracy : {:.2f}'.format(accuracy_score(y_test, y_pred)))
###Output
Best params : {'knn__n_neighbors': 6}
Best score : 0.968
KNN accuracy : 0.93
###Markdown
Decision TreeFind the best parameters ( max_depth, max_features )
###Code
from sklearn.tree import DecisionTreeClassifier
for i in range(1,20):
model = DecisionTreeClassifier(max_depth = i)
model.fit(X_train,y_train)
y_pred = model.predict(X_test)
score = accuracy_score(y_test, y_pred)
plt.bar(i,score, color = 'b')
plt.title('max_depth')
plt.xlabel('param\'s value')
plt.ylabel('accuracy')
plt.yticks(np.arange(0, 1.05,0.05))
plt.show()
for i in range(1,14):
model = DecisionTreeClassifier(max_features= i)
model.fit(X_train,y_train)
score = accuracy_score(y_test, y_pred)
plt.bar(i,score, color = 'b')
plt.title('max_features')
plt.xlabel('param\'s value')
plt.ylabel('accuracy')
plt.yticks(np.arange(0, 1.05,0.05))
plt.show()
from sklearn.tree import DecisionTreeClassifier
model = DecisionTreeClassifier(max_depth = 8,max_features=13, random_state = seed)
model.fit(X_train,y_train)
y_pred = model.predict(X_test)
print('Decision Tree accuracy : {:.2f}'.format(accuracy_score(y_test, y_pred)))
###Output
Decision Tree accuracy : 0.89
###Markdown
Use RandomizedSearchCV for Decision Tree
###Code
from sklearn.model_selection import RandomizedSearchCV
params = {'max_depth':[4,6,8,10], 'max_features':[8,10,12]}
model = DecisionTreeClassifier(random_state = seed)
rs = RandomizedSearchCV(model, param_distributions=params, cv=5,random_state = seed)
rs.fit(X_train,y_train)
print(rs.best_params_)
print(rs.best_score_)
y_pred = rs.predict(X_test)
print('Decision Tree : {:.2f}'.format(accuracy_score(y_test, y_pred)))
###Output
{'max_features': 10, 'max_depth': 6}
0.8943333333333333
Decision Tree : 0.89
###Markdown
RandomForest
###Code
from sklearn.ensemble import RandomForestClassifier
rf = RandomForestClassifier(n_estimators=300,random_state=seed)
rf.fit(X_train,y_train)
y_pred = rf.predict(X_test)
print('Random forest : {:.2f}'.format(accuracy_score(y_test, y_pred)))
###Output
Random forest : 0.98
###Markdown
Adaboost
###Code
from sklearn.ensemble import AdaBoostClassifier
dt = DecisionTreeClassifier(max_depth = 2,random_state = seed)
# adaboost
model = AdaBoostClassifier(base_estimator=dt, n_estimators=300, random_state = seed)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
print('AdaBoost : {:.2f}'.format(accuracy_score(y_test, y_pred)))
###Output
AdaBoost : 0.94
###Markdown
Gradient boosting
###Code
from sklearn.ensemble import GradientBoostingClassifier
gb = GradientBoostingClassifier(n_estimators=300, max_depth=2, random_state = seed)
gb.fit(X_train, y_train)
y_pred = gb.predict(X_test)
print('Gradient boosting : {:.2f}'.format(accuracy_score(y_test, y_pred)))
###Output
Gradient boosting : 0.98
###Markdown
Voting Classifier ( finalized model )
###Code
# Using Voting Classifier
from sklearn.metrics import confusion_matrix, classification_report
steps = [('scaler', StandardScaler()), ('knn',KNN(n_neighbors=6) )]
pipeline = Pipeline(steps)
rf = RandomForestClassifier(n_estimators=300,random_state=seed)
ab = AdaBoostClassifier(base_estimator=dt, n_estimators=300, random_state = seed)
gb = GradientBoostingClassifier(n_estimators=300, max_depth=2, random_state = seed)
classifiers = [('KNN', pipeline), ('Random forest', rf), ('Adaboost',ab),('Gradient Boosting', gb)]
for clf_name, clf in classifiers:
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print('{:s} : {:.3f}'.format(clf_name, accuracy))
from sklearn.ensemble import VotingClassifier
vc = VotingClassifier(estimators=classifiers)
vc.fit(X_train, y_train)
y_pred = vc.predict(X_test)
print('Voting Classifiers accuracy : {:.2f}'.format(accuracy_score(y_test, y_pred)))
print(confusion_matrix(y_test, y_pred))
print(classification_report(y_test, y_pred))
###Output
KNN : 0.926
Random forest : 0.981
Adaboost : 0.944
Gradient Boosting : 0.981
Voting Classifiers accuracy : 0.98
[[18 0 0]
[ 1 20 0]
[ 0 0 15]]
precision recall f1-score support
0 0.95 1.00 0.97 18
1 1.00 0.95 0.98 21
2 1.00 1.00 1.00 15
accuracy 0.98 54
macro avg 0.98 0.98 0.98 54
weighted avg 0.98 0.98 0.98 54
###Markdown
Save model
###Code
'''
import pickle
filename = 'wine_finalized_model.sav'
pickle.dump(vc, open(filename, 'wb'))
'''
###Output
_____no_output_____
###Markdown
Load model and perform prediction
###Code
def wine_model(filename, file):
'''load model from filename and predict file.'''
loaded_model = pickle.load(open(filename, 'rb'))
y_pred = loaded_model.predict(file)
return y_pred
###Output
_____no_output_____
###Markdown
Wine Quality Prediction Preliminaries In this little example we will look at several ways to predict the quality of wine based on several measurable quanities. But remember, waine tasting is largely a matter of personal taste.Frist, let's invoke some of the imports we will need.
###Code
import tensorflow as tf
import numpy as np
import os
import urllib
import random
from sklearn.neighbors import KNeighborsClassifier
import matplotlib.pyplot as plt
import tarfile
###Output
_____no_output_____
###Markdown
Next we need to make sure we have the data sets we needed downloaded. First let's get our data sets.
###Code
white_wine_file = "winequality-white.csv"
if not os.path.exists(white_wine_file):
urllib.request.urlretrieve("https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-white.csv", white_wine_file)
red_wine_file = "winequality-red.csv"
if not os.path.exists(red_wine_file):
urllib.request.urlretrieve("https://archive.ics.uci.edu/ml/machine-learning-databases/wine-quality/winequality-red.csv", red_wine_file)
###Output
_____no_output_____
###Markdown
Now we need to load and explore the data set. Load them into memory using the numpy tooling. The columns have the following meaings:'fixed acidity', 'volatile acidity', 'citric acid', 'residual sugar', 'chlorides', 'free sulfur dioxide', 'total sulfur dioxide', 'density', 'pH', 'sulphates', 'alcohol', 'quality'. We will pretty much ignore these as we will be doing ML based only on non-expert traning straegies. We also separate out the labels from the features.
###Code
tags = np.array(['fixed acidity', 'volatile acidity', 'citric acid', 'residual sugar', 'chlorides', 'free sulfur dioxide', 'total sulfur dioxide', 'density', 'pH', 'sulphates', 'alcohol'])
ww = np.loadtxt(white_wine_file, skiprows=1, delimiter=';')
ww_labels = ww[:, 11]
ww_features = ww[:, range(11)]
rw = np.loadtxt(red_wine_file, skiprows=1, delimiter=';')
rw_labels = rw[:, 11]
rw_features = rw[:, range(11)]
w_hist, _ = np.histogram(ww_labels, [0,1,2,3,4,5,6,7,8,9,10,11])
r_hist, _ = np.histogram(rw_labels, [0,1,2,3,4,5,6,7,8,9,10,11])
print("White wine features:")
print("Histogram of labels (w) = ", w_hist)
for w in range(11):
print("Feature = %20s (min = %6.3f, ave = %6.3f, max = %6.3f)." % (tags[w], np.min(ww_features[:,w]), np.average(ww_features[:,w]), np.max(ww_features[:,w])))
print("\nRed wine features:")
print("Histogram of labels (r) = ", r_hist)
for w in range(11):
print("Feature = %20s (min = %6.3f, ave = %6.3f, max = %6.3f)." % (tags[w], np.min(rw_features[:,w]), np.average(rw_features[:,w]), np.max(rw_features[:,w])))
###Output
White wine features:
Histogram of labels (w) = [ 0 0 0 20 163 1457 2198 880 175 5 0]
Feature = fixed acidity (min = 3.800, ave = 6.855, max = 14.200).
Feature = volatile acidity (min = 0.080, ave = 0.278, max = 1.100).
Feature = citric acid (min = 0.000, ave = 0.334, max = 1.660).
Feature = residual sugar (min = 0.600, ave = 6.391, max = 65.800).
Feature = chlorides (min = 0.009, ave = 0.046, max = 0.346).
Feature = free sulfur dioxide (min = 2.000, ave = 35.308, max = 289.000).
Feature = total sulfur dioxide (min = 9.000, ave = 138.361, max = 440.000).
Feature = density (min = 0.987, ave = 0.994, max = 1.039).
Feature = pH (min = 2.720, ave = 3.188, max = 3.820).
Feature = sulphates (min = 0.220, ave = 0.490, max = 1.080).
Feature = alcohol (min = 8.000, ave = 10.514, max = 14.200).
Red wine features:
Histogram of labels (r) = [ 0 0 0 10 53 681 638 199 18 0 0]
Feature = fixed acidity (min = 4.600, ave = 8.320, max = 15.900).
Feature = volatile acidity (min = 0.120, ave = 0.528, max = 1.580).
Feature = citric acid (min = 0.000, ave = 0.271, max = 1.000).
Feature = residual sugar (min = 0.900, ave = 2.539, max = 15.500).
Feature = chlorides (min = 0.012, ave = 0.087, max = 0.611).
Feature = free sulfur dioxide (min = 1.000, ave = 15.875, max = 72.000).
Feature = total sulfur dioxide (min = 6.000, ave = 46.468, max = 289.000).
Feature = density (min = 0.990, ave = 0.997, max = 1.004).
Feature = pH (min = 2.740, ave = 3.311, max = 4.010).
Feature = sulphates (min = 0.330, ave = 0.658, max = 2.000).
Feature = alcohol (min = 8.400, ave = 10.423, max = 14.900).
###Markdown
Data Segmentation Next we need to divide our data into training, validation, and test data sets. Typically we target 80, 10, 10. Just in case the existing data has some existing assumptions about the order, we will take random samples or each data set. Notice that we explicitly set the random number generator seed. This way we get the same partitioning everytime we rerun the program. Given the histograms above, we will combine the classes for the first 5 classes into on and the last 3 in to 1.From this point on we will focus on the white wine only. The red wine is left to the reader.
###Code
wn = len(ww_features)
random.seed(26)
# Select 3 or 5 classes. Notice that when changing the number of classes, you need to delete the temporary
# directories and their contents, e.g. bottleneck, retain_logs, SavedFeatures, wines, wines_te, wines_tr, wines_va.
n_classes = 3
if n_classes == 5:
label_map = [0, 0, 0, 0, 0, 1, 2, 3, 4, 4, 4]
if n_classes == 3:
label_map = [0, 0, 0, 0, 0, 0, 1, 2, 2, 2, 2]
ww_ind = random.sample(range(wn), wn)
ww_f_tr = np.array([ww_features[ww_ind[i]] for i in range(0, int(0.8*wn))])
ww_f_va = np.array([ww_features[ww_ind[i]] for i in range(int(0.8*wn)+1, int(0.9*wn))])
ww_f_te = np.array([ww_features[ww_ind[i]] for i in range(int(0.9*wn)+1, wn-1)])
ww_l_tr = np.array([label_map[int(ww_labels[ww_ind[i]])] for i in range(0, int(0.8*wn))])
ww_l_va = np.array([label_map[int(ww_labels[ww_ind[i]])] for i in range(int(0.8*wn)+1, int(0.9*wn))])
ww_l_te = np.array([label_map[int(ww_labels[ww_ind[i]])] for i in range(int(0.9*wn)+1, wn-1)])
###Output
_____no_output_____
###Markdown
K Nearest Neighbour Classification Let's start with a simple K Nearest Neighbours (KNN) style machine learning. This is a straingt forwards process requiring only a single traing step. Notice that we only list the results for the validation set. This is because we will be tuning the KNN parameters and don't want to over fit against the testing data set. To train the KNN classifier you can change the numbr of neighboours and the weighting strategy ('uniform' or 'distance').
###Code
knn = KNeighborsClassifier(n_neighbors=5, weights='distance')
knn.fit(ww_f_tr, ww_l_tr)
# Look at 10 of our validation set:
for i in range(10):
pred = knn.predict([ww_f_va[i]])[0]
probs = knn.predict_proba([ww_f_va[i]])
if n_classes == 5:
print ("Prediction = %1d Actual = %1d Probabilities = %5.3f %5.3f %5.3f %5.3f %5.3f" %
(pred, ww_l_va[i], probs[0][0], probs[0][1], probs[0][2], probs[0][3], probs[0][4]))
if n_classes == 3:
print ("Prediction = %1d Actual = %1d Probabilities = %5.3f %5.3f %5.3f" %
(pred, ww_l_va[i], probs[0][0], probs[0][1], probs[0][2]))
# Run the complete validation data set.
score = knn.score(ww_f_va, ww_l_va)
print("\n Overall score = %5.2f%%" % (100.0*score))
###Output
Prediction = 1 Actual = 1 Probabilities = 0.199 0.801 0.000
Prediction = 2 Actual = 2 Probabilities = 0.276 0.291 0.433
Prediction = 0 Actual = 0 Probabilities = 0.639 0.361 0.000
Prediction = 1 Actual = 1 Probabilities = 0.000 1.000 0.000
Prediction = 1 Actual = 2 Probabilities = 0.359 0.411 0.230
Prediction = 1 Actual = 1 Probabilities = 0.000 1.000 0.000
Prediction = 2 Actual = 2 Probabilities = 0.000 0.000 1.000
Prediction = 1 Actual = 1 Probabilities = 0.000 1.000 0.000
Prediction = 1 Actual = 1 Probabilities = 0.205 0.547 0.247
Prediction = 1 Actual = 1 Probabilities = 0.000 0.804 0.196
Overall score = 63.60%
###Markdown
Lets have a closer look at how our system in performaing. We'll look at the false positives and false negatives for each class. False positive is where the class was incorrectly predicted; a false negative is where a wrong class was predicited. In our case we will have a false positive somewhere for every false negative, but any patterns in the distribution could be interesting.
###Code
fp = np.zeros(n_classes)
fn = np.zeros(n_classes)
n = len(ww_f_va)
tot = 0
print("N = ", n)
for i in range(n):
pred = knn.predict([ww_f_va[i]])[0]
if pred != ww_l_va[i]:
tot = tot + 1
fn[int(ww_l_va[i])] = fn[int(ww_l_va[i])] + 1
fp[int(pred)] = fp[int(pred)] + 1
print("Total wrong = %3d. Eror rate = %8.4f%%" % (tot, 100.0*tot/n))
for i in range(n_classes):
print("Class = %2d False positive = %3d (%5.1f%%) False negative = %3d (%5.1f%%)." % (i, fp[i], 100.0*fp[i]/n, fn[i
], 100.0*fn[i]/n))
###Output
N = 489
###Markdown
The low false positives for the best and worst wines are encoraging. This means we are unlikely to be told a wine is good (or bad) incorrectly. However, we miss the oppertunity to sample about 4% of the best wines (false negatives), but these numbers too are relatively small.Observing this ability to identify good, bad, and ok wines, the reader might wish to try further restricting the number of classes and see how well the classifier functions. Introduction to Imagification The basic idea behine 'imigification' is that without needing to understand the detailed meaning of feature data we can still gain an insight into how well we might be able to classify this data. In the case of wine we were able to do pretty well with just using the KNN classifier, but in some cases there will be many more features or simply large volumes of data associated with each instance. In this case we want to develop a way to classify these without a detailed understanding of the specialist knowledge associated with the data.We have also discovered that modern image perception networks are quite good with detail that sometimes humans miss. We would like to exploit this learning with a technique called transfer learning. So while the wine case may not seem to demand this approach, we'll have a go anyway to see how straight forward the process of imagification can be. Capturing the Data as Images The first step in the process is to capture the data as images. Let's try a bar chart. [Note that we are normalizing all the features against the average across the whole data set so that all bars have about the same impact in the image.]Let's look at just one instance.
###Code
plt.close()
fig, bar = plt.subplots()
indx = range(11)
p = 50
features = [ww_f_tr[p][f]/np.average(ww_f_tr[:,f]) for f in range(11)]
bar.bar(indx, features)
plt.show()
###Output
_____no_output_____
###Markdown
Now we need to build the image data set to use in training the image recognizer. We will create three directories to stor the images, one each for training, validation, and testing. This step will take some time. Go have a coffee.
###Code
if not os.path.exists("wines_tr"):
os.makedirs("wines_tr")
f_inds = range(11)
for p in range (len(ww_f_tr)):
features = ww_f_tr[p]
for f in f_inds:
features[f] = features[f]/np.average(ww_f_tr[:,f])
plt.close()
_, bar = plt.subplots()
bar.bar(f_inds, features)
plt.savefig("wines_tr/WW%04d.jpeg"%(p))
if not os.path.exists("wines_va"):
os.makedirs("wines_va")
f_inds = range(11)
for p in range (len(ww_f_va)):
features = ww_f_va[p]
for f in f_inds:
features[f] = features[f]/np.average(ww_f_tr[:,f])
plt.close()
_, bar = plt.subplots()
bar.bar(f_inds, features)
plt.savefig("wines_va/WW%04d.jpeg"%(p))
if not os.path.exists("wines_te"):
os.makedirs("wines_te")
f_inds = range(11)
for p in range (len(ww_f_te)):
features = ww_f_te[p]
for f in f_inds:
features[f] = features[f]/np.average(ww_f_tr[:,f])
plt.close()
_, bar = plt.subplots()
bar.bar(f_inds, features)
plt.savefig("wines_te/WW%04d.jpeg"%(p))
###Output
_____no_output_____
###Markdown
Transfer Learning As simple approach to imagification and transfer learing is to remove the final layer of an existing image recognizer and replace it with a KNN classifier using the final pooling layer are the source for our features. This easily demonstrates the ability to adapt CNNs for use in transfer learning. The success of ths approach depends on how well our images capture the essential infomration. First make sure the Inception and TensorFlow environment is set up.
###Code
if not os.path.exists("model"):
os.makedirs("model")
if not os.path.exists("model/inception-2015-12-05.tgz"):
filepath, _ = urllib.request.urlretrieve(
"http://download.tensorflow.org/models/image/imagenet/inception-2015-12-05.tgz", "model/inception-2015-12-05.tgz")
tarfile.open(filepath, 'r:gz').extractall("model")
###Output
_____no_output_____
###Markdown
Now we need to run all our images through the Inception CNN and then set up a KNN to train against the Known labels.
###Code
# Set up Inception CNN.
tf.reset_default_graph()
f = tf.gfile.FastGFile("model/classify_image_graph_def.pb", 'rb')
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
tf.import_graph_def(graph_def, name='')
sess = tf.Session()
if os.path.exists ("SavedFeatures/tr_f.npy"):
tr_features = np.load("SavedFeatures/tr_f.npy")
tr_labels = np.load("SavedFeatures/tr_l.npy")
va_features = np.load("SavedFeatures/va_f.npy")
va_labels = np.load("SavedFeatures/va_l.npy")
te_features = np.load("SavedFeatures/te_f.npy")
te_labels = np.load("SavedFeatures/te_l.npy")
else:
os.makedirs("SavedFeatures")
pool3 = sess.graph.get_tensor_by_name('pool_3:0')
tr_features = np.empty((len(ww_f_tr), 2048), dtype='float32')
tr_labels = np.empty(len(ww_l_tr), dtype='int')
for i in range(len(ww_f_tr)):
image_f = "wines_tr/WW%04d.jpeg" % (i)
image = tf.gfile.FastGFile(image_f, 'rb').read()
tr_features[i] = sess.run(pool3, {'DecodeJpeg/contents:0': image})[0][0][0]
tr_labels[i] = ww_l_tr[i]
if i % 100 == 0:
print("Generating training feature set for image number = ", i)
va_features = np.empty((len(ww_f_va), 2048), dtype='float32')
va_labels = np.empty(len(ww_l_va), dtype='int')
for i in range(len(ww_f_va)):
image_f = "wines_va/WW%04d.jpeg" % (i)
image = tf.gfile.FastGFile(image_f, 'rb').read()
va_features[i] = sess.run(pool3, {'DecodeJpeg/contents:0': image})[0][0][0]
va_labels[i] = ww_l_va[i]
if i % 100 == 0:
print("Generating validation feature set for image number = ", i)
te_features = np.empty((len(ww_f_te), 2048), dtype='float32')
te_labels = np.empty(len(ww_l_te), dtype='int')
for i in range(len(ww_f_te)):
image_f = "wines_te/WW%04d.jpeg" % (i)
image = tf.gfile.FastGFile(image_f, 'rb').read()
te_features[i] = sess.run(pool3, {'DecodeJpeg/contents:0': image})[0][0][0]
te_labels[i] = ww_l_te[i]
if i % 100 == 0:
print("Generating ttest feature set for image number = ", i)
np.save("SavedFeatures/tr_f.npy", tr_features)
np.save("SavedFeatures/tr_l.npy", tr_labels)
np.save("SavedFeatures/va_f.npy", va_features)
np.save("SavedFeatures/va_l.npy", va_labels)
np.save("SavedFeatures/te_f.npy", te_features)
np.save("SavedFeatures/te_l.npy", te_labels)
###Output
_____no_output_____
###Markdown
Now train and validate our KNN based on the features extracted from the images.
###Code
knn = KNeighborsClassifier(n_neighbors=5, weights='distance')
knn.fit(tr_features, tr_labels)
# Look at 10 of our validation set:
for i in range(10):
pred = knn.predict([va_features[i]])[0]
probs = knn.predict_proba([va_features[i]])
if n_classes == 5:
print ("Prediction = %1d Actual = %1d Probabilities = %5.3f %5.3f %5.3f %5.3f %5.3f" %
(pred, va_labels[i], probs[0][0], probs[0][1], probs[0][2], probs[0][3], probs[0][4]))
if n_classes == 3:
print ("Prediction = %1d Actual = %1d Probabilities = %5.3f %5.3f %5.3f" %
(pred, va_labels[i], probs[0][0], probs[0][1], probs[0][2]))
# Run the complete validation data set.
score = knn.score(va_features, va_labels)
print("\n Overall score = %5.2f%%" % (100.0*score))
fp = np.zeros(11)
fn = np.zeros(11)
n = len(va_labels)
tot = 0
print("N = ", n)
for i in range(n):
pred = knn.predict([va_features[i]])[0]
if pred != va_labels[i]:
tot = tot + 1
fn[int(va_labels[i])] = fn[int(va_labels[i])] + 1
fp[int(pred)] = fp[int(pred)] + 1
print("Total wrong = %3d. Eror rate = %8.4f%%" % (tot, 100.0*tot/n))
for i in range(n_classes):
print("Class = %2d False positive = %3d (%5.1f%%) False negative = %3d (%5.1f%%)." % (i, fp[i], 100.0*fp[i]/n, fn[i
], 100.0*fn[i]/n))
# Build the nested directory structure needed for the retraining approach.
if not os.path.exists("wines"):
if n_classes == 5:
os.makedirs("wines")
os.makedirs("wines/undrinkable")
os.makedirs("wines/poor")
os.makedirs("wines/ok")
os.makedirs("wines/good")
os.makedirs("wines/excellent")
if n_classes == 3:
os.makedirs("wines")
os.makedirs("wines/undrinkable")
os.makedirs("wines/ok")
os.makedirs("wines/excellent")
f_inds = range(11)
for p in range (len(ww_features)):
features = ww_features[p]
for f in f_inds:
features[f] = features[f]/np.average(ww_features[:,f])
plt.close()
_, bar = plt.subplots()
bar.bar(f_inds, features)
lab = label_map[int(ww_labels[p])]
if lab == 0:
plt.savefig("wines/undrinkable/WW%04d.jpeg"%(p))
if lab == 1:
if n_classes == 5:
plt.savefig("wines/poor/WW%04d.jpeg"%(p))
if n_classes == 3:
plt.savefig("wines/ok/WW%04d.jpeg"%(p))
if lab == 2:
if n_classes == 5:
plt.savefig("wines/ok/WW%04d.jpeg"%(p))
if n_classes == 3:
plt.savefig("wines/excellent/WW%04d.jpeg"%(p))
if lab == 3:
plt.savefig("wines/good/WW%04d.jpeg"%(p))
if lab == 4:
plt.savefig("wines/excellent/WW%04d.jpeg"%(p))
###Output
_____no_output_____
###Markdown
The retrain.py application is part or the TensorFlow distribution and is discussed in detail in this tutorial: https://www.tensorflow.org/tutorials/image_retraining. This application has many options hat are worth exploring in the source code, but for now we will run it with just the defaults, which we have editied to meet our wines example.
###Code
%run "retrain.py"
###Output
Not extracting or downloading files, model already present in disk
Model path: ./model\classify_image_graph_def.pb
|
site/en/r2/guide/distribute_strategy.ipynb | ###Markdown
Copyright 2018 The TensorFlow Authors.
###Code
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###Output
_____no_output_____
###Markdown
Distributed Training in TensorFlow View on TensorFlow.org Run in Google Colab View source on GitHub OverviewThe `tf.distribute.Strategy` API is an easy way to distribute your trainingacross multiple devices/machines. Our goal is to allow users to use existingmodels and training code with minimal changes to enable distributed training.Currently, in core TensorFlow, we support `tf.distribute.MirroredStrategy`. Thisdoes in-graph replication with synchronous training on many GPUs on one machine.Essentially, we create copies of all variables in the model's layers on eachdevice. We then use all-reduce to combine gradients across the devices beforeapplying them to the variables to keep them in sync.Many other strategies will soon beavailable in core TensorFlow. You can find more information about them in the[README](https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/distribute).You can also read the[public design review](https://github.com/tensorflow/community/blob/master/rfcs/20181016-replicator.md)for updating the `tf.distribute.Strategy` API as part of the move toto core TF. Example with Keras APILet's see how to scale to multiple GPUs on one machine using `MirroredStrategy`with [tf.keras](https://www.tensorflow.org/guide/keras).We will take a very simple model consisting of a single layer. First, we will import Tensorflow.
###Code
from __future__ import absolute_import, division, print_function
!pip install tf-nightly-2.0-preview
import tensorflow as tf
###Output
_____no_output_____
###Markdown
To distribute a Keras model on multiple GPUs using `MirroredStrategy`, we first instantiate a `MirroredStrategy` object.
###Code
strategy = tf.distribute.MirroredStrategy()
###Output
_____no_output_____
###Markdown
We then create and compile the Keras model in `strategy.scope`.
###Code
with strategy.scope():
inputs = tf.keras.layers.Input(shape=(1,))
predictions = tf.keras.layers.Dense(1)(inputs)
model = tf.keras.models.Model(inputs=inputs, outputs=predictions)
model.compile(loss='mse',
optimizer=tf.keras.optimizers.SGD(learning_rate=0.2))
###Output
_____no_output_____
###Markdown
Let's also define a simple input dataset for training this model.
###Code
train_dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(10000).batch(10)
###Output
_____no_output_____
###Markdown
To train the model we call Keras `fit` API using the input dataset that wecreated earlier, same as how we would in a non-distributed case.
###Code
model.fit(train_dataset, epochs=5, steps_per_epoch=10)
###Output
_____no_output_____
###Markdown
Similarly, we can also call `evaluate` and `predict` as before using appropriatedatasets.
###Code
eval_dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100).batch(10)
model.evaluate(eval_dataset, steps=10)
predict_dataset = tf.data.Dataset.from_tensors(([1.])).repeat(10).batch(2)
model.predict(predict_dataset, steps=5)
###Output
_____no_output_____
###Markdown
That's all you need to train your model with Keras on multiple GPUs with`MirroredStrategy`. It will take care of splitting upthe input dataset, replicating layers and variables on each device, andcombining and applying gradients.The model and input code does not have to change because we have changed theunderlying components of TensorFlow (such as optimizer, batch norm andsummaries) to become strategy-aware. That means those components know how tocombine their state across devices. Further, saving and checkpointing worksseamlessly, so you can save with one or no distribute strategy and resume withanother. Example with Estimator APIYou can also use `tf.distribute.Strategy` API with[`Estimator`](https://www.tensorflow.org/api_docs/python/tf/estimator/Estimator).Let's see a simple example of it's usage with `MirroredStrategy`.We will use the `LinearRegressor` premade estimator as an example. To use `MirroredStrategy` with Estimator, all we need to do is:* Create an instance of the `MirroredStrategy` class.* Pass it to the[`RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig)parameter of the custom or premade `Estimator`.
###Code
strategy = tf.distribute.MirroredStrategy()
config = tf.estimator.RunConfig(
train_distribute=strategy, eval_distribute=strategy)
regressor = tf.estimator.LinearRegressor(
feature_columns=[tf.feature_column.numeric_column('feats')],
optimizer='SGD',
config=config)
###Output
_____no_output_____
###Markdown
We will define a simple input function to feed data for training this model.
###Code
def input_fn():
return tf.data.Dataset.from_tensors(({"feats":[1.]}, [1.])).repeat(10000).batch(10)
###Output
_____no_output_____
###Markdown
Then we can call `train` on the regressor instance to train the model.
###Code
regressor.train(input_fn=input_fn, steps=10)
###Output
_____no_output_____
###Markdown
And we can `evaluate` to evaluate the trained model.
###Code
regressor.evaluate(input_fn=input_fn, steps=10)
###Output
_____no_output_____
###Markdown
Copyright 2018 The TensorFlow Authors.
###Code
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###Output
_____no_output_____
###Markdown
Distributed training in TensorFlow View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook Overview`tf.distribute.Strategy` is a TensorFlow API to distribute training across multiple GPUs, multiple machines or TPUs. Using this API, users can distribute their existing models and training code with minimal code changes.`tf.distribute.Strategy` has been designed with these key goals in mind:* Easy to use and support multiple user segments, including researchers, ML engineers, etc.* Provide good performance out of the box.* Easy switching between strategies.`tf.distribute.Strategy` can be used with TensorFlow's high level APIs, [tf.keras](https://www.tensorflow.org/guide/keras) and [tf.estimator](https://www.tensorflow.org/guide/estimators), with just a couple of lines of code change. It also provides an API that can be used to distribute custom training loops (and in general any computation using TensorFlow).In TensorFlow 2.0, users can execute their programs eagerly, or in a graph using [`tf.function`](../tutorials/eager/tf_function.ipynb). `tf.distribute.Strategy` intends to support both these modes of execution. Note that we may talk about training most of the time in this guide, but this API can also be used for distributing evaluation and prediction on different platforms.As you will see in a bit, very few changes are needed to use `tf.distribute.Strategy` with your code. This is because we have changed the underlying components of TensorFlow to become strategy-aware. This includes variables, layers, models, optimizers, metrics, summaries, and checkpoints.In this guide, we will talk about various types of strategies and how one can use them in a different situations.
###Code
# Import TensorFlow
from __future__ import absolute_import, division, print_function, unicode_literals
!pip install tensorflow-gpu==2.0.0-beta1
import tensorflow as tf
###Output
_____no_output_____
###Markdown
Types of strategies`tf.distribute.Strategy` intends to cover a number of use cases along different axes. Some of these combinations are currently supported and others will be added in the future. Some of these axes are:* Synchronous vs asynchronous training: These are two common ways of distributing training with data parallelism. In sync training, all workers train over different slices of input data in sync, and aggregating gradients at each step. In async training, all workers are independently training over the input data and updating variables asynchronously. Typically sync training is supported via all-reduce and async through parameter server architecture.* Hardware platform: Users may want to scale their training onto multiple GPUs on one machine, or multiple machines in a network (with 0 or more GPUs each), or on Cloud TPUs.In order to support these use cases, we have 5 strategies available. In the next section we will talk about which of these are supported in which scenarios in TF 2.0-beta at this time. Here is a quick overview:| Training API | MirroredStrategy | TPUStrategy | MultiWorkerMirroredStrategy | CentralStorageStrategy | ParameterServerStrategy ||:----------------------- |:------------------- |:--------------------- |:--------------------------------- |:--------------------------------- |:-------------------------- || **Keras API** | Supported | Support planned in 2.0 RC | Experimental support | Experimental support | Supported planned in post 2.0 || **Custom training loop** | Experimental support | Experimental support | Support planned in 2.0 RC | Support planned in 2.0 RC | No support yet || **Estimator API** | Supported | Supported | Supported | Supported | Supported | MirroredStrategy`tf.distribute.MirroredStrategy` supports synchronous distributed training on multiple GPUs on one machine. It creates one replica per GPU device. Each variable in the model is mirrored across all the replicas. Together, these variables form a single conceptual variable called `MirroredVariable`. These variables are kept in sync with each other by applying identical updates.Efficient all-reduce algorithms are used to communicate the variable updates across the devices.All-reduce aggregates tensors across all the devices by adding them up, and makes them available on each device.It’s a fused algorithm that is very efficient and can reduce the overhead of synchronization significantly. There are many all-reduce algorithms and implementations available, depending on the type of communication available between devices. By default, it uses NVIDIA NCCL as the all-reduce implementation. The user can also choose between a few other options we provide, or write their own.Here is the simplest way of creating `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
###Output
_____no_output_____
###Markdown
This will create a `MirroredStrategy` instance which will use all the GPUs that are visible to TensorFlow, and use NCCL as the cross device communication.If you wish to use only some of the GPUs on your machine, you can do so like this:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(devices=["/gpu:0", "/gpu:1"])
###Output
_____no_output_____
###Markdown
If you wish to override the cross device communication, you can do so using the `cross_device_ops` argument by supplying an instance of `tf.distribute.CrossDeviceOps`. Currently we provide `tf.distribute.HierarchicalCopyAllReduce` and `tf.distribute.ReductionToOneDevice` as 2 other options other than `tf.distribute.NcclAllReduce` which is the default.
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(
cross_device_ops=tf.distribute.HierarchicalCopyAllReduce())
###Output
_____no_output_____
###Markdown
CentralStorageStrategy`tf.distribute.experimental.CentralStorageStrategy` does synchronous training as well. Variables are not mirrored, instead they are placed on the CPU and operations are replicated across all local GPUs. If there is only one GPU, all variables and operations will be placed on that GPU.Create an instance of `CentralStorageStrategy` by:
###Code
central_storage_strategy = tf.distribute.experimental.CentralStorageStrategy()
###Output
_____no_output_____
###Markdown
This will create a `CentralStorageStrategy` instance which will use all visible GPUs and CPU. Update to variables on replicas will be aggregated before being applied to variables. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. MultiWorkerMirroredStrategy`tf.distribute.experimental.MultiWorkerMirroredStrategy` is very similar to `MirroredStrategy`. It implements synchronous distributed training across multiple workers, each with potentially multiple GPUs. Similar to `MirroredStrategy`, it creates copies of all variables in the model on each device across all workers.It uses [CollectiveOps](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/collective_ops.py) as the multi-worker all-reduce communication method used to keep variables in sync. A collective op is a single op in the TensorFlow graph which can automatically choose an all-reduce algorithm in the TensorFlow runtime according to hardware, network topology and tensor sizes.It also implements additional performance optimizations. For example, it includes a static optimization that converts multiple all-reductions on small tensors into fewer all-reductions on larger tensors. In addition, we are designing it to have a plugin architecture - so that in the future, users will be able to plugin algorithms that are better tuned for their hardware. Note that collective ops also implement other collective operations such as broadcast and all-gather.Here is the simplest way of creating `MultiWorkerMirroredStrategy`:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()
###Output
_____no_output_____
###Markdown
`MultiWorkerMirroredStrategy` currently allows you to choose between two different implementations of collective ops. `CollectiveCommunication.RING` implements ring-based collectives using gRPC as the communication layer. `CollectiveCommunication.NCCL` uses [Nvidia's NCCL](https://developer.nvidia.com/nccl) to implement collectives. `CollectiveCommunication.AUTO` defers the choice to the runtime. The best choice of collective implementation depends upon the number and kind of GPUs, and the network interconnect in the cluster. You can specify them in the following way:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy(
tf.distribute.experimental.CollectiveCommunication.NCCL)
###Output
_____no_output_____
###Markdown
One of the key differences to get multi worker training going, as compared to multi-GPU training, is the multi-worker setup. "TF_CONFIG" environment variable is the standard way in TensorFlow to specify the cluster configuration to each worker that is part of the cluster. See section on ["TF_CONFIG" below](TF_CONFIG) for more details on how this can be done. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. TPUStrategy`tf.distribute.experimental.TPUStrategy` lets users run their TensorFlow training on Tensor Processing Units (TPUs). TPUs are Google's specialized ASICs designed to dramatically accelerate machine learning workloads. They are available on Google Colab, the [TensorFlow Research Cloud](https://www.tensorflow.org/tfrc) and [Google Compute Engine](https://cloud.google.com/tpu).In terms of distributed training architecture, TPUStrategy is the same `MirroredStrategy` - it implements synchronous distributed training. TPUs provide their own implementation of efficient all-reduce and other collective operations across multiple TPU cores, which are used in `TPUStrategy`.Here is how you would instantiate `TPUStrategy`.Note: To run this code in Colab, you should select TPU as the Colab runtime. We will have a tutorial soon that will demonstrate how you can use TPUStrategy.```cluster_resolver = tf.distribute.cluster_resolver.TPUClusterResolver( tpu=tpu_address)tf.config.experimental_connect_to_host(cluster_resolver.master())tf.tpu.experimental.initialize_tpu_system(cluster_resolver)tpu_strategy = tf.distribute.experimental.TPUStrategy(cluster_resolver)``` `TPUClusterResolver` instance helps locate the TPUs. In Colab, you don't need to specify any arguments to it. If you want to use this for Cloud TPUs, you will need to specify the name of your TPU resource in `tpu` argument. We also need to initialize the tpu system explicitly at the start of the program. This is required before TPUs can be used for computation and should ideally be done at the beginning because it also wipes out the TPU memory so all state will be lost. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. ParameterServerStrategy`tf.distribute.experimental.ParameterServerStrategy` supports parameter servers training on multiple machines. In this setup, some machines are designated as workers and some as parameter servers. Each variable of the model is placed on one parameter server. Computation is replicated across all GPUs of the all the workers.In terms of code, it looks similar to other strategies:```ps_strategy = tf.distribute.experimental.ParameterServerStrategy()``` For multi worker training, "TF_CONFIG" needs to specify the configuration of parameter servers and workers in your cluster, which you can read more about in ["TF_CONFIG" below](TF_CONFIG) below. So far we've talked about what are the different stategies available and how you can instantiate them. In the next few sections, we will talk about the different ways in which you can use them to distribute your training. We will show short code snippets in this guide and link off to full tutorials which you can run end to end. Using `tf.distribute.Strategy` with KerasWe've integrated `tf.distribute.Strategy` into `tf.keras` which is TensorFlow's implementation of the[Keras API specification](https://keras.io). `tf.keras` is a high-level API to build and train models. By integrating into `tf.keras` backend, we've made it seamless for Keras users to distribute their training written in the Keras training framework. The only things that need to change in a user's program are: (1) Create an instance of the appropriate `tf.distribute.Strategy` and (2) Move the creation and compiling of Keras model inside `strategy.scope`. We support all types of Keras models - sequential, functional and subclassed.Here is a snippet of code to do this for a very simple Keras model with one dense layer:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
model.compile(loss='mse', optimizer='sgd')
###Output
_____no_output_____
###Markdown
In this example we used `MirroredStrategy` so we can run this on a machine with multiple GPUs. `strategy.scope()` indicated which parts of the code to run distributed. Creating a model inside this scope allows us to create mirrored variables instead of regular variables. Compiling under the scope allows us to know that the user intends to train this model using this strategy. Once this is setup, you can fit your model like you would normally. `MirroredStrategy` takes care of replicating the model's training on the available GPUs, aggregating gradients etc.
###Code
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100).batch(10)
model.fit(dataset, epochs=2)
model.evaluate(dataset)
###Output
_____no_output_____
###Markdown
Here we used a `tf.data.Dataset` to provide the training and eval input. You can also use numpy arrays:
###Code
import numpy as np
inputs, targets = np.ones((100, 1)), np.ones((100, 1))
model.fit(inputs, targets, epochs=2, batch_size=10)
###Output
_____no_output_____
###Markdown
In both cases (dataset or numpy), each batch of the given input is divided equally among the multiple replicas. For instance, if using `MirroredStrategy` with 2 GPUs, each batch of size 10 will get divided among the 2 GPUs, with each receiving 5 input examples in each step. Each epoch will then train faster as you add more GPUs. Typically, you would want to increase your batch size as you add more accelerators so as to make effective use of the extra computing power. You will also need to re-tune your learning rate, depending on the model. You can use `strategy.num_replicas_in_sync` to get the number of replicas.
###Code
# Compute global batch size using number of replicas.
BATCH_SIZE_PER_REPLICA = 5
global_batch_size = (BATCH_SIZE_PER_REPLICA *
mirrored_strategy.num_replicas_in_sync)
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100)
dataset = dataset.batch(global_batch_size)
LEARNING_RATES_BY_BATCH_SIZE = {5: 0.1, 10: 0.15}
learning_rate = LEARNING_RATES_BY_BATCH_SIZE[global_batch_size]
###Output
_____no_output_____
###Markdown
What's supported now?In TF 2.0 beta release, we support training with Keras using `MirroredStrategy`, `CentralStorageStrategy` and `MultiWorkerMirroredStrategy`. Both `CentralStorageStrategy` and `MultiWorkerMirroredStrategy` are currently experimental APIs and are subject to change.Support for other strategies will be coming soon. The API and how to use will be exactly the same as above.| Training API | MirroredStrategy | TPUStrategy | MultiWorkerMirroredStrategy | CentralStorageStrategy | ParameterServerStrategy ||---------------- |--------------------- |----------------------- |----------------------------------- |----------------------------------- |--------------------------- || Keras APIs | Supported | Support planned in 2.0 RC | Experimental support | Experimental support | Support planned in post 2.0 | Examples and TutorialsHere is a list of tutorials and examples that illustrate the above integration end to end with Keras:1. Tutorial to train [MNIST](../tutorials/distribute/keras.ipynb) with `MirroredStrategy`.2. Official [ResNet50](https://github.com/tensorflow/models/blob/master/official/resnet/keras/keras_imagenet_main.py) training with ImageNet data using `MirroredStrategy`.3. [ResNet50](https://github.com/tensorflow/tpu/blob/master/models/experimental/resnet50_keras/resnet50.py) trained with Imagenet data on Cloud TPus with `TPUStrategy`. Note that this example only works with TensorFlow 1.x currently.4. [Tutorial](../tutorials/distribute/multi_worker_with_keras.ipynb) to train MNIST using `MultiWorkerMirroredStrategy`.5. [NCF](https://github.com/tensorflow/models/blob/master/official/recommendation/ncf_keras_main.py) trained using `MirroredStrategy`.2. [Transformer]( https://github.com/tensorflow/models/blob/master/official/transformer/v2/transformer_main.py) trained using `MirroredStrategy`. Using `tf.distribute.Strategy` with Estimator`tf.estimator` is a distributed training TensorFlow API that originally supported the async parameter server approach. Like with Keras, we've integrated `tf.distribute.Strategy` into `tf.Estimator` so that a user who is using Estimator for their training can easily change their training is distributed with very few changes to your their code. With this, estimator users can now do synchronous distributed training on multiple GPUs and multiple workers, as well as use TPUs.The usage of `tf.distribute.Strategy` with Estimator is slightly different than the Keras case. Instead of using `strategy.scope`, now we pass the strategy object into the [`RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig) for the Estimator.Here is a snippet of code that shows this with a premade estimator `LinearRegressor` and `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
config = tf.estimator.RunConfig(
train_distribute=mirrored_strategy, eval_distribute=mirrored_strategy)
regressor = tf.estimator.LinearRegressor(
feature_columns=[tf.feature_column.numeric_column('feats')],
optimizer='SGD',
config=config)
###Output
_____no_output_____
###Markdown
We use a premade Estimator here, but the same code works with a custom Estimator as well. `train_distribute` determines how training will be distributed, and `eval_distribute` determines how evaluation will be distributed. This is another difference from Keras where we use the same strategy for both training and eval.Now we can train and evaluate this Estimator with an input function:
###Code
def input_fn():
dataset = tf.data.Dataset.from_tensors(({"feats":[1.]}, [1.]))
return dataset.repeat(1000).batch(10)
regressor.train(input_fn=input_fn, steps=10)
regressor.evaluate(input_fn=input_fn, steps=10)
###Output
_____no_output_____
###Markdown
Another difference to highlight here between Estimator and Keras is the input handling. In Keras, we mentioned that each batch of the dataset is split across the multiple replicas. In Estimator, however, the user provides an `input_fn` and have full control over how they want their data to be distributed across workers and devices. We do not do automatic splitting of batch, nor automatically shard the data across different workers. The provided `input_fn` is called once per worker, thus giving one dataset per worker. Then one batch from that dataset is fed to one replica on that worker, thereby consuming N batches for N replicas on 1 worker. In other words, the dataset returned by the `input_fn` should provide batches of size `PER_REPLICA_BATCH_SIZE`. And the global batch size for a step can be obtained as `PER_REPLICA_BATCH_SIZE * strategy.num_replicas_in_sync`. When doing multi worker training, users will also want to either split their data across the workers, or shuffle with a random seed on each. You can see an example of how to do this in the [Multi-worker Training with Estimator](../tutorials/distribute/multi_worker_with_estimator.ipynb). We showed an example of using `MirroredStrategy` with Estimator. You can also use `TPUStrategy` with Estimator as well, in the exact same way:```config = tf.estimator.RunConfig( train_distribute=tpu_strategy, eval_distribute=tpu_strategy)``` And similarly, you can use multi worker and parameter server strategies as well. The code remains the same, but you need to use `tf.estimator.train_and_evaluate`, and set "TF_CONFIG" environment variables for each binary running in your cluster. What's supported now?In TF 2.0 beta release, we support training with Estimator using all strategies.| Training API | MirroredStrategy | TPUStrategy | MultiWorkerMirroredStrategy | CentralStorageStrategy | ParameterServerStrategy ||:--------------- |:------------------ |:------------- |:----------------------------- |:------------------------ |:------------------------- || Estimator API | Supported | Supported | Supported | Supported | Supported | Examples and TutorialsHere are some examples that show end to end usage of various strategies with Estimator:1. [Multi-worker Training with Estimator](../tutorials/distribute/multi_worker_with_estimator.ipynb) to train MNIST with multiple workers using `MultiWorkerMirroredStrategy`.2. [End to end example](https://github.com/tensorflow/ecosystem/tree/master/distribution_strategy) for multi worker training in tensorflow/ecosystem using Kuberentes templates. This example starts with a Keras model and converts it to an Estimator using the `tf.keras.estimator.model_to_estimator` API.3. Official [ResNet50](https://github.com/tensorflow/models/blob/master/official/resnet/imagenet_main.py) model, which can be trained using either `MirroredStrategy` or `MultiWorkerMirroredStrategy`.4. [ResNet50](https://github.com/tensorflow/tpu/blob/master/models/experimental/distribution_strategy/resnet_estimator.py) example with TPUStrategy. Using `tf.distribute.Strategy` with custom training loopsAs you've seen, using `tf.distribute.Strategy` with high level APIs is only a couple lines of code change. With a little more effort, `tf.distribute.Strategy` can also be used by other users who are not using these frameworks.TensorFlow is used for a wide variety of use cases and some users (such as researchers) require more flexibility and control over their training loops. This makes it hard for them to use the high level frameworks such as Estimator or Keras. For instance, someone using a GAN may want to take a different number of generator or discriminator steps each round. Similarly, the high level frameworks are not very suitable for Reinforcement Learning training. So these users will usually write their own training loops.For these users, we provide a core set of methods through the `tf.distribute.Strategy` classes. Using these may require minor restructuring of the code initially, but once that is done, the user should be able to switch between GPUs / TPUs / multiple machines by just changing the strategy instance.Here we will show a brief snippet illustrating this use case for a simple training example using the same Keras model as before. First, we create the model and optimizer inside the strategy's scope. This ensures that any variables created with the model and optimizer are mirrored variables.
###Code
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
optimizer = tf.keras.optimizers.SGD()
###Output
_____no_output_____
###Markdown
Next, we create the input dataset and call `tf.distribute.Strategy.experimental_distribute_dataset` to distribute the dataset based on the strategy.
###Code
with mirrored_strategy.scope():
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(1000).batch(
global_batch_size)
dist_dataset = mirrored_strategy.experimental_distribute_dataset(dataset)
###Output
_____no_output_____
###Markdown
Then, we define one step of the training. We will use `tf.GradientTape` to compute gradients and optimizer to apply those gradients to update our model's variables. To distribute this training step, we put in in a function `step_fn` and pass it to `tf.distrbute.Strategy.experimental_run_v2` along with the dataset inputs that we get from `dist_dataset` created before:
###Code
@tf.function
def train_step(dist_inputs):
def step_fn(inputs):
features, labels = inputs
with tf.GradientTape() as tape:
logits = model(features)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(
logits=logits, labels=labels)
loss = tf.reduce_sum(cross_entropy) * (1.0 / global_batch_size)
grads = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(list(zip(grads, model.trainable_variables)))
return cross_entropy
per_example_losses = mirrored_strategy.experimental_run_v2(
step_fn, args=(dist_inputs,))
mean_loss = mirrored_strategy.reduce(
tf.distribute.ReduceOp.MEAN, per_example_losses, axis=0)
return mean_loss
###Output
_____no_output_____
###Markdown
A few other things to note in the code above:1. We used `tf.nn.softmax_cross_entropy_with_logits` to compute the loss. And then we scaled the total loss by the global batch size. This is important because all the replicas are training in sync and number of examples in each step of training is the global batch. So the loss needs to be divided by the global batch size and not by the replica (local) batch size.2. We used the `tf.distribute.Strategy.reduce` API to aggregate the results returned by `tf.distribute.Strategy.experimental_run_v2`. `tf.distribute.Strategy.experimental_run_v2` returns results from each local replica in the strategy, and there are multiple ways to consume this result. You can `reduce` them to get an aggregated value. You can also do `tf.distribute.Strategy.experimental_local_results` to get the list of values contained in the result, one per local replica.3. When `apply_gradients` is called within a distribution strategy scope, its behavior is modified. Specifically, before applying gradients on each parallel instance during synchronous training, it performs a sum-over-all-replicas of the gradients. Finally, once we have defined the training step, we can iterate over `dist_dataset` and run the training in a loop:
###Code
with mirrored_strategy.scope():
for inputs in dist_dataset:
print(train_step(inputs))
###Output
_____no_output_____
###Markdown
In the example above, we iterated over the `dist_dataset` to provide input to your training. We also provide the `tf.distribute.Strategy.make_experimental_numpy_dataset` to support numpy inputs. You can use this API to create a dataset before calling `tf.distribute.Strategy.experimental_distribute_dataset`.Another way of iterating over your data is to explicitly use iterators. You may want to do this when you want to run for a given number of steps as opposed to iterating over the entire dataset.The above iteration would now be modified to first create an iterator and then explicity call `next` on it to get the input data.
###Code
with mirrored_strategy.scope():
iterator = iter(dist_dataset)
for _ in range(10):
print(train_step(next(iterator)))
###Output
_____no_output_____
###Markdown
Copyright 2018 The TensorFlow Authors.
###Code
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###Output
_____no_output_____
###Markdown
Distributed training in TensorFlow View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook Overview`tf.distribute.Strategy` is a TensorFlow API to distribute training across multiple GPUs, multiple machines or TPUs. Using this API, users can distribute their existing models and training code with minimal code changes.`tf.distribute.Strategy` has been designed with these key goals in mind:* Easy to use and support multiple user segments, including researchers, ML engineers, etc.* Provide good performance out of the box.* Easy switching between strategies.`tf.distribute.Strategy` can be used with TensorFlow's high level APIs, [tf.keras](https://www.tensorflow.org/guide/keras) and [tf.estimator](https://www.tensorflow.org/guide/estimators), with just a couple of lines of code change. It also provides an API that can be used to distribute custom training loops (and in general any computation using TensorFlow).In TensorFlow 2.0, users can execute their programs eagerly, or in a graph using [`tf.function`](../tutorials/eager/tf_function.ipynb). `tf.distribute.Strategy` intends to support both these modes of execution. Note that we may talk about training most of the time in this guide, but this API can also be used for distributing evaluation and prediction on different platforms.As you will see in a bit, very few changes are needed to use `tf.distribute.Strategy` with your code. This is because we have changed the underlying components of TensorFlow to become strategy-aware. This includes variables, layers, models, optimizers, metrics, summaries, and checkpoints.In this guide, we will talk about various types of strategies and how one can use them in a different situations.
###Code
# Import TensorFlow
from __future__ import absolute_import, division, print_function, unicode_literals
!pip install tensorflow-gpu==2.0.0-beta1
import tensorflow as tf
###Output
_____no_output_____
###Markdown
Types of strategies`tf.distribute.Strategy` intends to cover a number of use cases along different axes. Some of these combinations are currently supported and others will be added in the future. Some of these axes are:* Synchronous vs asynchronous training: These are two common ways of distributing training with data parallelism. In sync training, all workers train over different slices of input data in sync, and aggregating gradients at each step. In async training, all workers are independently training over the input data and updating variables asynchronously. Typically sync training is supported via all-reduce and async through parameter server architecture.* Hardware platform: Users may want to scale their training onto multiple GPUs on one machine, or multiple machines in a network (with 0 or more GPUs each), or on Cloud TPUs.In order to support these use cases, we have 5 strategies available. In the next section we will talk about which of these are supported in which scenarios in TF 2.0-beta at this time. Here is a quick overview:| Training API | MirroredStrategy | TPUStrategy | MultiWorkerMirroredStrategy | CentralStorageStrategy | ParameterServerStrategy ||:----------------------- |:------------------- |:--------------------- |:--------------------------------- |:--------------------------------- |:-------------------------- || **Keras API** | Supported | Support planned in 2.0 RC | Experimental support | Experimental support | Supported planned in post 2.0 || **Custom training loop** | Experimental support | Experimental support | Support planned in 2.0 RC | Support planned in 2.0 RC | No support yet || **Estimator API** | Supported | Supported | Supported | Supported | Supported | MirroredStrategy`tf.distribute.MirroredStrategy` supports synchronous distributed training on multiple GPUs on one machine. It creates one replica per GPU device. Each variable in the model is mirrored across all the replicas. Together, these variables form a single conceptual variable called `MirroredVariable`. These variables are kept in sync with each other by applying identical updates.Efficient all-reduce algorithms are used to communicate the variable updates across the devices.All-reduce aggregates tensors across all the devices by adding them up, and makes them available on each device.It’s a fused algorithm that is very efficient and can reduce the overhead of synchronization significantly. There are many all-reduce algorithms and implementations available, depending on the type of communication available between devices. By default, it uses NVIDIA NCCL as the all-reduce implementation. The user can also choose between a few other options we provide, or write their own.Here is the simplest way of creating `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
###Output
_____no_output_____
###Markdown
This will create a `MirroredStrategy` instance which will use all the GPUs that are visible to TensorFlow, and use NCCL as the cross device communication.If you wish to use only some of the GPUs on your machine, you can do so like this:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(devices=["/gpu:0", "/gpu:1"])
###Output
_____no_output_____
###Markdown
If you wish to override the cross device communication, you can do so using the `cross_device_ops` argument by supplying an instance of `tf.distribute.CrossDeviceOps`. Currently we provide `tf.distribute.HierarchicalCopyAllReduce` and `tf.distribute.ReductionToOneDevice` as 2 other options other than `tf.distribute.NcclAllReduce` which is the default.
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(
cross_device_ops=tf.distribute.HierarchicalCopyAllReduce())
###Output
_____no_output_____
###Markdown
CentralStorageStrategy`tf.distribute.experimental.CentralStorageStrategy` does synchronous training as well. Variables are not mirrored, instead they are placed on the CPU and operations are replicated across all local GPUs. If there is only one GPU, all variables and operations will be placed on that GPU.Create an instance of `CentralStorageStrategy` by:
###Code
central_storage_strategy = tf.distribute.experimental.CentralStorageStrategy()
###Output
_____no_output_____
###Markdown
This will create a `CentralStorageStrategy` instance which will use all visible GPUs and CPU. Update to variables on replicas will be aggregated before being applied to variables. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. MultiWorkerMirroredStrategy`tf.distribute.experimental.MultiWorkerMirroredStrategy` is very similar to `MirroredStrategy`. It implements synchronous distributed training across multiple workers, each with potentially multiple GPUs. Similar to `MirroredStrategy`, it creates copies of all variables in the model on each device across all workers.It uses [CollectiveOps](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/collective_ops.py) as the multi-worker all-reduce communication method used to keep variables in sync. A collective op is a single op in the TensorFlow graph which can automatically choose an all-reduce algorithm in the TensorFlow runtime according to hardware, network topology and tensor sizes.It also implements additional performance optimizations. For example, it includes a static optimization that converts multiple all-reductions on small tensors into fewer all-reductions on larger tensors. In addition, we are designing it to have a plugin architecture - so that in the future, users will be able to plugin algorithms that are better tuned for their hardware. Note that collective ops also implement other collective operations such as broadcast and all-gather.Here is the simplest way of creating `MultiWorkerMirroredStrategy`:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()
###Output
_____no_output_____
###Markdown
`MultiWorkerMirroredStrategy` currently allows you to choose between two different implementations of collective ops. `CollectiveCommunication.RING` implements ring-based collectives using gRPC as the communication layer. `CollectiveCommunication.NCCL` uses [Nvidia's NCCL](https://developer.nvidia.com/nccl) to implement collectives. `CollectiveCommunication.AUTO` defers the choice to the runtime. The best choice of collective implementation depends upon the number and kind of GPUs, and the network interconnect in the cluster. You can specify them in the following way:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy(
tf.distribute.experimental.CollectiveCommunication.NCCL)
###Output
_____no_output_____
###Markdown
One of the key differences to get multi worker training going, as compared to multi-GPU training, is the multi-worker setup. "TF_CONFIG" environment variable is the standard way in TensorFlow to specify the cluster configuration to each worker that is part of the cluster. See section on ["TF_CONFIG" below](TF_CONFIG) for more details on how this can be done. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. TPUStrategy`tf.distribute.experimental.TPUStrategy` lets users run their TensorFlow training on Tensor Processing Units (TPUs). TPUs are Google's specialized ASICs designed to dramatically accelerate machine learning workloads. They are available on Google Colab, the [TensorFlow Research Cloud](https://www.tensorflow.org/tfrc) and [Google Compute Engine](https://cloud.google.com/tpu).In terms of distributed training architecture, TPUStrategy is the same `MirroredStrategy` - it implements synchronous distributed training. TPUs provide their own implementation of efficient all-reduce and other collective operations across multiple TPU cores, which are used in `TPUStrategy`.Here is how you would instantiate `TPUStrategy`.Note: To run this code in Colab, you should select TPU as the Colab runtime. We will have a tutorial soon that will demonstrate how you can use TPUStrategy.```cluster_resolver = tf.distribute.cluster_resolver.TPUClusterResolver( tpu=tpu_address)tf.config.experimental_connect_to_host(cluster_resolver.master())tf.tpu.experimental.initialize_tpu_system(cluster_resolver)tpu_strategy = tf.distribute.experimental.TPUStrategy(cluster_resolver)``` `TPUClusterResolver` instance helps locate the TPUs. In Colab, you don't need to specify any arguments to it. If you want to use this for Cloud TPUs, you will need to specify the name of your TPU resource in `tpu` argument. We also need to initialize the tpu system explicitly at the start of the program. This is required before TPUs can be used for computation and should ideally be done at the beginning because it also wipes out the TPU memory so all state will be lost. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. ParameterServerStrategy`tf.distribute.experimental.ParameterServerStrategy` supports parameter servers training on multiple machines. In this setup, some machines are designated as workers and some as parameter servers. Each variable of the model is placed on one parameter server. Computation is replicated across all GPUs of the all the workers.In terms of code, it looks similar to other strategies:```ps_strategy = tf.distribute.experimental.ParameterServerStrategy()``` For multi worker training, "TF_CONFIG" needs to specify the configuration of parameter servers and workers in your cluster, which you can read more about in ["TF_CONFIG" below](TF_CONFIG) below. So far we've talked about what are the different stategies available and how you can instantiate them. In the next few sections, we will talk about the different ways in which you can use them to distribute your training. We will show short code snippets in this guide and link off to full tutorials which you can run end to end. Using `tf.distribute.Strategy` with KerasWe've integrated `tf.distribute.Strategy` into `tf.keras` which is TensorFlow's implementation of the[Keras API specification](https://keras.io). `tf.keras` is a high-level API to build and train models. By integrating into `tf.keras` backend, we've made it seamless for Keras users to distribute their training written in the Keras training framework. The only things that need to change in a user's program are: (1) Create an instance of the appropriate `tf.distribute.Strategy` and (2) Move the creation and compiling of Keras model inside `strategy.scope`. We support all types of Keras models - sequential, functional and subclassed.Here is a snippet of code to do this for a very simple Keras model with one dense layer:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
model.compile(loss='mse', optimizer='sgd')
###Output
_____no_output_____
###Markdown
In this example we used `MirroredStrategy` so we can run this on a machine with multiple GPUs. `strategy.scope()` indicated which parts of the code to run distributed. Creating a model inside this scope allows us to create mirrored variables instead of regular variables. Compiling under the scope allows us to know that the user intends to train this model using this strategy. Once this is setup, you can fit your model like you would normally. `MirroredStrategy` takes care of replicating the model's training on the available GPUs, aggregating gradients etc.
###Code
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100).batch(10)
model.fit(dataset, epochs=2)
model.evaluate(dataset)
###Output
_____no_output_____
###Markdown
Here we used a `tf.data.Dataset` to provide the training and eval input. You can also use numpy arrays:
###Code
import numpy as np
inputs, targets = np.ones((100, 1)), np.ones((100, 1))
model.fit(inputs, targets, epochs=2, batch_size=10)
###Output
_____no_output_____
###Markdown
In both cases (dataset or numpy), each batch of the given input is divided equally among the multiple replicas. For instance, if using `MirroredStrategy` with 2 GPUs, each batch of size 10 will get divided among the 2 GPUs, with each receiving 5 input examples in each step. Each epoch will then train faster as you add more GPUs. Typically, you would want to increase your batch size as you add more accelerators so as to make effective use of the extra computing power. You will also need to re-tune your learning rate, depending on the model. You can use `strategy.num_replicas_in_sync` to get the number of replicas.
###Code
# Compute global batch size using number of replicas.
BATCH_SIZE_PER_REPLICA = 5
global_batch_size = (BATCH_SIZE_PER_REPLICA *
mirrored_strategy.num_replicas_in_sync)
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100)
dataset = dataset.batch(global_batch_size)
LEARNING_RATES_BY_BATCH_SIZE = {5: 0.1, 10: 0.15}
learning_rate = LEARNING_RATES_BY_BATCH_SIZE[global_batch_size]
###Output
_____no_output_____
###Markdown
What's supported now?In TF 2.0 beta release, we support training with Keras using `MirroredStrategy`, `CentralStorageStrategy` and `MultiWorkerMirroredStrategy`. Both `CentralStorageStrategy` and `MultiWorkerMirroredStrategy` are currently experimental APIs and are subject to change.Support for other strategies will be coming soon. The API and how to use will be exactly the same as above.| Training API | MirroredStrategy | TPUStrategy | MultiWorkerMirroredStrategy | CentralStorageStrategy | ParameterServerStrategy ||---------------- |--------------------- |----------------------- |----------------------------------- |----------------------------------- |--------------------------- || Keras APIs | Supported | Support planned in 2.0 RC | Experimental support | Experimental support | Support planned in post 2.0 | Examples and TutorialsHere is a list of tutorials and examples that illustrate the above integration end to end with Keras:1. Tutorial to train [MNIST](../tutorials/distribute/keras.ipynb) with `MirroredStrategy`.2. Official [ResNet50](https://github.com/tensorflow/models/blob/master/official/resnet/keras/keras_imagenet_main.py) training with ImageNet data using `MirroredStrategy`.3. [ResNet50](https://github.com/tensorflow/tpu/blob/master/models/experimental/resnet50_keras/resnet50.py) trained with Imagenet data on Cloud TPus with `TPUStrategy`. Note that this example only works with TensorFlow 1.x currently.4. [Tutorial](../tutorials/distribute/multi_worker_with_keras.ipynb) to train MNIST using `MultiWorkerMirroredStrategy`.5. [NCF](https://github.com/tensorflow/models/blob/master/official/recommendation/ncf_keras_main.py) trained using `MirroredStrategy`.2. [Transformer]( https://github.com/tensorflow/models/blob/master/official/transformer/v2/transformer_main.py) trained using `MirroredStrategy`. Using `tf.distribute.Strategy` with Estimator`tf.estimator` is a distributed training TensorFlow API that originally supported the async parameter server approach. Like with Keras, we've integrated `tf.distribute.Strategy` into `tf.Estimator` so that a user who is using Estimator for their training can easily change their training is distributed with very few changes to your their code. With this, estimator users can now do synchronous distributed training on multiple GPUs and multiple workers, as well as use TPUs.The usage of `tf.distribute.Strategy` with Estimator is slightly different than the Keras case. Instead of using `strategy.scope`, now we pass the strategy object into the [`RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig) for the Estimator.Here is a snippet of code that shows this with a premade estimator `LinearRegressor` and `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
config = tf.estimator.RunConfig(
train_distribute=mirrored_strategy, eval_distribute=mirrored_strategy)
regressor = tf.estimator.LinearRegressor(
feature_columns=[tf.feature_column.numeric_column('feats')],
optimizer='SGD',
config=config)
###Output
_____no_output_____
###Markdown
We use a premade Estimator here, but the same code works with a custom Estimator as well. `train_distribute` determines how training will be distributed, and `eval_distribute` determines how evaluation will be distributed. This is another difference from Keras where we use the same strategy for both training and eval.Now we can train and evaluate this Estimator with an input function:
###Code
def input_fn():
dataset = tf.data.Dataset.from_tensors(({"feats":[1.]}, [1.]))
return dataset.repeat(1000).batch(10)
regressor.train(input_fn=input_fn, steps=10)
regressor.evaluate(input_fn=input_fn, steps=10)
###Output
_____no_output_____
###Markdown
Another difference to highlight here between Estimator and Keras is the input handling. In Keras, we mentioned that each batch of the dataset is split across the multiple replicas. In Estimator, however, the user provides an `input_fn` and have full control over how they want their data to be distributed across workers and devices. We do not do automatic splitting of batch, nor automatically shard the data across different workers. The provided `input_fn` is called once per worker, thus giving one dataset per worker. Then one batch from that dataset is fed to one replica on that worker, thereby consuming N batches for N replicas on 1 worker. In other words, the dataset returned by the `input_fn` should provide batches of size `PER_REPLICA_BATCH_SIZE`. And the global batch size for a step can be obtained as `PER_REPLICA_BATCH_SIZE * strategy.num_replicas_in_sync`. When doing multi worker training, users will also want to either split their data across the workers, or shuffle with a random seed on each. You can see an example of how to do this in the [Multi-worker Training with Estimator](../tutorials/distribute/multi_worker_with_estimator.ipynb). We showed an example of using `MirroredStrategy` with Estimator. You can also use `TPUStrategy` with Estimator as well, in the exact same way:```config = tf.estimator.RunConfig( train_distribute=tpu_strategy, eval_distribute=tpu_strategy)``` And similarly, you can use multi worker and parameter server strategies as well. The code remains the same, but you need to use `tf.estimator.train_and_evaluate`, and set "TF_CONFIG" environment variables for each binary running in your cluster. What's supported now?In TF 2.0 beta release, we support training with Estimator using all strategies.| Training API | MirroredStrategy | TPUStrategy | MultiWorkerMirroredStrategy | CentralStorageStrategy | ParameterServerStrategy ||:--------------- |:------------------ |:------------- |:----------------------------- |:------------------------ |:------------------------- || Estimator API | Supported | Supported | Supported | Supported | Supported | Examples and TutorialsHere are some examples that show end to end usage of various strategies with Estimator:1. [Multi-worker Training with Estimator](../tutorials/distribute/multi_worker_with_estimator.ipynb) to train MNIST with multiple workers using `MultiWorkerMirroredStrategy`.2. [End to end example](https://github.com/tensorflow/ecosystem/tree/master/distribution_strategy) for multi worker training in tensorflow/ecosystem using Kuberentes templates. This example starts with a Keras model and converts it to an Estimator using the `tf.keras.estimator.model_to_estimator` API.3. Official [ResNet50](https://github.com/tensorflow/models/blob/master/official/resnet/imagenet_main.py) model, which can be trained using either `MirroredStrategy` or `MultiWorkerMirroredStrategy`.4. [ResNet50](https://github.com/tensorflow/tpu/blob/master/models/experimental/distribution_strategy/resnet_estimator.py) example with TPUStrategy. Using `tf.distribute.Strategy` with custom training loopsAs you've seen, using `tf.distribute.Strategy` with high level APIs is only a couple lines of code change. With a little more effort, `tf.distribute.Strategy` can also be used by other users who are not using these frameworks.TensorFlow is used for a wide variety of use cases and some users (such as researchers) require more flexibility and control over their training loops. This makes it hard for them to use the high level frameworks such as Estimator or Keras. For instance, someone using a GAN may want to take a different number of generator or discriminator steps each round. Similarly, the high level frameworks are not very suitable for Reinforcement Learning training. So these users will usually write their own training loops.For these users, we provide a core set of methods through the `tf.distribute.Strategy` classes. Using these may require minor restructuring of the code initially, but once that is done, the user should be able to switch between GPUs / TPUs / multiple machines by just changing the strategy instance.Here we will show a brief snippet illustrating this use case for a simple training example using the same Keras model as before. First, we create the model and optimizer inside the strategy's scope. This ensures that any variables created with the model and optimizer are mirrored variables.
###Code
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
optimizer = tf.keras.optimizers.SGD()
###Output
_____no_output_____
###Markdown
Next, we create the input dataset and call `tf.distribute.Strategy.experimental_distribute_dataset` to distribute the dataset based on the strategy.
###Code
with mirrored_strategy.scope():
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(1000).batch(
global_batch_size)
dist_dataset = mirrored_strategy.experimental_distribute_dataset(dataset)
###Output
_____no_output_____
###Markdown
Then, we define one step of the training. We will use `tf.GradientTape` to compute gradients and optimizer to apply those gradients to update our model's variables. To distribute this training step, we put in in a function `step_fn` and pass it to `tf.distrbute.Strategy.experimental_run_v2` along with the dataset inputs that we get from `dist_dataset` created before:
###Code
@tf.function
def train_step(dist_inputs):
def step_fn(inputs):
features, labels = inputs
with tf.GradientTape() as tape:
logits = model(features)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(
logits=logits, labels=labels)
loss = tf.reduce_sum(cross_entropy) * (1.0 / global_batch_size)
grads = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(list(zip(grads, model.trainable_variables)))
return cross_entropy
per_example_losses = mirrored_strategy.experimental_run_v2(
step_fn, args=(dist_inputs,))
mean_loss = mirrored_strategy.reduce(
tf.distribute.ReduceOp.MEAN, per_example_losses, axis=0)
return mean_loss
###Output
_____no_output_____
###Markdown
A few other things to note in the code above:1. We used `tf.nn.softmax_cross_entropy_with_logits` to compute the loss. And then we scaled the total loss by the global batch size. This is important because all the replicas are training in sync and number of examples in each step of training is the global batch. So the loss needs to be divided by the global batch size and not by the replica (local) batch size.2. We used the `tf.distribute.Strategy.reduce` API to aggregate the results returned by `tf.distribute.Strategy.experimental_run_v2`. `tf.distribute.Strategy.experimental_run_v2` returns results from each local replica in the strategy, and there are multiple ways to consume this result. You can `reduce` them to get an aggregated value. You can also do `tf.distribute.Strategy.experimental_local_results` to get the list of values contained in the result, one per local replica.3. When `apply_gradients` is called within a distribution strategy scope, its behavior is modified. Specifically, before applying gradients on each parallel instance during synchronous training, it performs a sum-over-all-replicas of the gradients. Finally, once we have defined the training step, we can iterate over `dist_dataset` and run the training in a loop:
###Code
with mirrored_strategy.scope():
for inputs in dist_dataset:
print(train_step(inputs))
###Output
_____no_output_____
###Markdown
In the example above, we iterated over the `dist_dataset` to provide input to your training. We also provide the `tf.distribute.Strategy.make_experimental_numpy_dataset` to support numpy inputs. You can use this API to create a dataset before calling `tf.distribute.Strategy.experimental_distribute_dataset`.Another way of iterating over your data is to explicitly use iterators. You may want to do this when you want to run for a given number of steps as opposed to iterating over the entire dataset.The above iteration would now be modified to first create an iterator and then explicity call `next` on it to get the input data.
###Code
with mirrored_strategy.scope():
iterator = iter(dist_dataset)
for _ in range(10):
print(train_step(next(iterator)))
###Output
_____no_output_____
###Markdown
Copyright 2018 The TensorFlow Authors.
###Code
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###Output
_____no_output_____
###Markdown
Distributed Training in TensorFlow View on TensorFlow.org Run in Google Colab View source on GitHub Overview`tf.distribute.Strategy` is a TensorFlow API to distribute trainingacross multiple GPUs, multiple machines or TPUs. Using this API, users can distribute their existing models and training code with minimal code changes.`tf.distribute.Strategy` has been designed with these key goals in mind:* Easy to use and support multiple user segments, including researchers, ML engineers, etc.* Provide good performance out of the box.* Easy switching between strategies.`tf.distribute.Strategy` can be used with TensorFlow's high level APIs, [tf.keras](https://www.tensorflow.org/guide/keras) and [tf.estimator](https://www.tensorflow.org/guide/estimators), with just a couple of lines of code change. It also provides an API that can be used to distribute custom training loops (and in general any computation using TensorFlow).In TensorFlow 2.0, users can execute their programs eagerly, or in a graph using [`tf.function`](../tutorials/eager/tf_function.ipynb). `tf.distribute.Strategy` intends to support both these modes of execution. Note that we may talk about training most of the time in this guide, but this API can also be used for distributing evaluation and prediction on different platforms.As you will see in a bit, very few changes are needed to use `tf.distribute.Strategy` with your code. This is because we have changed the underlying components of TensorFlow to become strategy-aware. This includes variables, layers, models, optimizers, metrics, summaries, and checkpoints. In this guide, we will talk about various types of strategies and how one can use them in a different situations.
###Code
# Import TensorFlow
from __future__ import absolute_import, division, print_function
!pip install tensorflow-gpu==2.0.0-alpha0
import tensorflow as tf
###Output
_____no_output_____
###Markdown
Types of strategies`tf.distribute.Strategy` intends to cover a number of use cases along different axes. Some of these combinations are currently supported and others will be added in the future. Some of these axes are:* Syncronous vs asynchronous training: These are two common ways of distributing training with data parallelism. In sync training, all workers train over different slices of input data in sync, and aggregating gradients at each step. In async training, all workers are independently training over the input data and updating variables asynchronously. Typically sync training is supported via all-reduce and async through parameter server architecture.* Hardware platform: Users may want to scale their training onto multiple GPUs on one machine, or multiple machines in a network (with 0 or more GPUs each), or on Cloud TPUs.In order to support these use cases, we have 4 strategies available. In the next section we will talk about which of these are supported in which scenarios in TF 2.0-alpha at this time. MirroredStrategy`tf.distribute.MirroredStrategy` support synchronous distributed training on multiple GPUs on one machine. It creates one replica per GPU device. Each variable in the model is mirrored across all the replicas. Together, these variables form a single conceptual variable called `MirroredVariable`. These variables are kept in sync with each other by applying identical updates.Efficient all-reduce algorithms are used to communicate the variable updates across the devices.All-reduce aggregates tensors across all the devices by adding them up, and makes them available on each device.It’s a fused algorithm that is very efficient and can reduce the overhead of synchronization significantly. There are many all-reduce algorithms and implementations available, depending on the type of communication available between devices. By default, it uses NVIDIA NCCL as the all-reduce implementation. The user can also choose between a few other options we provide, or write their own.Here is the simplest way of creating `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
###Output
_____no_output_____
###Markdown
This will create a `MirroredStrategy` instance which will use all the GPUs that are visible to TensorFlow, and use NCCL as the cross device communication.If you wish to use only some of the GPUs on your machine, you can do so like this:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(devices=["/gpu:0", "/gpu:1"])
###Output
_____no_output_____
###Markdown
If you wish to override the cross device communication, you can do so using the `cross_device_ops` argument by supplying an instance of `tf.distribute.CrossDeviceOps`. Currently we provide `tf.distribute.HierarchicalCopyAllReduce` and `tf.distribute.ReductionToOneDevice` as 2 other options other than `tf.distribute.NcclAllReduce` which is the default.
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(
cross_device_ops=tf.distribute.HierarchicalCopyAllReduce())
###Output
_____no_output_____
###Markdown
MultiWorkerMirroredStrategy`tf.distribute.experimental.MultiWorkerMirroredStrategy` is very similar to `MirroredStrategy`. It implements synchronous distributed training across multiple workers, each with potentially multiple GPUs. Similar to `MirroredStrategy`, it creates copies of all variables in the model on each device across all workers. It uses [CollectiveOps](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/collective_ops.py) as the multi-worker all-reduce communication method used to keep variables in sync. A collective op is a single op in the TensorFlow graph which can automatically choose an all-reduce algorithm in the TensorFlow runtime according to hardware, network topology and tensor sizes. It also implements additional performance optimizations. For example, it includes a static optimization that converts multiple all-reductions on small tensors into fewer all-reductions on larger tensors. In addition, we are designing it to have a plugin architecture - so that in the future, users will be able to plugin algorithms that are better tuned for their hardware. Note that collective ops also implement other collective operations such as broadcast and all-gather. Here is the simplest way of creating `MultiWorkerMirroredStrategy`:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()
###Output
_____no_output_____
###Markdown
`MultiWorkerMirroredStrategy` currently allows you to choose between two different implementations of collective ops. `CollectiveCommunication.RING` implements ring-based collectives using gRPC as the communication layer. `CollectiveCommunication.NCCL` uses [Nvidia's NCCL](https://developer.nvidia.com/nccl) to implement collectives. `CollectiveCommunication.AUTO` defers the choice to the runtime. The best choice of collective implementation depends upon the number and kind of GPUs, and the network interconnect in the cluster. You can specify them like so:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy(
tf.distribute.experimental.CollectiveCommunication.NCCL)
###Output
_____no_output_____
###Markdown
One of the key differences to get multi worker training going, as compared to multi-GPU training, is the multi-worker setup. "TF_CONFIG" environment variable is the standard way in TensorFlow to specify the cluster configuration to each worker that is part of the cluster. See section on ["TF_CONFIG" below](TF_CONFIG) for more details on how this can be done. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. TPUStrategy`tf.distribute.experimental.TPUStrategy` lets users run their TensorFlow training on Tensor Processing Units (TPUs). TPUs are Google's specialized ASICs designed to dramatically accelerate machine learning workloads. They are available on Google Colab, the [TensorFlow Research Cloud](https://www.tensorflow.org/tfrc) and [Google Compute Engine](https://cloud.google.com/tpu).In terms of distributed training architecture, TPUStrategy is the same `MirroredStrategy` - it implements synchronous distributed training. TPUs provide their own implementation of efficient all-reduce and other collective operations across multiple TPU cores, which are used in `TPUStrategy`. Here is how you would instantiate `TPUStrategy`.Note: To run this code in Colab, you should select TPU as the Colab runtime. See [Using TPUs]( tpu.ipynb) guide for a runnable version.```resolver = tf.distribute.cluster_resolver.TPUClusterResolver()tf.tpu.experimental.initialize_tpu_system(resolver)tpu_strategy = tf.distribute.experimental.TPUStrategy(resolver)``` `TPUClusterResolver` instance helps locate the TPUs. In Colab, you don't need to specify any arguments to it. If you want to use this for Cloud TPUs, you will need to specify the name of your TPU resource in `tpu` argument. We also need to initialize the tpu system explicitly at the start of the program. This is required before TPUs can be used for computation and should ideally be done at the beginning because it also wipes out the TPU memory so all state will be lost. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. ParameterServerStrategy`tf.distribute.experimental.ParameterServerStrategy` supports parameter servers training. It can be used either for multi-GPU synchronous local training or asynchronous multi-machine training. When used to train locally on one machine, variables are not mirrored, instead they are placed on the CPU and operations are replicated across all local GPUs. In a multi-machine setting, some machines are designated as workers and some as parameter servers. Each variable of the model is placed on one parameter server. Computation is replicated across all GPUs of the all the workers.In terms of code, it looks similar to other strategies:
###Code
ps_strategy = tf.distribute.experimental.ParameterServerStrategy()
###Output
_____no_output_____
###Markdown
For multi worker training, "TF_CONFIG" needs to specify the configuration of parameter servers and workers in your cluster, which you can read more about in ["TF_CONFIG" below](TF_CONFIG) below. So far we've talked about what are the different stategies available and how you can instantiate them. In the next few sections, we will talk about the different ways in which you can use them to distribute your training. We will show short code snippets in this guide and link off to full tutorials which you can run end to end. Using `tf.distribute.Strategy` with KerasWe've integrated `tf.distribute.Strategy` into `tf.keras` which is TensorFlow's implementation of the[Keras API specification](https://keras.io). `tf.keras` is a high-level API to build and train models. By integrating into `tf.keras` backend, we've made it seamless for Keras users to distribute their training written in the Keras training framework. The only things that need to change in a user's program are: (1) Create an instance of the appropriate `tf.distribute.Strategy` and (2) Move the creation and compiling of Keras model inside `strategy.scope`. Here is a snippet of code to do this for a very simple Keras model with one dense layer:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
model.compile(loss='mse', optimizer='sgd')
###Output
_____no_output_____
###Markdown
In this example we used `MirroredStrategy` so we can run this on a machine with multiple GPUs. `strategy.scope()` indicated which parts of the code to run distributed. Creating a model inside this scope allows us to create mirrored variables instead of regular variables. Compiling under the scope allows us to know that the user intends to train this model using this strategy. Once this is setup, you can fit your model like you would normally. `MirroredStrategy` takes care of replicating the model's training on the available GPUs, aggregating gradients etc.
###Code
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100).batch(10)
model.fit(dataset, epochs=2)
model.evaluate(dataset)
###Output
_____no_output_____
###Markdown
Here we used a `tf.data.Dataset` to provide the training and eval input. You can also use numpy arrays:
###Code
import numpy as np
inputs, targets = np.ones((100, 1)), np.ones((100, 1))
model.fit(inputs, targets, epochs=2, batch_size=10)
###Output
_____no_output_____
###Markdown
In both cases (dataset or numpy), each batch of the given input is divided equally among the multiple replicas. For instance, if using `MirroredStrategy` with 2 GPUs, each batch of size 10 will get divided among the 2 GPUs, with each receiving 5 input examples in each step. Each epoch will then train faster as you add more GPUs. Typically, you would want to increase your batch size as you add more accelerators so as to make effective use of the extra computing power. You will also need to re-tune your learning rate, depending on the model. You can use `strategy.num_replicas_in_sync` to get the number of replicas.
###Code
# Compute global batch size using number of replicas.
BATCH_SIZE_PER_REPLICA = 5
global_batch_size = (BATCH_SIZE_PER_REPLICA *
mirrored_strategy.num_replicas_in_sync)
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100)
dataset = dataset.batch(global_batch_size)
LEARNING_RATES_BY_BATCH_SIZE = {5: 0.1, 10: 0.15}
learning_rate = LEARNING_RATES_BY_BATCH_SIZE[global_batch_size]
###Output
_____no_output_____
###Markdown
What's supported now?In TF 2.0 alpha release, we support training with Keras using `MirroredStrategy`, as well as one machine parameter server using `ParameterServerStrategy`. Support for other strategies will be coming soon. The API and how to use will be exactly the same as above. If you wish to use the other strategies like `TPUStrategy` or `MultiWorkerMirorredStrategy` in Keras in TF 2.0, you can currently do so by disabling eager execution (`tf.compat.v1.disable_eager_execution()`). Another thing to note is that when using `MultiWorkerMirorredStrategy` for multiple workers with Keras, currently the user will have to explicitly shard or shuffle the data for different workers, but we will change this in the future to automatically shard the input data intelligently. Examples and TutorialsHere is a list of tutorials and examples that illustrate the above integration end to end with Keras:1. [Tutorial](../tutorials/distribute/keras.ipynb) to train MNIST with `MirroredStrategy`.2. [Tutorial](tpu.ipynb) to train Fashion MNIST with `TPUStrategy` (currently uses `disable_eager_execution`)3. Official [ResNet50](https://github.com/tensorflow/models/blob/master/official/resnet/keras/keras_imagenet_main.py) training with ImageNet data using `MirroredStrategy`.4. [ResNet50](https://github.com/tensorflow/tpu/blob/master/models/experimental/resnet50_keras/resnet50.py) trained with Imagenet data on Cloud TPus with `TPUStrategy`. Note that this example only works with TensorFlow 1.x currently. Using `tf.distribute.Strategy` with Estimator`tf.estimator` is a distributed training TensorFlow API that originally supported the async parameter server approach. Like with Keras, we've integrated `tf.distribute.Strategy` into `tf.Estimator` so that a user who is using Estimator for their training can easily change their training is distributed with very few changes to your their code. With this, estimator users can now do synchronous distributed training on multiple GPUs and multiple workers, as well as use TPUs. The usage of `tf.distribute.Strategy` with Estimator is slightly different than the Keras case. Instead of using `strategy.scope`, now we pass the strategy object into the [`RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig) for the Estimator. Here is a snippet of code that shows this with a premade estimator `LinearRegressor` and `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
config = tf.estimator.RunConfig(
train_distribute=mirrored_strategy, eval_distribute=mirrored_strategy)
regressor = tf.estimator.LinearRegressor(
feature_columns=[tf.feature_column.numeric_column('feats')],
optimizer='SGD',
config=config)
###Output
_____no_output_____
###Markdown
We use a premade Estimator here, but the same code works with a custom Estimator as well. `train_evaluate` determines how training will be distributed, and `eval_distribute` determines how evaluation will be distributed. This is another difference from Keras where we use the same strategy for both training and eval. Now we can train and evaluate this Estimator with an input function:
###Code
def input_fn():
dataset = tf.data.Dataset.from_tensors(({"feats":[1.]}, [1.]))
return dataset.repeat(1000).batch(10)
regressor.train(input_fn=input_fn, steps=10)
regressor.evaluate(input_fn=input_fn, steps=10)
###Output
_____no_output_____
###Markdown
Another difference to highlight here between Estimator and Keras is the input handling. In Keras, we mentioned that each batch of the dataset is split across the multiple replicas. In Estimator, however, the user provides an `input_fn` and have full control over how they want their data to be distributed across workers and devices. We do not do automatic splitting of batch, nor automatically shard the data across different workers. The provided `input_fn` is called once per worker, thus giving one dataset per worker. Then one batch from that dataset is fed to one replica on that worker, thereby consuming N batches for N replicas on 1 worker. In other words, the dataset returned by the `input_fn` should provide batches of size `PER_REPLICA_BATCH_SIZE`. And the global batch size for a step can be obtained as `PER_REPLICA_BATCH_SIZE * strategy.num_replicas_in_sync`. When doing multi worker training, users will also want to either split their data across the workers, or shuffle with a random seed on each. You can see an example of how to do this in the [multi-worker tutorial](../tutorials/distribute/multi_worker.ipynb). We showed an example of using `MirroredStrategy` with Estimator. You can also use `TPUStrategy` with Estimator as well, in the exact same way:```config = tf.estimator.RunConfig( train_distribute=tpu_strategy, eval_distribute=tpu_strategy)``` And similarly, you can use multi worker and parameter server strategies as well. The code remains the same, but you need to use `tf.estimator.train_and_evaluate`, and set "TF_CONFIG" environment variables for each binary running in your cluster. What's supported now?In TF 2.0 alpha release, we support training with Estimator using all strategies. Examples and TutorialsHere are some examples that show end to end usage of various strategies with Estimator:1. [Tutorial]((../tutorials/distribute/multi_worker.ipynb) to train MNIST with multiple workers using `MultiWorkerMirroredStrategy`.2. [End to end example](https://github.com/tensorflow/ecosystem/tree/master/distribution_strategy) for multi worker training in tensorflow/ecosystem using Kuberentes templates. This example starts with a Keras model and converts it to an Estimator using the `tf.keras.estimator.model_to_estimator` API. 3. Official [ResNet50](https://github.com/tensorflow/models/blob/master/official/resnet/imagenet_main.py) model, which can be trained using either `MirroredStrategy` or `MultiWorkerMirroredStrategy`.4. [ResNet50](https://github.com/tensorflow/tpu/blob/master/models/experimental/distribution_strategy/resnet_estimator.py) example with TPUStrategy. Using `tf.distribute.Strategy` with custom training loopsAs you've seen, using `tf.distrbute.Strategy` with high level APIs is only a couple lines of code change. With a little more effort, `tf.distrbute.Strategy` can also be used by other users who are not using these frameworks.TensorFlow is used for a wide variety of use cases and some users (such as researchers) require more flexibility and control over their training loops. This makes it hard for them to use the high level frameworks such as Estimator or Keras. For instance, someone using a GAN may want to take a different number of generator or discriminator steps each round. Similarly, the high level frameworks are not very suitable for Reinforcement Learning training. So these users will usually write their own training loops. For these users, we provide a core set of methods through the `tf.distrbute.Strategy` classes. Using these may require minor restructuring of the code initially, but once that is done, the user should be able to switch between GPUs / TPUs / multiple machines by just changing the strategy instance.Here we will show a brief snippet illustrating this use case for a simple training example using the same Keras model as before. Note: These APIs are still experimental and we are improving them to make them more user friendly in TensorFlow 2.0. First, we create the model and optimizer inside the strategy's scope. This ensures that any variables created with the model and optimizer are mirrored variables.
###Code
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
optimizer = tf.keras.optimizers.SGD()
###Output
_____no_output_____
###Markdown
Next, we create the input dataset and call `make_dataset_iterator` to distribute the dataset based on the strategy. This API is expected to change in the near future.
###Code
with mirrored_strategy.scope():
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(1000).batch(
global_batch_size)
input_iterator = mirrored_strategy.make_dataset_iterator(dataset)
###Output
_____no_output_____
###Markdown
Then, we define one step of the training. We will use `tf.GradientTape` to compute gradients and optimizer to apply those gradients to update our model's variables. To distribute this training step, we put in in a function `step_fn` and pass it to `strategy.experimental_run` along with the iterator created before:
###Code
@tf.function
def train_step():
def step_fn(inputs):
features, labels = inputs
with tf.GradientTape() as tape:
logits = model(features)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(
logits=logits, labels=labels)
loss = tf.reduce_sum(cross_entropy) * (1.0 / global_batch_size)
grads = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(list(zip(grads, model.trainable_variables)))
return loss
per_replica_losses = mirrored_strategy.experimental_run(
step_fn, input_iterator)
mean_loss = mirrored_strategy.reduce(
tf.distribute.ReduceOp.MEAN, per_replica_losses)
return mean_loss
###Output
_____no_output_____
###Markdown
A few other things to note in the code above: 1. We used `tf.nn.softmax_cross_entropy_with_logits` to compute the loss. And then we scaled the total loss by the global batch size. This is important because all the replicas are training in sync and number of examples in each step of training is the global batch. If you're using TensorFlow's standard losses from `tf.losses` or `tf.keras.losses`, they are distribution aware and will take care of the scaling by number of replicas whenever a strategy is in scope. 2. We used the `strategy.reduce` API to aggregate the results returned by `experimental_run`. `experimental_run` returns results from each local replica in the strategy, and there are multiple ways to consume this result. You can `reduce` them to get an aggregated value. You can also do `strategy.unwrap(results)`* to get the list of values contained in the result, one per local replica.*expected to change Finally, once we have defined the training step, we can initialize the iterator and run the training in a loop:
###Code
with mirrored_strategy.scope():
input_iterator.initialize()
for _ in range(10):
print(train_step())
###Output
_____no_output_____
###Markdown
Copyright 2018 The TensorFlow Authors.
###Code
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###Output
_____no_output_____
###Markdown
Distributed Training in TensorFlow View on TensorFlow.org Run in Google Colab View source on GitHub Overview`tf.distribute.Strategy` is a TensorFlow API to distribute trainingacross multiple GPUs, multiple machines or TPUs. Using this API, users can distribute their existing models and training code with minimal code changes.`tf.distribute.Strategy` has been designed with these key goals in mind:* Easy to use and support multiple user segments, including researchers, ML engineers, etc.* Provide good performance out of the box.* Easy switching between strategies.`tf.distribute.Strategy` can be used with TensorFlow's high level APIs, [tf.keras](https://www.tensorflow.org/guide/keras) and [tf.estimator](https://www.tensorflow.org/guide/estimators), with just a couple of lines of code change. It also provides an API that can be used to distribute custom training loops (and in general any computation using TensorFlow).In TensorFlow 2.0, users can execute their programs eagerly, or in a graph using [`tf.function`](../tutorials/eager/tf_function.ipynb). `tf.distribute.Strategy` intends to support both these modes of execution. Note that we may talk about training most of the time in this guide, but this API can also be used for distributing evaluation and prediction on different platforms.As you will see in a bit, very few changes are needed to use `tf.distribute.Strategy` with your code. This is because we have changed the underlying components of TensorFlow to become strategy-aware. This includes variables, layers, models, optimizers, metrics, summaries, and checkpoints.In this guide, we will talk about various types of strategies and how one can use them in a different situations.
###Code
# Import TensorFlow
from __future__ import absolute_import, division, print_function, unicode_literals
!pip install tf-nightly-gpu-2.0-preview
import tensorflow as tf
###Output
_____no_output_____
###Markdown
Types of strategies`tf.distribute.Strategy` intends to cover a number of use cases along different axes. Some of these combinations are currently supported and others will be added in the future. Some of these axes are:* Syncronous vs asynchronous training: These are two common ways of distributing training with data parallelism. In sync training, all workers train over different slices of input data in sync, and aggregating gradients at each step. In async training, all workers are independently training over the input data and updating variables asynchronously. Typically sync training is supported via all-reduce and async through parameter server architecture.* Hardware platform: Users may want to scale their training onto multiple GPUs on one machine, or multiple machines in a network (with 0 or more GPUs each), or on Cloud TPUs.In order to support these use cases, we have 4 strategies available. In the next section we will talk about which of these are supported in which scenarios in TF 2.0-alpha at this time. MirroredStrategy`tf.distribute.MirroredStrategy` support synchronous distributed training on multiple GPUs on one machine. It creates one replica per GPU device. Each variable in the model is mirrored across all the replicas. Together, these variables form a single conceptual variable called `MirroredVariable`. These variables are kept in sync with each other by applying identical updates.Efficient all-reduce algorithms are used to communicate the variable updates across the devices.All-reduce aggregates tensors across all the devices by adding them up, and makes them available on each device.It’s a fused algorithm that is very efficient and can reduce the overhead of synchronization significantly. There are many all-reduce algorithms and implementations available, depending on the type of communication available between devices. By default, it uses NVIDIA NCCL as the all-reduce implementation. The user can also choose between a few other options we provide, or write their own.Here is the simplest way of creating `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
###Output
_____no_output_____
###Markdown
This will create a `MirroredStrategy` instance which will use all the GPUs that are visible to TensorFlow, and use NCCL as the cross device communication.If you wish to use only some of the GPUs on your machine, you can do so like this:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(devices=["/gpu:0", "/gpu:1"])
###Output
_____no_output_____
###Markdown
If you wish to override the cross device communication, you can do so using the `cross_device_ops` argument by supplying an instance of `tf.distribute.CrossDeviceOps`. Currently we provide `tf.distribute.HierarchicalCopyAllReduce` and `tf.distribute.ReductionToOneDevice` as 2 other options other than `tf.distribute.NcclAllReduce` which is the default.
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(
cross_device_ops=tf.distribute.HierarchicalCopyAllReduce())
###Output
_____no_output_____
###Markdown
CentralStorageStrategy`tf.distribute.experimental.CentralStorageStrategy` does synchronous training as well. Variables are not mirrored, instead they are placed on the CPU and operations are replicated across all local GPUs. If there is only one GPU, all variables and operations will be placed on that GPU.Create a `CentralStorageStrategy` by:
###Code
central_storage_strategy = tf.distribute.experimental.CentralStorageStrategy()
###Output
_____no_output_____
###Markdown
This will create a `CentralStorageStrategy` instance which will use all visible GPUs and CPU. Update to variables on replicas will be aggragated before being applied to variables. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. MultiWorkerMirroredStrategy`tf.distribute.experimental.MultiWorkerMirroredStrategy` is very similar to `MirroredStrategy`. It implements synchronous distributed training across multiple workers, each with potentially multiple GPUs. Similar to `MirroredStrategy`, it creates copies of all variables in the model on each device across all workers.It uses [CollectiveOps](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/collective_ops.py) as the multi-worker all-reduce communication method used to keep variables in sync. A collective op is a single op in the TensorFlow graph which can automatically choose an all-reduce algorithm in the TensorFlow runtime according to hardware, network topology and tensor sizes.It also implements additional performance optimizations. For example, it includes a static optimization that converts multiple all-reductions on small tensors into fewer all-reductions on larger tensors. In addition, we are designing it to have a plugin architecture - so that in the future, users will be able to plugin algorithms that are better tuned for their hardware. Note that collective ops also implement other collective operations such as broadcast and all-gather.Here is the simplest way of creating `MultiWorkerMirroredStrategy`:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()
###Output
_____no_output_____
###Markdown
`MultiWorkerMirroredStrategy` currently allows you to choose between two different implementations of collective ops. `CollectiveCommunication.RING` implements ring-based collectives using gRPC as the communication layer. `CollectiveCommunication.NCCL` uses [Nvidia's NCCL](https://developer.nvidia.com/nccl) to implement collectives. `CollectiveCommunication.AUTO` defers the choice to the runtime. The best choice of collective implementation depends upon the number and kind of GPUs, and the network interconnect in the cluster. You can specify them like so:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy(
tf.distribute.experimental.CollectiveCommunication.NCCL)
###Output
_____no_output_____
###Markdown
One of the key differences to get multi worker training going, as compared to multi-GPU training, is the multi-worker setup. "TF_CONFIG" environment variable is the standard way in TensorFlow to specify the cluster configuration to each worker that is part of the cluster. See section on ["TF_CONFIG" below](TF_CONFIG) for more details on how this can be done. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. TPUStrategy`tf.distribute.experimental.TPUStrategy` lets users run their TensorFlow training on Tensor Processing Units (TPUs). TPUs are Google's specialized ASICs designed to dramatically accelerate machine learning workloads. They are available on Google Colab, the [TensorFlow Research Cloud](https://www.tensorflow.org/tfrc) and [Google Compute Engine](https://cloud.google.com/tpu).In terms of distributed training architecture, TPUStrategy is the same `MirroredStrategy` - it implements synchronous distributed training. TPUs provide their own implementation of efficient all-reduce and other collective operations across multiple TPU cores, which are used in `TPUStrategy`.Here is how you would instantiate `TPUStrategy`.Note: To run this code in Colab, you should select TPU as the Colab runtime. See [Using TPUs]( tpu.ipynb) guide for a runnable version.```resolver = tf.distribute.cluster_resolver.TPUClusterResolver()tf.tpu.experimental.initialize_tpu_system(resolver)tpu_strategy = tf.distribute.experimental.TPUStrategy(resolver)``` `TPUClusterResolver` instance helps locate the TPUs. In Colab, you don't need to specify any arguments to it. If you want to use this for Cloud TPUs, you will need to specify the name of your TPU resource in `tpu` argument. We also need to initialize the tpu system explicitly at the start of the program. This is required before TPUs can be used for computation and should ideally be done at the beginning because it also wipes out the TPU memory so all state will be lost. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. ParameterServerStrategy`tf.distribute.experimental.ParameterServerStrategy` supports parameter servers training on multiple machines. In this setup, some machines are designated as workers and some as parameter servers. Each variable of the model is placed on one parameter server. Computation is replicated across all GPUs of the all the workers.In terms of code, it looks similar to other strategies:```ps_strategy = tf.distribute.experimental.ParameterServerStrategy()``` For multi worker training, "TF_CONFIG" needs to specify the configuration of parameter servers and workers in your cluster, which you can read more about in ["TF_CONFIG" below](TF_CONFIG) below. So far we've talked about what are the different stategies available and how you can instantiate them. In the next few sections, we will talk about the different ways in which you can use them to distribute your training. We will show short code snippets in this guide and link off to full tutorials which you can run end to end. Using `tf.distribute.Strategy` with KerasWe've integrated `tf.distribute.Strategy` into `tf.keras` which is TensorFlow's implementation of the[Keras API specification](https://keras.io). `tf.keras` is a high-level API to build and train models. By integrating into `tf.keras` backend, we've made it seamless for Keras users to distribute their training written in the Keras training framework. The only things that need to change in a user's program are: (1) Create an instance of the appropriate `tf.distribute.Strategy` and (2) Move the creation and compiling of Keras model inside `strategy.scope`.Here is a snippet of code to do this for a very simple Keras model with one dense layer:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
model.compile(loss='mse', optimizer='sgd')
###Output
_____no_output_____
###Markdown
In this example we used `MirroredStrategy` so we can run this on a machine with multiple GPUs. `strategy.scope()` indicated which parts of the code to run distributed. Creating a model inside this scope allows us to create mirrored variables instead of regular variables. Compiling under the scope allows us to know that the user intends to train this model using this strategy. Once this is setup, you can fit your model like you would normally. `MirroredStrategy` takes care of replicating the model's training on the available GPUs, aggregating gradients etc.
###Code
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100).batch(10)
model.fit(dataset, epochs=2)
model.evaluate(dataset)
###Output
_____no_output_____
###Markdown
Here we used a `tf.data.Dataset` to provide the training and eval input. You can also use numpy arrays:
###Code
import numpy as np
inputs, targets = np.ones((100, 1)), np.ones((100, 1))
model.fit(inputs, targets, epochs=2, batch_size=10)
###Output
_____no_output_____
###Markdown
In both cases (dataset or numpy), each batch of the given input is divided equally among the multiple replicas. For instance, if using `MirroredStrategy` with 2 GPUs, each batch of size 10 will get divided among the 2 GPUs, with each receiving 5 input examples in each step. Each epoch will then train faster as you add more GPUs. Typically, you would want to increase your batch size as you add more accelerators so as to make effective use of the extra computing power. You will also need to re-tune your learning rate, depending on the model. You can use `strategy.num_replicas_in_sync` to get the number of replicas.
###Code
# Compute global batch size using number of replicas.
BATCH_SIZE_PER_REPLICA = 5
global_batch_size = (BATCH_SIZE_PER_REPLICA *
mirrored_strategy.num_replicas_in_sync)
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100)
dataset = dataset.batch(global_batch_size)
LEARNING_RATES_BY_BATCH_SIZE = {5: 0.1, 10: 0.15}
learning_rate = LEARNING_RATES_BY_BATCH_SIZE[global_batch_size]
###Output
_____no_output_____
###Markdown
What's supported now?In TF 2.0 alpha release, we support training with Keras using `MirroredStrategy`, as well as one machine parameter server using `ParameterServerStrategy`.Support for other strategies will be coming soon. The API and how to use will be exactly the same as above. If you wish to use the other strategies like `TPUStrategy` or `MultiWorkerMirorredStrategy` in Keras in TF 2.0, you can currently do so by disabling eager execution (`tf.compat.v1.disable_eager_execution()`). Another thing to note is that when using `MultiWorkerMirorredStrategy` for multiple workers with Keras, currently the user will have to explicitly shard or shuffle the data for different workers, but we will change this in the future to automatically shard the input data intelligently. Examples and TutorialsHere is a list of tutorials and examples that illustrate the above integration end to end with Keras:1. [Tutorial](../tutorials/distribute/keras.ipynb) to train MNIST with `MirroredStrategy`.2. Official [ResNet50](https://github.com/tensorflow/models/blob/master/official/resnet/keras/keras_imagenet_main.py) training with ImageNet data using `MirroredStrategy`.3. [ResNet50](https://github.com/tensorflow/tpu/blob/master/models/experimental/resnet50_keras/resnet50.py) trained with Imagenet data on Cloud TPus with `TPUStrategy`. Note that this example only works with TensorFlow 1.x currently. Using `tf.distribute.Strategy` with Estimator`tf.estimator` is a distributed training TensorFlow API that originally supported the async parameter server approach. Like with Keras, we've integrated `tf.distribute.Strategy` into `tf.Estimator` so that a user who is using Estimator for their training can easily change their training is distributed with very few changes to your their code. With this, estimator users can now do synchronous distributed training on multiple GPUs and multiple workers, as well as use TPUs.The usage of `tf.distribute.Strategy` with Estimator is slightly different than the Keras case. Instead of using `strategy.scope`, now we pass the strategy object into the [`RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig) for the Estimator.Here is a snippet of code that shows this with a premade estimator `LinearRegressor` and `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
config = tf.estimator.RunConfig(
train_distribute=mirrored_strategy, eval_distribute=mirrored_strategy)
regressor = tf.estimator.LinearRegressor(
feature_columns=[tf.feature_column.numeric_column('feats')],
optimizer='SGD',
config=config)
###Output
_____no_output_____
###Markdown
We use a premade Estimator here, but the same code works with a custom Estimator as well. `train_distribute` determines how training will be distributed, and `eval_distribute` determines how evaluation will be distributed. This is another difference from Keras where we use the same strategy for both training and eval.Now we can train and evaluate this Estimator with an input function:
###Code
def input_fn():
dataset = tf.data.Dataset.from_tensors(({"feats":[1.]}, [1.]))
return dataset.repeat(1000).batch(10)
regressor.train(input_fn=input_fn, steps=10)
regressor.evaluate(input_fn=input_fn, steps=10)
###Output
_____no_output_____
###Markdown
Another difference to highlight here between Estimator and Keras is the input handling. In Keras, we mentioned that each batch of the dataset is split across the multiple replicas. In Estimator, however, the user provides an `input_fn` and have full control over how they want their data to be distributed across workers and devices. We do not do automatic splitting of batch, nor automatically shard the data across different workers. The provided `input_fn` is called once per worker, thus giving one dataset per worker. Then one batch from that dataset is fed to one replica on that worker, thereby consuming N batches for N replicas on 1 worker. In other words, the dataset returned by the `input_fn` should provide batches of size `PER_REPLICA_BATCH_SIZE`. And the global batch size for a step can be obtained as `PER_REPLICA_BATCH_SIZE * strategy.num_replicas_in_sync`. When doing multi worker training, users will also want to either split their data across the workers, or shuffle with a random seed on each. You can see an example of how to do this in the [multi-worker tutorial](../tutorials/distribute/multi_worker.ipynb). We showed an example of using `MirroredStrategy` with Estimator. You can also use `TPUStrategy` with Estimator as well, in the exact same way:```config = tf.estimator.RunConfig( train_distribute=tpu_strategy, eval_distribute=tpu_strategy)``` And similarly, you can use multi worker and parameter server strategies as well. The code remains the same, but you need to use `tf.estimator.train_and_evaluate`, and set "TF_CONFIG" environment variables for each binary running in your cluster. What's supported now?In TF 2.0 alpha release, we support training with Estimator using all strategies. Examples and TutorialsHere are some examples that show end to end usage of various strategies with Estimator:1. [Tutorial](../tutorials/distribute/multi_worker.ipynb) to train MNIST with multiple workers using `MultiWorkerMirroredStrategy`.2. [End to end example](https://github.com/tensorflow/ecosystem/tree/master/distribution_strategy) for multi worker training in tensorflow/ecosystem using Kuberentes templates. This example starts with a Keras model and converts it to an Estimator using the `tf.keras.estimator.model_to_estimator` API.3. Official [ResNet50](https://github.com/tensorflow/models/blob/master/official/resnet/imagenet_main.py) model, which can be trained using either `MirroredStrategy` or `MultiWorkerMirroredStrategy`.4. [ResNet50](https://github.com/tensorflow/tpu/blob/master/models/experimental/distribution_strategy/resnet_estimator.py) example with TPUStrategy. Using `tf.distribute.Strategy` with custom training loopsAs you've seen, using `tf.distrbute.Strategy` with high level APIs is only a couple lines of code change. With a little more effort, `tf.distrbute.Strategy` can also be used by other users who are not using these frameworks.TensorFlow is used for a wide variety of use cases and some users (such as researchers) require more flexibility and control over their training loops. This makes it hard for them to use the high level frameworks such as Estimator or Keras. For instance, someone using a GAN may want to take a different number of generator or discriminator steps each round. Similarly, the high level frameworks are not very suitable for Reinforcement Learning training. So these users will usually write their own training loops.For these users, we provide a core set of methods through the `tf.distrbute.Strategy` classes. Using these may require minor restructuring of the code initially, but once that is done, the user should be able to switch between GPUs / TPUs / multiple machines by just changing the strategy instance.Here we will show a brief snippet illustrating this use case for a simple training example using the same Keras model as before.Note: These APIs are still experimental and we are improving them to make them more user friendly in TensorFlow 2.0. First, we create the model and optimizer inside the strategy's scope. This ensures that any variables created with the model and optimizer are mirrored variables.
###Code
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
optimizer = tf.keras.optimizers.SGD()
###Output
_____no_output_____
###Markdown
Next, we create the input dataset and call `make_dataset_iterator` to distribute the dataset based on the strategy. This API is expected to change in the near future.
###Code
with mirrored_strategy.scope():
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(1000).batch(
global_batch_size)
input_iterator = mirrored_strategy.make_dataset_iterator(dataset)
###Output
_____no_output_____
###Markdown
Then, we define one step of the training. We will use `tf.GradientTape` to compute gradients and optimizer to apply those gradients to update our model's variables. To distribute this training step, we put in in a function `step_fn` and pass it to `strategy.experimental_run` along with the iterator created before:
###Code
@tf.function
def train_step():
def step_fn(inputs):
features, labels = inputs
with tf.GradientTape() as tape:
logits = model(features)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(
logits=logits, labels=labels)
loss = tf.reduce_sum(cross_entropy) * (1.0 / global_batch_size)
grads = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(list(zip(grads, model.trainable_variables)))
return loss
per_replica_losses = mirrored_strategy.experimental_run(
step_fn, input_iterator)
mean_loss = mirrored_strategy.reduce(
tf.distribute.ReduceOp.SUM, per_replica_losses, axis=None)
return mean_loss
###Output
_____no_output_____
###Markdown
A few other things to note in the code above:1. We used `tf.nn.softmax_cross_entropy_with_logits` to compute the loss. And then we scaled the total loss by the global batch size. This is important because all the replicas are training in sync and number of examples in each step of training is the global batch. So the loss needs to be divided by the global batch size and not by the replica (local) batch size.2. We used the `strategy.reduce` API to aggregate the results returned by `experimental_run`. `experimental_run` returns results from each local replica in the strategy, and there are multiple ways to consume this result. You can `reduce` them to get an aggregated value. You can also do `strategy.unwrap(results)`* to get the list of values contained in the result, one per local replica.3. When `apply_gradients` is called within a distribution strategy scope, its behavior is modified. Specifically, before applying gradients on each parallel instance during synchronous training, it performs a sum-over-all-replicas of the gradients.*expected to change Finally, once we have defined the training step, we can initialize the iterator and run the training in a loop:
###Code
with mirrored_strategy.scope():
input_iterator.initialize()
for _ in range(10):
print(train_step())
###Output
_____no_output_____
###Markdown
Copyright 2018 The TensorFlow Authors.
###Code
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###Output
_____no_output_____
###Markdown
Distributed Training in TensorFlow View on TensorFlow.org Run in Google Colab View source on GitHub Overview`tf.distribute.Strategy` is a TensorFlow API to distribute trainingacross multiple GPUs, multiple machines or TPUs. Using this API, users can distribute their existing models and training code with minimal code changes.`tf.distribute.Strategy` has been designed with these key goals in mind:* Easy to use and support multiple user segments, including researchers, ML engineers, etc.* Provide good performance out of the box.* Easy switching between strategies.`tf.distribute.Strategy` can be used with TensorFlow's high level APIs, [tf.keras](https://www.tensorflow.org/guide/keras) and [tf.estimator](https://www.tensorflow.org/guide/estimators), with just a couple of lines of code change. It also provides an API that can be used to distribute custom training loops (and in general any computation using TensorFlow).In TensorFlow 2.0, users can execute their programs eagerly, or in a graph using [`tf.function`](../tutorials/eager/tf_function.ipynb). `tf.distribute.Strategy` intends to support both these modes of execution. Note that we may talk about training most of the time in this guide, but this API can also be used for distributing evaluation and prediction on different platforms.As you will see in a bit, very few changes are needed to use `tf.distribute.Strategy` with your code. This is because we have changed the underlying components of TensorFlow to become strategy-aware. This includes variables, layers, models, optimizers, metrics, summaries, and checkpoints. In this guide, we will talk about various types of strategies and how one can use them in a different situations.
###Code
# Import TensorFlow
from __future__ import absolute_import, division, print_function
!pip install tf-nightly-2.0-preview #gpu
import tensorflow as tf
###Output
_____no_output_____
###Markdown
Types of strategies`tf.distribute.Strategy` intends to cover a number of use cases along different axes. Some of these combinations are currently supported and others will be added in the future. Some of these axes are:* Syncronous vs asynchronous training: These are two common ways of distributing training with data parallelism. In sync training, all workers train over different slices of input data in sync, and aggregating gradients at each step. In async training, all workers are independently training over the input data and updating variables asynchronously. Typically sync training is supported via all-reduce and async through parameter server architecture.* Hardware platform: Users may want to scale their training onto multiple GPUs on one machine, or multiple machines in a network (with 0 or more GPUs each), or on Cloud TPUs.In order to support these use cases, we have 4 strategies available. In the next section we will talk about which of these are supported in which scenarios in TF 2.0-alpha at this time. MirroredStrategy`tf.distribute.MirroredStrategy` support synchronous distributed training on multiple GPUs on one machine. It creates one replica per GPU device. Each variable in the model is mirrored across all the replicas. Together, these variables form a single conceptual variable called `MirroredVariable`. These variables are kept in sync with each other by applying identical updates.Efficient all-reduce algorithms are used to communicate the variable updates across the devices.All-reduce aggregates tensors across all the devices by adding them up, and makes them available on each device.It’s a fused algorithm that is very efficient and can reduce the overhead of synchronization significantly. There are many all-reduce algorithms and implementations available, depending on the type of communication available between devices. By default, it uses NVIDIA NCCL as the all-reduce implementation. The user can also choose between a few other options we provide, or write their own.Here is the simplest way of creating `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
###Output
_____no_output_____
###Markdown
This will create a `MirroredStrategy` instance which will use all the GPUs that are visible to TensorFlow, and use NCCL as the cross device communication.If you wish to use only some of the GPUs on your machine, you can do so like this:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(devices=["/gpu:0", "/gpu:1"])
###Output
_____no_output_____
###Markdown
If you wish to override the cross device communication, you can do so using the `cross_device_ops` argument by supplying an instance of `tf.distribute.CrossDeviceOps`. Currently we provide `tf.distribute.HierarchicalCopyAllReduce` and `tf.distribute.ReductionToOneDevice` as 2 other options other than `tf.distribute.NcclAllReduce` which is the default.
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(
cross_device_ops=tf.distribute.HierarchicalCopyAllReduce())
###Output
_____no_output_____
###Markdown
MultiWorkerMirroredStrategy`tf.distribute.experimental.MultiWorkerMirroredStrategy` is very similar to `MirroredStrategy`. It implements synchronous distributed training across multiple workers, each with potentially multiple GPUs. Similar to `MirroredStrategy`, it creates copies of all variables in the model on each device across all workers. It uses [CollectiveOps](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/collective_ops.py) as the multi-worker all-reduce communication method used to keep variables in sync. A collective op is a single op in the TensorFlow graph which can automatically choose an all-reduce algorithm in the TensorFlow runtime according to hardware, network topology and tensor sizes. It also implements additional performance optimizations. For example, it includes a static optimization that converts multiple all-reductions on small tensors into fewer all-reductions on larger tensors. In addition, we are designing it to have a plugin architecture - so that in the future, users will be able to plugin algorithms that are better tuned for their hardware. Note that collective ops also implement other collective operations such as broadcast and all-gather. Here is the simplest way of creating `MultiWorkerMirroredStrategy`:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()
###Output
_____no_output_____
###Markdown
`MultiWorkerMirroredStrategy` currently allows you to choose between two different implementations of collective ops. `CollectiveCommunication.RING` implements ring-based collectives using gRPC as the communication layer. `CollectiveCommunication.NCCL` uses [Nvidia's NCCL](https://developer.nvidia.com/nccl) to implement collectives. `CollectiveCommunication.AUTO` defers the choice to the runtime. The best choice of collective implementation depends upon the number and kind of GPUs, and the network interconnect in the cluster. You can specify them like so:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy(
tf.distribute.experimental.CollectiveCommunication.NCCL)
###Output
_____no_output_____
###Markdown
One of the key differences to get multi worker training going, as compared to multi-GPU training, is the multi-worker setup. "TF_CONFIG" environment variable is the standard way in TensorFlow to specify the cluster configuration to each worker that is part of the cluster. See section on ["TF_CONFIG" below](TF_CONFIG) for more details on how this can be done. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. TPUStrategy`tf.distribute.experimental.TPUStrategy` lets users run their TensorFlow training on Tensor Processing Units (TPUs). TPUs are Google's specialized ASICs designed to dramatically accelerate machine learning workloads. They are available on Google Colab, the [TensorFlow Research Cloud](https://www.tensorflow.org/tfrc) and [Google Compute Engine](https://cloud.google.com/tpu).In terms of distributed training architecture, TPUStrategy is the same `MirroredStrategy` - it implements synchronous distributed training. TPUs provide their own implementation of efficient all-reduce and other collective operations across multiple TPU cores, which are used in `TPUStrategy`. Here is how you would instantiate `TPUStrategy`.Note: To run this code in Colab, you should select TPU as the Colab runtime. See [Using TPUs]( tpu.ipynb) guide for a runnable version.```resolver = tf.distribute.cluster_resolver.TPUClusterResolver()tf.tpu.experimental.initialize_tpu_system(resolver)tpu_strategy = tf.distribute.experimental.TPUStrategy(resolver)``` `TPUClusterResolver` instance helps locate the TPUs. In Colab, you don't need to specify any arguments to it. If you want to use this for Cloud TPUs, you will need to specify the name of your TPU resource in `tpu` argument. We also need to initialize the tpu system explicitly at the start of the program. This is required before TPUs can be used for computation and should ideally be done at the beginning because it also wipes out the TPU memory so all state will be lost. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. ParameterServerStrategy`tf.distribute.experimental.ParameterServerStrategy` supports parameter servers training. It can be used either for multi-GPU synchronous local training or asynchronous multi-machine training. When used to train locally on one machine, variables are not mirrored, instead they are placed on the CPU and operations are replicated across all local GPUs. In a multi-machine setting, some machines are designated as workers and some as parameter servers. Each variable of the model is placed on one parameter server. Computation is replicated across all GPUs of the all the workers.In terms of code, it looks similar to other strategies:
###Code
ps_strategy = tf.distribute.experimental.ParameterServerStrategy()
###Output
_____no_output_____
###Markdown
For multi worker training, "TF_CONFIG" needs to specify the configuration of parameter servers and workers in your cluster, which you can read more about in ["TF_CONFIG" below](TF_CONFIG) below. So far we've talked about what are the different stategies available and how you can instantiate them. In the next few sections, we will talk about the different ways in which you can use them to distribute your training. We will show short code snippets in this guide and link off to full tutorials which you can run end to end. Using `tf.distribute.Strategy` with KerasWe've integrated `tf.distribute.Strategy` into `tf.keras` which is TensorFlow's implementation of the[Keras API specification](https://keras.io). `tf.keras` is a high-level API to build and train models. By integrating into `tf.keras` backend, we've made it seamless for Keras users to distribute their training written in the Keras training framework. The only things that need to change in a user's program are: (1) Create an instance of the appropriate `tf.distribute.Strategy` and (2) Move the creation and compiling of Keras model inside `strategy.scope`. Here is a snippet of code to do this for a very simple Keras model with one dense layer:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
model.compile(loss='mse', optimizer='sgd')
###Output
_____no_output_____
###Markdown
In this example we used `MirroredStrategy` so we can run this on a machine with multiple GPUs. `strategy.scope()` indicated which parts of the code to run distributed. Creating a model inside this scope allows us to create mirrored variables instead of regular variables. Compiling under the scope allows us to know that the user intends to train this model using this strategy. Once this is setup, you can fit your model like you would normally. `MirroredStrategy` takes care of replicating the model's training on the available GPUs, aggregating gradients etc.
###Code
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100).batch(10)
model.fit(dataset, epochs=2)
model.evaluate(dataset)
###Output
_____no_output_____
###Markdown
Here we used a `tf.data.Dataset` to provide the training and eval input. You can also use numpy arrays:
###Code
import numpy as np
inputs, targets = np.ones((100, 1)), np.ones((100, 1))
model.fit(inputs, targets, epochs=2, batch_size=10)
###Output
_____no_output_____
###Markdown
In both cases (dataset or numpy), each batch of the given input is divided equally among the multiple replicas. For instance, if using `MirroredStrategy` with 2 GPUs, each batch of size 10 will get divided among the 2 GPUs, with each receiving 5 input examples in each step. Each epoch will then train faster as you add more GPUs. Typically, you would want to increase your batch size as you add more accelerators so as to make effective use of the extra computing power. You will also need to re-tune your learning rate, depending on the model. You can use `strategy.num_replicas_in_sync` to get the number of replicas.
###Code
# Compute global batch size using number of replicas.
BATCH_SIZE_PER_REPLICA = 5
global_batch_size = (BATCH_SIZE_PER_REPLICA *
mirrored_strategy.num_replicas_in_sync)
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100)
dataset = dataset.batch(global_batch_size)
LEARNING_RATES_BY_BATCH_SIZE = {5: 0.1, 10: 0.15}
learning_rate = LEARNING_RATES_BY_BATCH_SIZE[global_batch_size]
###Output
_____no_output_____
###Markdown
What's supported now?In TF 2.0 alpha release, we support training with Keras using `MirroredStrategy`, as well as one machine parameter server using `ParameterServerStrategy`. Support for other strategies will be coming soon. The API and how to use will be exactly the same as above. If you wish to use the other strategies like `TPUStrategy` or `MultiWorkerMirorredStrategy` in Keras in TF 2.0, you can currently do so by disabling eager execution (`tf.compat.v1.disable_eager_execution()`). Another thing to note is that when using `MultiWorkerMirorredStrategy` for multiple workers with Keras, currently the user will have to explicitly shard or shuffle the data for different workers, but we will change this in the future to automatically shard the input data intelligently. Examples and TutorialsHere is a list of tutorials and examples that illustrate the above integration end to end with Keras:1. [Tutorial](../tutorials/distribute/keras.ipynb) to train MNIST with `MirroredStrategy`.2. [Tutorial](tpu.ipynb) to train Fashion MNIST with `TPUStrategy` (currently uses `disable_eager_execution`)3. Official [ResNet50](https://github.com/tensorflow/models/blob/master/official/resnet/keras/keras_imagenet_main.py) training with ImageNet data using `MirroredStrategy`.4. [ResNet50](https://github.com/tensorflow/tpu/blob/master/models/experimental/resnet50_keras/resnet50.py) trained with Imagenet data on Cloud TPus with `TPUStrategy`. Note that this example only works with TensorFlow 1.x currently. Using `tf.distribute.Strategy` with Estimator`tf.estimator` is a distributed training TensorFlow API that originally supported the async parameter server approach. Like with Keras, we've integrated `tf.distribute.Strategy` into `tf.Estimator` so that a user who is using Estimator for their training can easily change their training is distributed with very few changes to your their code. With this, estimator users can now do synchronous distributed training on multiple GPUs and multiple workers, as well as use TPUs. The usage of `tf.distribute.Strategy` with Estimator is slightly different than the Keras case. Instead of using `strategy.scope`, now we pass the strategy object into the [`RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig) for the Estimator. Here is a snippet of code that shows this with a premade estimator `LinearRegressor` and `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
config = tf.estimator.RunConfig(
train_distribute=mirrored_strategy, eval_distribute=mirrored_strategy)
regressor = tf.estimator.LinearRegressor(
feature_columns=[tf.feature_column.numeric_column('feats')],
optimizer='SGD',
config=config)
###Output
_____no_output_____
###Markdown
We use a premade Estimator here, but the same code works with a custom Estimator as well. `train_evaluate` determines how training will be distributed, and `eval_distribute` determines how evaluation will be distributed. This is another difference from Keras where we use the same strategy for both training and eval. Now we can train and evaluate this Estimator with an input function:
###Code
def input_fn():
dataset = tf.data.Dataset.from_tensors(({"feats":[1.]}, [1.]))
return dataset.repeat(1000).batch(10)
regressor.train(input_fn=input_fn, steps=10)
regressor.evaluate(input_fn=input_fn, steps=10)
###Output
_____no_output_____
###Markdown
Another difference to highlight here between Estimator and Keras is the input handling. In Keras, we mentioned that each batch of the dataset is split across the multiple replicas. In Estimator, however, the user provides an `input_fn` and have full control over how they want their data to be distributed across workers and devices. We do not do automatic splitting of batch, nor automatically shard the data across different workers. The provided `input_fn` is called once per worker, thus giving one dataset per worker. Then one batch from that dataset is fed to one replica on that worker, thereby consuming N batches for N replicas on 1 worker. In other words, the dataset returned by the `input_fn` should provide batches of size `PER_REPLICA_BATCH_SIZE`. And the global batch size for a step can be obtained as `PER_REPLICA_BATCH_SIZE * strategy.num_replicas_in_sync`. When doing multi worker training, users will also want to either split their data across the workers, or shuffle with a random seed on each. You can see an example of how to do this in the [multi-worker tutorial](../tutorials/distribute/multi_worker.ipynb). We showed an example of using `MirroredStrategy` with Estimator. You can also use `TPUStrategy` with Estimator as well, in the exact same way:```config = tf.estimator.RunConfig( train_distribute=tpu_strategy, eval_distribute=tpu_strategy)``` And similarly, you can use multi worker and parameter server strategies as well. The code remains the same, but you need to use `tf.estimator.train_and_evaluate`, and set "TF_CONFIG" environment variables for each binary running in your cluster. What's supported now?In TF 2.0 alpha release, we support training with Estimator using all strategies. Examples and TutorialsHere are some examples that show end to end usage of various strategies with Estimator:1. [Tutorial]((../tutorials/distribute/multi_worker.ipynb) to train MNIST with multiple workers using `MultiWorkerMirroredStrategy`.2. [End to end example](https://github.com/tensorflow/ecosystem/tree/master/distribution_strategy) for multi worker training in tensorflow/ecosystem using Kuberentes templates. This example starts with a Keras model and converts it to an Estimator using the `tf.keras.estimator.model_to_estimator` API. 3. Official [ResNet50](https://github.com/tensorflow/models/blob/master/official/resnet/imagenet_main.py) model, which can be trained using either `MirroredStrategy` or `MultiWorkerMirroredStrategy`.4. [ResNet50](https://github.com/tensorflow/tpu/blob/master/models/experimental/distribution_strategy/resnet_estimator.py) example with TPUStrategy. Using `tf.distribute.Strategy` with custom training loopsAs you've seen, using `tf.distrbute.Strategy` with high level APIs is only a couple lines of code change. With a little more effort, `tf.distrbute.Strategy` can also be used by other users who are not using these frameworks.TensorFlow is used for a wide variety of use cases and some users (such as researchers) require more flexibility and control over their training loops. This makes it hard for them to use the high level frameworks such as Estimator or Keras. For instance, someone using a GAN may want to take a different number of generator or discriminator steps each round. Similarly, the high level frameworks are not very suitable for Reinforcement Learning training. So these users will usually write their own training loops. For these users, we provide a core set of methods through the `tf.distrbute.Strategy` classes. Using these may require minor restructuring of the code initially, but once that is done, the user should be able to switch between GPUs / TPUs / multiple machines by just changing the strategy instance.Here we will show a brief snippet illustrating this use case for a simple training example using the same Keras model as before. Note: These APIs are still experimental and we are improving them to make them more user friendly in TensorFlow 2.0. First, we create the model and optimizer inside the strategy's scope. This ensures that any variables created with the model and optimizer are mirrored variables.
###Code
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
optimizer = tf.keras.optimizers.SGD()
###Output
_____no_output_____
###Markdown
Next, we create the input dataset and call `make_dataset_iterator` to distribute the dataset based on the strategy. This API is expected to change in the near future.
###Code
with mirrored_strategy.scope():
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(1000).batch(
global_batch_size)
input_iterator = mirrored_strategy.make_dataset_iterator(dataset)
###Output
_____no_output_____
###Markdown
Then, we define one step of the training. We will use `tf.GradientTape` to compute gradients and optimizer to apply those gradients to update our model's variables. To distribute this training step, we put in in a function `step_fn` and pass it to `strategy.experimental_run` along with the iterator created before:
###Code
@tf.function
def train_step():
def step_fn(inputs):
features, labels = inputs
with tf.GradientTape() as tape:
logits = model(features)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(
logits=logits, labels=labels)
loss = tf.reduce_sum(cross_entropy) * (1.0 / global_batch_size)
grads = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(list(zip(grads, model.trainable_variables)))
return loss
per_replica_losses = mirrored_strategy.experimental_run(
step_fn, input_iterator)
mean_loss = mirrored_strategy.reduce(
tf.distribute.ReduceOp.MEAN, per_replica_losses)
return mean_loss
###Output
_____no_output_____
###Markdown
A few other things to note in the code above: 1. We used `tf.nn.softmax_cross_entropy_with_logits` to compute the loss. And then we scaled the total loss by the global batch size. This is important because all the replicas are training in sync and number of examples in each step of training is the global batch. If you're using TensorFlow's standard losses from `tf.losses` or `tf.keras.losses`, they are distribution aware and will take care of the scaling by number of replicas whenever a strategy is in scope. 2. We used the `strategy.reduce` API to aggregate the results returned by `experimental_run`. `experimental_run` returns results from each local replica in the strategy, and there are multiple ways to consume this result. You can `reduce` them to get an aggregated value. You can also do `strategy.unwrap(results)`* to get the list of values contained in the result, one per local replica.*expected to change Finally, once we have defined the training step, we can initialize the iterator and run the training in a loop:
###Code
with mirrored_strategy.scope():
input_iterator.initialize()
for _ in range(10):
print(train_step())
###Output
_____no_output_____
###Markdown
Copyright 2018 The TensorFlow Authors.
###Code
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###Output
_____no_output_____
###Markdown
Distributed training in TensorFlow View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook Overview`tf.distribute.Strategy` is a TensorFlow API to distribute training across multiple GPUs, multiple machines or TPUs. Using this API, users can distribute their existing models and training code with minimal code changes.`tf.distribute.Strategy` has been designed with these key goals in mind:* Easy to use and support multiple user segments, including researchers, ML engineers, etc.* Provide good performance out of the box.* Easy switching between strategies.`tf.distribute.Strategy` can be used with TensorFlow's high level APIs, [tf.keras](https://www.tensorflow.org/guide/keras) and [tf.estimator](https://www.tensorflow.org/guide/estimators), with just a couple of lines of code change. It also provides an API that can be used to distribute custom training loops (and in general any computation using TensorFlow).In TensorFlow 2.0, users can execute their programs eagerly, or in a graph using [`tf.function`](../tutorials/eager/tf_function.ipynb). `tf.distribute.Strategy` intends to support both these modes of execution. Note that we may talk about training most of the time in this guide, but this API can also be used for distributing evaluation and prediction on different platforms.As you will see in a bit, very few changes are needed to use `tf.distribute.Strategy` with your code. This is because we have changed the underlying components of TensorFlow to become strategy-aware. This includes variables, layers, models, optimizers, metrics, summaries, and checkpoints.In this guide, we will talk about various types of strategies and how one can use them in a different situations.
###Code
# Import TensorFlow
from __future__ import absolute_import, division, print_function, unicode_literals
!pip install tensorflow-gpu==2.0.0-beta1
import tensorflow as tf
###Output
_____no_output_____
###Markdown
Types of strategies`tf.distribute.Strategy` intends to cover a number of use cases along different axes. Some of these combinations are currently supported and others will be added in the future. Some of these axes are:* Synchronous vs asynchronous training: These are two common ways of distributing training with data parallelism. In sync training, all workers train over different slices of input data in sync, and aggregating gradients at each step. In async training, all workers are independently training over the input data and updating variables asynchronously. Typically sync training is supported via all-reduce and async through parameter server architecture.* Hardware platform: Users may want to scale their training onto multiple GPUs on one machine, or multiple machines in a network (with 0 or more GPUs each), or on Cloud TPUs.In order to support these use cases, we have 5 strategies available. In the next section we will talk about which of these are supported in which scenarios in TF 2.0-beta at this time. Here is a quick overview:| Training API | MirroredStrategy | TPUStrategy | MultiWorkerMirroredStrategy | CentralStorageStrategy | ParameterServerStrategy ||:----------------------- |:------------------- |:--------------------- |:--------------------------------- |:--------------------------------- |:-------------------------- || **Keras API** | Supported | Support planned in 2.0 RC | Experimental support | Experimental support | Supported planned post 2.0 || **Custom training loop** | Experimental support | Experimental support | Support planned post 2.0 RC | Support planned in 2.0 RC | No support yet || **Estimator API** | Limited Support | Limited Support | Limited Support | Limited Support | Limited Support | MirroredStrategy`tf.distribute.MirroredStrategy` supports synchronous distributed training on multiple GPUs on one machine. It creates one replica per GPU device. Each variable in the model is mirrored across all the replicas. Together, these variables form a single conceptual variable called `MirroredVariable`. These variables are kept in sync with each other by applying identical updates.Efficient all-reduce algorithms are used to communicate the variable updates across the devices.All-reduce aggregates tensors across all the devices by adding them up, and makes them available on each device.It’s a fused algorithm that is very efficient and can reduce the overhead of synchronization significantly. There are many all-reduce algorithms and implementations available, depending on the type of communication available between devices. By default, it uses NVIDIA NCCL as the all-reduce implementation. The user can also choose between a few other options we provide, or write their own.Here is the simplest way of creating `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
###Output
_____no_output_____
###Markdown
This will create a `MirroredStrategy` instance which will use all the GPUs that are visible to TensorFlow, and use NCCL as the cross device communication.If you wish to use only some of the GPUs on your machine, you can do so like this:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(devices=["/gpu:0", "/gpu:1"])
###Output
_____no_output_____
###Markdown
If you wish to override the cross device communication, you can do so using the `cross_device_ops` argument by supplying an instance of `tf.distribute.CrossDeviceOps`. Currently we provide `tf.distribute.HierarchicalCopyAllReduce` and `tf.distribute.ReductionToOneDevice` as 2 other options other than `tf.distribute.NcclAllReduce` which is the default.
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(
cross_device_ops=tf.distribute.HierarchicalCopyAllReduce())
###Output
_____no_output_____
###Markdown
CentralStorageStrategy`tf.distribute.experimental.CentralStorageStrategy` does synchronous training as well. Variables are not mirrored, instead they are placed on the CPU and operations are replicated across all local GPUs. If there is only one GPU, all variables and operations will be placed on that GPU.Create an instance of `CentralStorageStrategy` by:
###Code
central_storage_strategy = tf.distribute.experimental.CentralStorageStrategy()
###Output
_____no_output_____
###Markdown
This will create a `CentralStorageStrategy` instance which will use all visible GPUs and CPU. Update to variables on replicas will be aggregated before being applied to variables. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. MultiWorkerMirroredStrategy`tf.distribute.experimental.MultiWorkerMirroredStrategy` is very similar to `MirroredStrategy`. It implements synchronous distributed training across multiple workers, each with potentially multiple GPUs. Similar to `MirroredStrategy`, it creates copies of all variables in the model on each device across all workers.It uses [CollectiveOps](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/collective_ops.py) as the multi-worker all-reduce communication method used to keep variables in sync. A collective op is a single op in the TensorFlow graph which can automatically choose an all-reduce algorithm in the TensorFlow runtime according to hardware, network topology and tensor sizes.It also implements additional performance optimizations. For example, it includes a static optimization that converts multiple all-reductions on small tensors into fewer all-reductions on larger tensors. In addition, we are designing it to have a plugin architecture - so that in the future, users will be able to plugin algorithms that are better tuned for their hardware. Note that collective ops also implement other collective operations such as broadcast and all-gather.Here is the simplest way of creating `MultiWorkerMirroredStrategy`:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()
###Output
_____no_output_____
###Markdown
`MultiWorkerMirroredStrategy` currently allows you to choose between two different implementations of collective ops. `CollectiveCommunication.RING` implements ring-based collectives using gRPC as the communication layer. `CollectiveCommunication.NCCL` uses [Nvidia's NCCL](https://developer.nvidia.com/nccl) to implement collectives. `CollectiveCommunication.AUTO` defers the choice to the runtime. The best choice of collective implementation depends upon the number and kind of GPUs, and the network interconnect in the cluster. You can specify them in the following way:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy(
tf.distribute.experimental.CollectiveCommunication.NCCL)
###Output
_____no_output_____
###Markdown
One of the key differences to get multi worker training going, as compared to multi-GPU training, is the multi-worker setup. "TF_CONFIG" environment variable is the standard way in TensorFlow to specify the cluster configuration to each worker that is part of the cluster. See section on ["TF_CONFIG" below](TF_CONFIG) for more details on how this can be done. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. TPUStrategy`tf.distribute.experimental.TPUStrategy` lets users run their TensorFlow training on Tensor Processing Units (TPUs). TPUs are Google's specialized ASICs designed to dramatically accelerate machine learning workloads. They are available on Google Colab, the [TensorFlow Research Cloud](https://www.tensorflow.org/tfrc) and [Google Compute Engine](https://cloud.google.com/tpu).In terms of distributed training architecture, TPUStrategy is the same `MirroredStrategy` - it implements synchronous distributed training. TPUs provide their own implementation of efficient all-reduce and other collective operations across multiple TPU cores, which are used in `TPUStrategy`.Here is how you would instantiate `TPUStrategy`.Note: To run this code in Colab, you should select TPU as the Colab runtime. We will have a tutorial soon that will demonstrate how you can use TPUStrategy.```cluster_resolver = tf.distribute.cluster_resolver.TPUClusterResolver( tpu=tpu_address)tf.config.experimental_connect_to_host(cluster_resolver.master())tf.tpu.experimental.initialize_tpu_system(cluster_resolver)tpu_strategy = tf.distribute.experimental.TPUStrategy(cluster_resolver)``` `TPUClusterResolver` instance helps locate the TPUs. In Colab, you don't need to specify any arguments to it. If you want to use this for Cloud TPUs, you will need to specify the name of your TPU resource in `tpu` argument. We also need to initialize the tpu system explicitly at the start of the program. This is required before TPUs can be used for computation and should ideally be done at the beginning because it also wipes out the TPU memory so all state will be lost. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. ParameterServerStrategy`tf.distribute.experimental.ParameterServerStrategy` supports parameter servers training on multiple machines. In this setup, some machines are designated as workers and some as parameter servers. Each variable of the model is placed on one parameter server. Computation is replicated across all GPUs of all the workers.In terms of code, it looks similar to other strategies:```ps_strategy = tf.distribute.experimental.ParameterServerStrategy()``` For multi worker training, "TF_CONFIG" needs to specify the configuration of parameter servers and workers in your cluster, which you can read more about in ["TF_CONFIG" below](TF_CONFIG) below. So far we've talked about what are the different stategies available and how you can instantiate them. In the next few sections, we will talk about the different ways in which you can use them to distribute your training. We will show short code snippets in this guide and link off to full tutorials which you can run end to end. Using `tf.distribute.Strategy` with KerasWe've integrated `tf.distribute.Strategy` into `tf.keras` which is TensorFlow's implementation of the[Keras API specification](https://keras.io). `tf.keras` is a high-level API to build and train models. By integrating into `tf.keras` backend, we've made it seamless for Keras users to distribute their training written in the Keras training framework. The only things that need to change in a user's program are: (1) Create an instance of the appropriate `tf.distribute.Strategy` and (2) Move the creation and compiling of Keras model inside `strategy.scope`. We support all types of Keras models - sequential, functional and subclassed.Here is a snippet of code to do this for a very simple Keras model with one dense layer:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
model.compile(loss='mse', optimizer='sgd')
###Output
_____no_output_____
###Markdown
In this example we used `MirroredStrategy` so we can run this on a machine with multiple GPUs. `strategy.scope()` indicated which parts of the code to run distributed. Creating a model inside this scope allows us to create mirrored variables instead of regular variables. Compiling under the scope allows us to know that the user intends to train this model using this strategy. Once this is setup, you can fit your model like you would normally. `MirroredStrategy` takes care of replicating the model's training on the available GPUs, aggregating gradients etc.
###Code
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100).batch(10)
model.fit(dataset, epochs=2)
model.evaluate(dataset)
###Output
_____no_output_____
###Markdown
Here we used a `tf.data.Dataset` to provide the training and eval input. You can also use numpy arrays:
###Code
import numpy as np
inputs, targets = np.ones((100, 1)), np.ones((100, 1))
model.fit(inputs, targets, epochs=2, batch_size=10)
###Output
_____no_output_____
###Markdown
In both cases (dataset or numpy), each batch of the given input is divided equally among the multiple replicas. For instance, if using `MirroredStrategy` with 2 GPUs, each batch of size 10 will get divided among the 2 GPUs, with each receiving 5 input examples in each step. Each epoch will then train faster as you add more GPUs. Typically, you would want to increase your batch size as you add more accelerators so as to make effective use of the extra computing power. You will also need to re-tune your learning rate, depending on the model. You can use `strategy.num_replicas_in_sync` to get the number of replicas.
###Code
# Compute global batch size using number of replicas.
BATCH_SIZE_PER_REPLICA = 5
global_batch_size = (BATCH_SIZE_PER_REPLICA *
mirrored_strategy.num_replicas_in_sync)
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100)
dataset = dataset.batch(global_batch_size)
LEARNING_RATES_BY_BATCH_SIZE = {5: 0.1, 10: 0.15}
learning_rate = LEARNING_RATES_BY_BATCH_SIZE[global_batch_size]
###Output
_____no_output_____
###Markdown
What's supported now?In TF 2.0 beta release, we support training with Keras using `MirroredStrategy`, `CentralStorageStrategy` and `MultiWorkerMirroredStrategy`. Both `CentralStorageStrategy` and `MultiWorkerMirroredStrategy` are currently experimental APIs and are subject to change.Support for other strategies will be coming soon. The API and how to use will be exactly the same as above.| Training API | MirroredStrategy | TPUStrategy | MultiWorkerMirroredStrategy | CentralStorageStrategy | ParameterServerStrategy ||---------------- |--------------------- |----------------------- |----------------------------------- |----------------------------------- |--------------------------- || Keras APIs | Supported | Support planned in 2.0 RC | Experimental support | Experimental support | Support planned in post 2.0 | Examples and TutorialsHere is a list of tutorials and examples that illustrate the above integration end to end with Keras:1. Tutorial to train [MNIST](../tutorials/distribute/keras.ipynb) with `MirroredStrategy`.2. Official [ResNet50](https://github.com/tensorflow/models/blob/master/official/resnet/keras/keras_imagenet_main.py) training with ImageNet data using `MirroredStrategy`.3. [ResNet50](https://github.com/tensorflow/tpu/blob/master/models/experimental/resnet50_keras/resnet50.py) trained with Imagenet data on Cloud TPus with `TPUStrategy`. Note that this example only works with TensorFlow 1.x currently.4. [Tutorial](../tutorials/distribute/multi_worker_with_keras.ipynb) to train MNIST using `MultiWorkerMirroredStrategy`.5. [NCF](https://github.com/tensorflow/models/blob/master/official/recommendation/ncf_keras_main.py) trained using `MirroredStrategy`.2. [Transformer]( https://github.com/tensorflow/models/blob/master/official/transformer/v2/transformer_main.py) trained using `MirroredStrategy`. Using `tf.distribute.Strategy` with custom training loopsAs you've seen, using `tf.distribute.Strategy` with high level APIs is only a couple lines of code change. With a little more effort, `tf.distribute.Strategy` can also be used by other users who are not using these frameworks.TensorFlow is used for a wide variety of use cases and some users (such as researchers) require more flexibility and control over their training loops. This makes it hard for them to use the high level frameworks such as Estimator or Keras. For instance, someone using a GAN may want to take a different number of generator or discriminator steps each round. Similarly, the high level frameworks are not very suitable for Reinforcement Learning training. So these users will usually write their own training loops.For these users, we provide a core set of methods through the `tf.distribute.Strategy` classes. Using these may require minor restructuring of the code initially, but once that is done, the user should be able to switch between GPUs / TPUs / multiple machines by just changing the strategy instance.Here we will show a brief snippet illustrating this use case for a simple training example using the same Keras model as before. First, we create the model and optimizer inside the strategy's scope. This ensures that any variables created with the model and optimizer are mirrored variables.
###Code
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
optimizer = tf.keras.optimizers.SGD()
###Output
_____no_output_____
###Markdown
Next, we create the input dataset and call `tf.distribute.Strategy.experimental_distribute_dataset` to distribute the dataset based on the strategy.
###Code
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(1000).batch(
global_batch_size)
dist_dataset = mirrored_strategy.experimental_distribute_dataset(dataset)
###Output
_____no_output_____
###Markdown
Then, we define one step of the training. We will use `tf.GradientTape` to compute gradients and optimizer to apply those gradients to update our model's variables. To distribute this training step, we put in in a function `step_fn` and pass it to `tf.distrbute.Strategy.experimental_run_v2` along with the dataset inputs that we get from `dist_dataset` created before:
###Code
@tf.function
def train_step(dist_inputs):
def step_fn(inputs):
features, labels = inputs
with tf.GradientTape() as tape:
logits = model(features)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(
logits=logits, labels=labels)
loss = tf.reduce_sum(cross_entropy) * (1.0 / global_batch_size)
grads = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(list(zip(grads, model.trainable_variables)))
return cross_entropy
per_example_losses = mirrored_strategy.experimental_run_v2(
step_fn, args=(dist_inputs,))
mean_loss = mirrored_strategy.reduce(
tf.distribute.ReduceOp.MEAN, per_example_losses, axis=0)
return mean_loss
###Output
_____no_output_____
###Markdown
A few other things to note in the code above:1. We used `tf.nn.softmax_cross_entropy_with_logits` to compute the loss. And then we scaled the total loss by the global batch size. This is important because all the replicas are training in sync and number of examples in each step of training is the global batch. So the loss needs to be divided by the global batch size and not by the replica (local) batch size.2. We used the `tf.distribute.Strategy.reduce` API to aggregate the results returned by `tf.distribute.Strategy.experimental_run_v2`. `tf.distribute.Strategy.experimental_run_v2` returns results from each local replica in the strategy, and there are multiple ways to consume this result. You can `reduce` them to get an aggregated value. You can also do `tf.distribute.Strategy.experimental_local_results` to get the list of values contained in the result, one per local replica.3. When `apply_gradients` is called within a distribution strategy scope, its behavior is modified. Specifically, before applying gradients on each parallel instance during synchronous training, it performs a sum-over-all-replicas of the gradients. Finally, once we have defined the training step, we can iterate over `dist_dataset` and run the training in a loop:
###Code
with mirrored_strategy.scope():
for inputs in dist_dataset:
print(train_step(inputs))
###Output
_____no_output_____
###Markdown
In the example above, we iterated over the `dist_dataset` to provide input to your training. We also provide the `tf.distribute.Strategy.make_experimental_numpy_dataset` to support numpy inputs. You can use this API to create a dataset before calling `tf.distribute.Strategy.experimental_distribute_dataset`.Another way of iterating over your data is to explicitly use iterators. You may want to do this when you want to run for a given number of steps as opposed to iterating over the entire dataset.The above iteration would now be modified to first create an iterator and then explicity call `next` on it to get the input data.
###Code
with mirrored_strategy.scope():
iterator = iter(dist_dataset)
for _ in range(10):
print(train_step(next(iterator)))
###Output
_____no_output_____
###Markdown
This covers the simplest case of using `tf.distribute.Strategy` API to distribute custom training loops. We are in the process of improving these APIs. Since this use case requires more work on the part of the user, we will be publishing a separate detailed guide in the future. What's supported now?In TF 2.0 beta release, we support training with custom training loops using `MirroredStrategy` as shown above and `TPUStrategy`. `MultiWorkerMirorredStrategy` support will be coming in the future.| Training API | MirroredStrategy | TPUStrategy | MultiWorkerMirroredStrategy | CentralStorageStrategy | ParameterServerStrategy ||:----------------------- |:------------------- |:------------------- |:----------------------------- |:------------------------ |:------------------------- || Custom Training Loop | Supported | Supported | Support planned in 2.0 RC | Support planned in 2.0 RC | No support yet | Examples and TutorialsHere are some examples for using distribution strategy with custom training loops:1. [Tutorial](../tutorials/distribute/training_loops.ipynb) to train MNIST using `MirroredStrategy`.2. [DenseNet](https://github.com/tensorflow/examples/blob/master/tensorflow_examples/models/densenet/distributed_train.py) example using `MirroredStrategy`.1. [BERT](https://github.com/tensorflow/models/blob/master/official/bert/run_classifier.py) example trained using `MirroredStrategy` and `TPUStrategy`.This example is particularly helpful for understanding how to load from a checkpoint and generate periodic checkpoints during distributed training etc.2. [NCF](https://github.com/tensorflow/models/blob/master/official/recommendation/ncf_keras_main.py) example trained using `MirroredStrategy` that can be enabled using the `keras_use_ctl` flag.3. [NMT](https://github.com/tensorflow/examples/blob/master/tensorflow_examples/models/nmt_with_attention/distributed_train.py) example trained using `MirroredStrategy`. Using `tf.distribute.Strategy` with Estimator`tf.estimator` is a distributed training TensorFlow API that originally supported the async parameter server approach. Like with Keras, we've integrated `tf.distribute.Strategy` into `tf.Estimator` so that a user who is using Estimator for their training can easily change their training is distributed with very few changes to your their code. With this, estimator users can now do synchronous distributed training on multiple GPUs and multiple workers, as well as use TPUs. This support in estimator is, however, limited. See [What's supported now](estimator_support) section below for more details.The usage of `tf.distribute.Strategy` with Estimator is slightly different than the Keras case. Instead of using `strategy.scope`, now we pass the strategy object into the [`RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig) for the Estimator.Here is a snippet of code that shows this with a premade estimator `LinearRegressor` and `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
config = tf.estimator.RunConfig(
train_distribute=mirrored_strategy, eval_distribute=mirrored_strategy)
regressor = tf.estimator.LinearRegressor(
feature_columns=[tf.feature_column.numeric_column('feats')],
optimizer='SGD',
config=config)
###Output
_____no_output_____
###Markdown
We use a premade Estimator here, but the same code works with a custom Estimator as well. `train_distribute` determines how training will be distributed, and `eval_distribute` determines how evaluation will be distributed. This is another difference from Keras where we use the same strategy for both training and eval.Now we can train and evaluate this Estimator with an input function:
###Code
def input_fn():
dataset = tf.data.Dataset.from_tensors(({"feats":[1.]}, [1.]))
return dataset.repeat(1000).batch(10)
regressor.train(input_fn=input_fn, steps=10)
regressor.evaluate(input_fn=input_fn, steps=10)
###Output
_____no_output_____
###Markdown
Copyright 2018 The TensorFlow Authors.
###Code
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###Output
_____no_output_____
###Markdown
Distributed training in TensorFlow View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook Overview`tf.distribute.Strategy` is a TensorFlow API to distribute training across multiple GPUs, multiple machines or TPUs. Using this API, users can distribute their existing models and training code with minimal code changes.`tf.distribute.Strategy` has been designed with these key goals in mind:* Easy to use and support multiple user segments, including researchers, ML engineers, etc.* Provide good performance out of the box.* Easy switching between strategies.`tf.distribute.Strategy` can be used with TensorFlow's high level APIs, [tf.keras](https://www.tensorflow.org/guide/keras) and [tf.estimator](https://www.tensorflow.org/guide/estimators), with just a couple of lines of code change. It also provides an API that can be used to distribute custom training loops (and in general any computation using TensorFlow).In TensorFlow 2.0, users can execute their programs eagerly, or in a graph using [`tf.function`](../tutorials/eager/tf_function.ipynb). `tf.distribute.Strategy` intends to support both these modes of execution. Note that we may talk about training most of the time in this guide, but this API can also be used for distributing evaluation and prediction on different platforms.As you will see in a bit, very few changes are needed to use `tf.distribute.Strategy` with your code. This is because we have changed the underlying components of TensorFlow to become strategy-aware. This includes variables, layers, models, optimizers, metrics, summaries, and checkpoints.In this guide, we will talk about various types of strategies and how one can use them in a different situations.
###Code
# Import TensorFlow
from __future__ import absolute_import, division, print_function, unicode_literals
!pip install tensorflow-gpu==2.0.0-beta1
import tensorflow as tf
###Output
_____no_output_____
###Markdown
Types of strategies`tf.distribute.Strategy` intends to cover a number of use cases along different axes. Some of these combinations are currently supported and others will be added in the future. Some of these axes are:* Synchronous vs asynchronous training: These are two common ways of distributing training with data parallelism. In sync training, all workers train over different slices of input data in sync, and aggregating gradients at each step. In async training, all workers are independently training over the input data and updating variables asynchronously. Typically sync training is supported via all-reduce and async through parameter server architecture.* Hardware platform: Users may want to scale their training onto multiple GPUs on one machine, or multiple machines in a network (with 0 or more GPUs each), or on Cloud TPUs.In order to support these use cases, we have 5 strategies available. In the next section we will talk about which of these are supported in which scenarios in TF 2.0-beta at this time. Here is a quick overview:| Training API | MirroredStrategy | TPUStrategy | MultiWorkerMirroredStrategy | CentralStorageStrategy | ParameterServerStrategy ||:----------------------- |:------------------- |:--------------------- |:--------------------------------- |:--------------------------------- |:-------------------------- || **Keras API** | Supported | Support planned in 2.0 RC | Experimental support | Experimental support | Supported planned in post 2.0 || **Custom training loop** | Experimental support | Experimental support | Support planned in 2.0 RC | Support planned in 2.0 RC | No support yet || **Estimator API** | Supported | Supported | Supported | Supported | Supported | MirroredStrategy`tf.distribute.MirroredStrategy` supports synchronous distributed training on multiple GPUs on one machine. It creates one replica per GPU device. Each variable in the model is mirrored across all the replicas. Together, these variables form a single conceptual variable called `MirroredVariable`. These variables are kept in sync with each other by applying identical updates.Efficient all-reduce algorithms are used to communicate the variable updates across the devices.All-reduce aggregates tensors across all the devices by adding them up, and makes them available on each device.It’s a fused algorithm that is very efficient and can reduce the overhead of synchronization significantly. There are many all-reduce algorithms and implementations available, depending on the type of communication available between devices. By default, it uses NVIDIA NCCL as the all-reduce implementation. The user can also choose between a few other options we provide, or write their own.Here is the simplest way of creating `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
###Output
_____no_output_____
###Markdown
This will create a `MirroredStrategy` instance which will use all the GPUs that are visible to TensorFlow, and use NCCL as the cross device communication.If you wish to use only some of the GPUs on your machine, you can do so like this:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(devices=["/gpu:0", "/gpu:1"])
###Output
_____no_output_____
###Markdown
If you wish to override the cross device communication, you can do so using the `cross_device_ops` argument by supplying an instance of `tf.distribute.CrossDeviceOps`. Currently we provide `tf.distribute.HierarchicalCopyAllReduce` and `tf.distribute.ReductionToOneDevice` as 2 other options other than `tf.distribute.NcclAllReduce` which is the default.
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(
cross_device_ops=tf.distribute.HierarchicalCopyAllReduce())
###Output
_____no_output_____
###Markdown
CentralStorageStrategy`tf.distribute.experimental.CentralStorageStrategy` does synchronous training as well. Variables are not mirrored, instead they are placed on the CPU and operations are replicated across all local GPUs. If there is only one GPU, all variables and operations will be placed on that GPU.Create an instance of `CentralStorageStrategy` by:
###Code
central_storage_strategy = tf.distribute.experimental.CentralStorageStrategy()
###Output
_____no_output_____
###Markdown
This will create a `CentralStorageStrategy` instance which will use all visible GPUs and CPU. Update to variables on replicas will be aggregated before being applied to variables. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. MultiWorkerMirroredStrategy`tf.distribute.experimental.MultiWorkerMirroredStrategy` is very similar to `MirroredStrategy`. It implements synchronous distributed training across multiple workers, each with potentially multiple GPUs. Similar to `MirroredStrategy`, it creates copies of all variables in the model on each device across all workers.It uses [CollectiveOps](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/collective_ops.py) as the multi-worker all-reduce communication method used to keep variables in sync. A collective op is a single op in the TensorFlow graph which can automatically choose an all-reduce algorithm in the TensorFlow runtime according to hardware, network topology and tensor sizes.It also implements additional performance optimizations. For example, it includes a static optimization that converts multiple all-reductions on small tensors into fewer all-reductions on larger tensors. In addition, we are designing it to have a plugin architecture - so that in the future, users will be able to plugin algorithms that are better tuned for their hardware. Note that collective ops also implement other collective operations such as broadcast and all-gather.Here is the simplest way of creating `MultiWorkerMirroredStrategy`:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()
###Output
_____no_output_____
###Markdown
`MultiWorkerMirroredStrategy` currently allows you to choose between two different implementations of collective ops. `CollectiveCommunication.RING` implements ring-based collectives using gRPC as the communication layer. `CollectiveCommunication.NCCL` uses [Nvidia's NCCL](https://developer.nvidia.com/nccl) to implement collectives. `CollectiveCommunication.AUTO` defers the choice to the runtime. The best choice of collective implementation depends upon the number and kind of GPUs, and the network interconnect in the cluster. You can specify them in the following way:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy(
tf.distribute.experimental.CollectiveCommunication.NCCL)
###Output
_____no_output_____
###Markdown
One of the key differences to get multi worker training going, as compared to multi-GPU training, is the multi-worker setup. "TF_CONFIG" environment variable is the standard way in TensorFlow to specify the cluster configuration to each worker that is part of the cluster. See section on ["TF_CONFIG" below](TF_CONFIG) for more details on how this can be done. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. TPUStrategy`tf.distribute.experimental.TPUStrategy` lets users run their TensorFlow training on Tensor Processing Units (TPUs). TPUs are Google's specialized ASICs designed to dramatically accelerate machine learning workloads. They are available on Google Colab, the [TensorFlow Research Cloud](https://www.tensorflow.org/tfrc) and [Google Compute Engine](https://cloud.google.com/tpu).In terms of distributed training architecture, TPUStrategy is the same `MirroredStrategy` - it implements synchronous distributed training. TPUs provide their own implementation of efficient all-reduce and other collective operations across multiple TPU cores, which are used in `TPUStrategy`.Here is how you would instantiate `TPUStrategy`.Note: To run this code in Colab, you should select TPU as the Colab runtime. We will have a tutorial soon that will demonstrate how you can use TPUStrategy.```cluster_resolver = tf.distribute.cluster_resolver.TPUClusterResolver( tpu=tpu_address)tf.config.experimental_connect_to_host(cluster_resolver.master())tf.tpu.experimental.initialize_tpu_system(cluster_resolver)tpu_strategy = tf.distribute.experimental.TPUStrategy(cluster_resolver)``` `TPUClusterResolver` instance helps locate the TPUs. In Colab, you don't need to specify any arguments to it. If you want to use this for Cloud TPUs, you will need to specify the name of your TPU resource in `tpu` argument. We also need to initialize the tpu system explicitly at the start of the program. This is required before TPUs can be used for computation and should ideally be done at the beginning because it also wipes out the TPU memory so all state will be lost. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. ParameterServerStrategy`tf.distribute.experimental.ParameterServerStrategy` supports parameter servers training on multiple machines. In this setup, some machines are designated as workers and some as parameter servers. Each variable of the model is placed on one parameter server. Computation is replicated across all GPUs of the all the workers.In terms of code, it looks similar to other strategies:```ps_strategy = tf.distribute.experimental.ParameterServerStrategy()``` For multi worker training, "TF_CONFIG" needs to specify the configuration of parameter servers and workers in your cluster, which you can read more about in ["TF_CONFIG" below](TF_CONFIG) below. So far we've talked about what are the different stategies available and how you can instantiate them. In the next few sections, we will talk about the different ways in which you can use them to distribute your training. We will show short code snippets in this guide and link off to full tutorials which you can run end to end. Using `tf.distribute.Strategy` with KerasWe've integrated `tf.distribute.Strategy` into `tf.keras` which is TensorFlow's implementation of the[Keras API specification](https://keras.io). `tf.keras` is a high-level API to build and train models. By integrating into `tf.keras` backend, we've made it seamless for Keras users to distribute their training written in the Keras training framework. The only things that need to change in a user's program are: (1) Create an instance of the appropriate `tf.distribute.Strategy` and (2) Move the creation and compiling of Keras model inside `strategy.scope`. We support all types of Keras models - sequential, functional and subclassed.Here is a snippet of code to do this for a very simple Keras model with one dense layer:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
model.compile(loss='mse', optimizer='sgd')
###Output
_____no_output_____
###Markdown
In this example we used `MirroredStrategy` so we can run this on a machine with multiple GPUs. `strategy.scope()` indicated which parts of the code to run distributed. Creating a model inside this scope allows us to create mirrored variables instead of regular variables. Compiling under the scope allows us to know that the user intends to train this model using this strategy. Once this is setup, you can fit your model like you would normally. `MirroredStrategy` takes care of replicating the model's training on the available GPUs, aggregating gradients etc.
###Code
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100).batch(10)
model.fit(dataset, epochs=2)
model.evaluate(dataset)
###Output
_____no_output_____
###Markdown
Here we used a `tf.data.Dataset` to provide the training and eval input. You can also use numpy arrays:
###Code
import numpy as np
inputs, targets = np.ones((100, 1)), np.ones((100, 1))
model.fit(inputs, targets, epochs=2, batch_size=10)
###Output
_____no_output_____
###Markdown
In both cases (dataset or numpy), each batch of the given input is divided equally among the multiple replicas. For instance, if using `MirroredStrategy` with 2 GPUs, each batch of size 10 will get divided among the 2 GPUs, with each receiving 5 input examples in each step. Each epoch will then train faster as you add more GPUs. Typically, you would want to increase your batch size as you add more accelerators so as to make effective use of the extra computing power. You will also need to re-tune your learning rate, depending on the model. You can use `strategy.num_replicas_in_sync` to get the number of replicas.
###Code
# Compute global batch size using number of replicas.
BATCH_SIZE_PER_REPLICA = 5
global_batch_size = (BATCH_SIZE_PER_REPLICA *
mirrored_strategy.num_replicas_in_sync)
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100)
dataset = dataset.batch(global_batch_size)
LEARNING_RATES_BY_BATCH_SIZE = {5: 0.1, 10: 0.15}
learning_rate = LEARNING_RATES_BY_BATCH_SIZE[global_batch_size]
###Output
_____no_output_____
###Markdown
What's supported now?In TF 2.0 beta release, we support training with Keras using `MirroredStrategy`, `CentralStorageStrategy` and `MultiWorkerMirroredStrategy`. Both `CentralStorageStrategy` and `MultiWorkerMirroredStrategy` are currently experimental APIs and are subject to change.Support for other strategies will be coming soon. The API and how to use will be exactly the same as above.| Training API | MirroredStrategy | TPUStrategy | MultiWorkerMirroredStrategy | CentralStorageStrategy | ParameterServerStrategy ||---------------- |--------------------- |----------------------- |----------------------------------- |----------------------------------- |--------------------------- || Keras APIs | Supported | Support planned in 2.0 RC | Experimental support | Experimental support | Support planned in post 2.0 | Examples and TutorialsHere is a list of tutorials and examples that illustrate the above integration end to end with Keras:1. Tutorial to train [MNIST](../tutorials/distribute/keras.ipynb) with `MirroredStrategy`.2. Official [ResNet50](https://github.com/tensorflow/models/blob/master/official/resnet/keras/keras_imagenet_main.py) training with ImageNet data using `MirroredStrategy`.3. [ResNet50](https://github.com/tensorflow/tpu/blob/master/models/experimental/resnet50_keras/resnet50.py) trained with Imagenet data on Cloud TPus with `TPUStrategy`. Note that this example only works with TensorFlow 1.x currently.4. [Tutorial](../tutorials/distribute/multi_worker_with_keras.ipynb) to train MNIST using `MultiWorkerMirroredStrategy`.5. [NCF](https://github.com/tensorflow/models/blob/master/official/recommendation/ncf_keras_main.py) trained using `MirroredStrategy`.2. [Transformer]( https://github.com/tensorflow/models/blob/master/official/transformer/v2/transformer_main.py) trained using `MirroredStrategy`. Using `tf.distribute.Strategy` with Estimator`tf.estimator` is a distributed training TensorFlow API that originally supported the async parameter server approach. Like with Keras, we've integrated `tf.distribute.Strategy` into `tf.Estimator` so that a user who is using Estimator for their training can easily change their training is distributed with very few changes to your their code. With this, estimator users can now do synchronous distributed training on multiple GPUs and multiple workers, as well as use TPUs.The usage of `tf.distribute.Strategy` with Estimator is slightly different than the Keras case. Instead of using `strategy.scope`, now we pass the strategy object into the [`RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig) for the Estimator.Here is a snippet of code that shows this with a premade estimator `LinearRegressor` and `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
config = tf.estimator.RunConfig(
train_distribute=mirrored_strategy, eval_distribute=mirrored_strategy)
regressor = tf.estimator.LinearRegressor(
feature_columns=[tf.feature_column.numeric_column('feats')],
optimizer='SGD',
config=config)
###Output
_____no_output_____
###Markdown
We use a premade Estimator here, but the same code works with a custom Estimator as well. `train_distribute` determines how training will be distributed, and `eval_distribute` determines how evaluation will be distributed. This is another difference from Keras where we use the same strategy for both training and eval.Now we can train and evaluate this Estimator with an input function:
###Code
def input_fn():
dataset = tf.data.Dataset.from_tensors(({"feats":[1.]}, [1.]))
return dataset.repeat(1000).batch(10)
regressor.train(input_fn=input_fn, steps=10)
regressor.evaluate(input_fn=input_fn, steps=10)
###Output
_____no_output_____
###Markdown
Another difference to highlight here between Estimator and Keras is the input handling. In Keras, we mentioned that each batch of the dataset is split across the multiple replicas. In Estimator, however, the user provides an `input_fn` and have full control over how they want their data to be distributed across workers and devices. We do not do automatic splitting of batch, nor automatically shard the data across different workers. The provided `input_fn` is called once per worker, thus giving one dataset per worker. Then one batch from that dataset is fed to one replica on that worker, thereby consuming N batches for N replicas on 1 worker. In other words, the dataset returned by the `input_fn` should provide batches of size `PER_REPLICA_BATCH_SIZE`. And the global batch size for a step can be obtained as `PER_REPLICA_BATCH_SIZE * strategy.num_replicas_in_sync`. When doing multi worker training, users will also want to either split their data across the workers, or shuffle with a random seed on each. You can see an example of how to do this in the [Multi-worker Training with Estimator](../tutorials/distribute/multi_worker_with_estimator.ipynb). We showed an example of using `MirroredStrategy` with Estimator. You can also use `TPUStrategy` with Estimator as well, in the exact same way:```config = tf.estimator.RunConfig( train_distribute=tpu_strategy, eval_distribute=tpu_strategy)``` And similarly, you can use multi worker and parameter server strategies as well. The code remains the same, but you need to use `tf.estimator.train_and_evaluate`, and set "TF_CONFIG" environment variables for each binary running in your cluster. What's supported now?In TF 2.0 beta release, we support training with Estimator using all strategies.| Training API | MirroredStrategy | TPUStrategy | MultiWorkerMirroredStrategy | CentralStorageStrategy | ParameterServerStrategy ||:--------------- |:------------------ |:------------- |:----------------------------- |:------------------------ |:------------------------- || Estimator API | Supported | Supported | Supported | Supported | Supported | Examples and TutorialsHere are some examples that show end to end usage of various strategies with Estimator:1. [Multi-worker Training with Estimator](../tutorials/distribute/multi_worker_with_estimator.ipynb) to train MNIST with multiple workers using `MultiWorkerMirroredStrategy`.2. [End to end example](https://github.com/tensorflow/ecosystem/tree/master/distribution_strategy) for multi worker training in tensorflow/ecosystem using Kuberentes templates. This example starts with a Keras model and converts it to an Estimator using the `tf.keras.estimator.model_to_estimator` API.3. Official [ResNet50](https://github.com/tensorflow/models/blob/master/official/resnet/imagenet_main.py) model, which can be trained using either `MirroredStrategy` or `MultiWorkerMirroredStrategy`.4. [ResNet50](https://github.com/tensorflow/tpu/blob/master/models/experimental/distribution_strategy/resnet_estimator.py) example with TPUStrategy. Using `tf.distribute.Strategy` with custom training loopsAs you've seen, using `tf.distribute.Strategy` with high level APIs is only a couple lines of code change. With a little more effort, `tf.distribute.Strategy` can also be used by other users who are not using these frameworks.TensorFlow is used for a wide variety of use cases and some users (such as researchers) require more flexibility and control over their training loops. This makes it hard for them to use the high level frameworks such as Estimator or Keras. For instance, someone using a GAN may want to take a different number of generator or discriminator steps each round. Similarly, the high level frameworks are not very suitable for Reinforcement Learning training. So these users will usually write their own training loops.For these users, we provide a core set of methods through the `tf.distribute.Strategy` classes. Using these may require minor restructuring of the code initially, but once that is done, the user should be able to switch between GPUs / TPUs / multiple machines by just changing the strategy instance.Here we will show a brief snippet illustrating this use case for a simple training example using the same Keras model as before. First, we create the model and optimizer inside the strategy's scope. This ensures that any variables created with the model and optimizer are mirrored variables.
###Code
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
optimizer = tf.keras.optimizers.SGD()
###Output
_____no_output_____
###Markdown
Next, we create the input dataset and call `tf.distribute.Strategy.experimental_distribute_dataset` to distribute the dataset based on the strategy.
###Code
with mirrored_strategy.scope():
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(1000).batch(
global_batch_size)
dist_dataset = mirrored_strategy.experimental_distribute_dataset(dataset)
###Output
_____no_output_____
###Markdown
Then, we define one step of the training. We will use `tf.GradientTape` to compute gradients and optimizer to apply those gradients to update our model's variables. To distribute this training step, we put in in a function `step_fn` and pass it to `tf.distrbute.Strategy.experimental_run_v2` along with the dataset inputs that we get from `dist_dataset` created before:
###Code
@tf.function
def train_step(dist_inputs):
def step_fn(inputs):
features, labels = inputs
with tf.GradientTape() as tape:
logits = model(features)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(
logits=logits, labels=labels)
loss = tf.reduce_sum(cross_entropy) * (1.0 / global_batch_size)
grads = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(list(zip(grads, model.trainable_variables)))
return cross_entropy
per_example_losses = mirrored_strategy.experimental_run_v2(
step_fn, args=(dist_inputs,))
mean_loss = mirrored_strategy.reduce(
tf.distribute.ReduceOp.MEAN, per_example_losses, axis=0)
return mean_loss
###Output
_____no_output_____
###Markdown
A few other things to note in the code above:1. We used `tf.nn.softmax_cross_entropy_with_logits` to compute the loss. And then we scaled the total loss by the global batch size. This is important because all the replicas are training in sync and number of examples in each step of training is the global batch. So the loss needs to be divided by the global batch size and not by the replica (local) batch size.2. We used the `tf.distribute.Strategy.reduce` API to aggregate the results returned by `tf.distribute.Strategy.experimental_run_v2`. `tf.distribute.Strategy.experimental_run_v2` returns results from each local replica in the strategy, and there are multiple ways to consume this result. You can `reduce` them to get an aggregated value. You can also do `tf.distribute.Strategy.experimental_local_results` to get the list of values contained in the result, one per local replica.3. When `apply_gradients` is called within a distribution strategy scope, its behavior is modified. Specifically, before applying gradients on each parallel instance during synchronous training, it performs a sum-over-all-replicas of the gradients. Finally, once we have defined the training step, we can iterate over `dist_dataset` and run the training in a loop:
###Code
with mirrored_strategy.scope():
for inputs in dist_dataset:
print(train_step(inputs))
###Output
_____no_output_____
###Markdown
In the example above, we iterated over the `dist_dataset` to provide input to your training. We also provide the `tf.distribute.Strategy.make_experimental_numpy_dataset` to support numpy inputs. You can use this API to create a dataset before calling `tf.distribute.Strategy.experimental_distribute_dataset`.Another way of iterating over your data is to explicitly use iterators. You may want to do this when you want to run for a given number of steps as opposed to iterating over the entire dataset.The above iteration would now be modified to first create an iterator and then explicity call `next` on it to get the input data.
###Code
with mirrored_strategy.scope():
iterator = iter(dist_dataset)
for _ in range(10):
print(train_step(next(iterator)))
###Output
_____no_output_____
###Markdown
Copyright 2018 The TensorFlow Authors.
###Code
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###Output
_____no_output_____
###Markdown
Distributed Training in TensorFlow View on TensorFlow.org Run in Google Colab View source on GitHub OverviewThe `tf.distribute.Strategy` API is an easy way to distribute your trainingacross multiple devices/machines. Our goal is to allow users to use existingmodels and training code with minimal changes to enable distributed training.Currently, in core TensorFlow, we support `tf.distribute.MirroredStrategy`. Thisdoes in-graph replication with synchronous training on many GPUs on one machine.Essentially, we create copies of all variables in the model's layers on eachdevice. We then use all-reduce to combine gradients across the devices beforeapplying them to the variables to keep them in sync.Many other strategies will soon beavailable in core TensorFlow. You can find more information about them in the[README](https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/distribute).You can also read the[public design review](https://github.com/tensorflow/community/blob/master/rfcs/20181016-replicator.md)for updating the `tf.distribute.Strategy` API as part of the move toto core TF. Example with Keras APILet's see how to scale to multiple GPUs on one machine using `MirroredStrategy`with [tf.keras](https://www.tensorflow.org/guide/keras).We will take a very simple model consisting of a single layer. First, we will import Tensorflow.
###Code
from __future__ import absolute_import, division, print_function
!pip install tf-nightly-2.0-preview
import tensorflow as tf
###Output
_____no_output_____
###Markdown
To distribute a Keras model on multiple GPUs using `MirroredStrategy`, we first instantiate a `MirroredStrategy` object.
###Code
strategy = tf.distribute.MirroredStrategy()
###Output
_____no_output_____
###Markdown
We then create and compile the Keras model in `strategy.scope`.
###Code
with strategy.scope():
inputs = tf.keras.layers.Input(shape=(1,))
predictions = tf.keras.layers.Dense(1)(inputs)
model = tf.keras.models.Model(inputs=inputs, outputs=predictions)
model.compile(loss='mse',
optimizer=tf.keras.optimizers.SGD(learning_rate=0.2))
###Output
_____no_output_____
###Markdown
Let's also define a simple input dataset for training this model.
###Code
train_dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(10000).batch(10)
###Output
_____no_output_____
###Markdown
To train the model we call Keras `fit` API using the input dataset that wecreated earlier, same as how we would in a non-distributed case.
###Code
model.fit(train_dataset, epochs=5, steps_per_epoch=10)
###Output
_____no_output_____
###Markdown
Similarly, we can also call `evaluate` and `predict` as before using appropriatedatasets.
###Code
eval_dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100).batch(10)
model.evaluate(eval_dataset, steps=10)
predict_dataset = tf.data.Dataset.from_tensors(([1.])).repeat(10).batch(2)
model.predict(predict_dataset, steps=5)
###Output
_____no_output_____
###Markdown
That's all you need to train your model with Keras on multiple GPUs with`MirroredStrategy`. It will take care of splitting upthe input dataset, replicating layers and variables on each device, andcombining and applying gradients.The model and input code does not have to change because we have changed theunderlying components of TensorFlow (such as optimizer, batch norm andsummaries) to become strategy-aware. That means those components know how tocombine their state across devices. Further, saving and checkpointing worksseamlessly, so you can save with one or no distribute strategy and resume withanother. Example with Estimator APIYou can also use `tf.distribute.Strategy` API with[`Estimator`](https://www.tensorflow.org/api_docs/python/tf/estimator/Estimator).Let's see a simple example of its usage with `MirroredStrategy`.We will use the `LinearRegressor` premade estimator as an example. To use `MirroredStrategy` with Estimator, all we need to do is:* Create an instance of the `MirroredStrategy` class.* Pass it to the[`RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig)parameter of the custom or premade `Estimator`.
###Code
strategy = tf.distribute.MirroredStrategy()
config = tf.estimator.RunConfig(
train_distribute=strategy, eval_distribute=strategy)
regressor = tf.estimator.LinearRegressor(
feature_columns=[tf.feature_column.numeric_column('feats')],
optimizer='SGD',
config=config)
###Output
_____no_output_____
###Markdown
We will define a simple input function to feed data for training this model.
###Code
def input_fn():
return tf.data.Dataset.from_tensors(({"feats":[1.]}, [1.])).repeat(10000).batch(10)
###Output
_____no_output_____
###Markdown
Then we can call `train` on the regressor instance to train the model.
###Code
regressor.train(input_fn=input_fn, steps=10)
###Output
_____no_output_____
###Markdown
And we can `evaluate` to evaluate the trained model.
###Code
regressor.evaluate(input_fn=input_fn, steps=10)
###Output
_____no_output_____
###Markdown
Copyright 2018 The TensorFlow Authors.
###Code
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###Output
_____no_output_____
###Markdown
Distributed training in TensorFlow View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook Overview`tf.distribute.Strategy` is a TensorFlow API to distribute training across multiple GPUs, multiple machines or TPUs. Using this API, users can distribute their existing models and training code with minimal code changes.`tf.distribute.Strategy` has been designed with these key goals in mind:* Easy to use and support multiple user segments, including researchers, ML engineers, etc.* Provide good performance out of the box.* Easy switching between strategies.Use `tf.distribute.Strategy` with a high-level API like [Keras](https://www.tensorflow.org/guide/keras), and can also be used to distribute custom training loops (and, in general, any computation using TensorFlow).In TensorFlow 2.0, users can execute their programs eagerly, or in a graph using [`tf.function`](../tutorials/eager/tf_function.ipynb). `tf.distribute.Strategy` intends to support both these modes of execution. Note that we may talk about training most of the time in this guide, but this API can also be used for distributing evaluation and prediction on different platforms.As you will see in a bit, very few changes are needed to use `tf.distribute.Strategy` with your code. This is because we have changed the underlying components of TensorFlow to become strategy-aware. This includes variables, layers, models, optimizers, metrics, summaries, and checkpoints.In this guide, we will talk about various types of strategies and how one can use them in a different situations.Note: For a deeper understanding of the concepts, please watch [this deep-dive presentation](https://youtu.be/jKV53r9-H14). This is especially recommended if you plan to write your own training loop.
###Code
# Import TensorFlow
from __future__ import absolute_import, division, print_function, unicode_literals
try:
# %tensorflow_version only exists in Colab.
%tensorflow_version 2.x
except Exception:
pass
import tensorflow as tf
###Output
_____no_output_____
###Markdown
Types of strategies`tf.distribute.Strategy` intends to cover a number of use cases along different axes. Some of these combinations are currently supported and others will be added in the future. Some of these axes are:* Synchronous vs asynchronous training: These are two common ways of distributing training with data parallelism. In sync training, all workers train over different slices of input data in sync, and aggregating gradients at each step. In async training, all workers are independently training over the input data and updating variables asynchronously. Typically sync training is supported via all-reduce and async through parameter server architecture.* Hardware platform: Users may want to scale their training onto multiple GPUs on one machine, or multiple machines in a network (with 0 or more GPUs each), or on Cloud TPUs.In order to support these use cases, there are five strategies available. In the next section we will talk about which of these are supported in which scenarios in TF 2.0 at this time. Here is a quick overview:| Training API | MirroredStrategy | TPUStrategy | MultiWorkerMirroredStrategy | CentralStorageStrategy | ParameterServerStrategy ||:----------------------- |:------------------- |:--------------------- |:--------------------------------- |:--------------------------------- |:-------------------------- || **Keras API** | Supported | Experimental support | Experimental support | Experimental support | Supported planned post 2.0 || **Custom training loop** | Experimental support | Experimental support | Support planned post 2.0 | Support planned post 2.0 | No support yet || **Estimator API** | Limited Support | Not supported | Limited Support | Limited Support | Limited Support |Note: Estimator support is limited. Basic training and evaluation are experimental, and advanced features—such as scaffold—are not implemented. We recommend using Keras or custom training loops if a use case is not covered. MirroredStrategy`tf.distribute.MirroredStrategy` supports synchronous distributed training on multiple GPUs on one machine. It creates one replica per GPU device. Each variable in the model is mirrored across all the replicas. Together, these variables form a single conceptual variable called `MirroredVariable`. These variables are kept in sync with each other by applying identical updates.Efficient all-reduce algorithms are used to communicate the variable updates across the devices.All-reduce aggregates tensors across all the devices by adding them up, and makes them available on each device.It’s a fused algorithm that is very efficient and can reduce the overhead of synchronization significantly. There are many all-reduce algorithms and implementations available, depending on the type of communication available between devices. By default, it uses NVIDIA NCCL as the all-reduce implementation. The user can also choose between a few other options we provide, or write their own.Here is the simplest way of creating `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
###Output
_____no_output_____
###Markdown
This will create a `MirroredStrategy` instance which will use all the GPUs that are visible to TensorFlow, and use NCCL as the cross device communication.If you wish to use only some of the GPUs on your machine, you can do so like this:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(devices=["/gpu:0", "/gpu:1"])
###Output
_____no_output_____
###Markdown
If you wish to override the cross device communication, you can do so using the `cross_device_ops` argument by supplying an instance of `tf.distribute.CrossDeviceOps`. Currently, `tf.distribute.HierarchicalCopyAllReduce` and `tf.distribute.ReductionToOneDevice` are two options other than `tf.distribute.NcclAllReduce` which is the default.
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(
cross_device_ops=tf.distribute.HierarchicalCopyAllReduce())
###Output
_____no_output_____
###Markdown
CentralStorageStrategy`tf.distribute.experimental.CentralStorageStrategy` does synchronous training as well. Variables are not mirrored, instead they are placed on the CPU and operations are replicated across all local GPUs. If there is only one GPU, all variables and operations will be placed on that GPU.Create an instance of `CentralStorageStrategy` by:
###Code
central_storage_strategy = tf.distribute.experimental.CentralStorageStrategy()
###Output
_____no_output_____
###Markdown
This will create a `CentralStorageStrategy` instance which will use all visible GPUs and CPU. Update to variables on replicas will be aggregated before being applied to variables. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. MultiWorkerMirroredStrategy`tf.distribute.experimental.MultiWorkerMirroredStrategy` is very similar to `MirroredStrategy`. It implements synchronous distributed training across multiple workers, each with potentially multiple GPUs. Similar to `MirroredStrategy`, it creates copies of all variables in the model on each device across all workers.It uses [CollectiveOps](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/collective_ops.py) as the multi-worker all-reduce communication method used to keep variables in sync. A collective op is a single op in the TensorFlow graph which can automatically choose an all-reduce algorithm in the TensorFlow runtime according to hardware, network topology and tensor sizes.It also implements additional performance optimizations. For example, it includes a static optimization that converts multiple all-reductions on small tensors into fewer all-reductions on larger tensors. In addition, we are designing it to have a plugin architecture - so that in the future, users will be able to plugin algorithms that are better tuned for their hardware. Note that collective ops also implement other collective operations such as broadcast and all-gather.Here is the simplest way of creating `MultiWorkerMirroredStrategy`:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()
###Output
_____no_output_____
###Markdown
`MultiWorkerMirroredStrategy` currently allows you to choose between two different implementations of collective ops. `CollectiveCommunication.RING` implements ring-based collectives using gRPC as the communication layer. `CollectiveCommunication.NCCL` uses [Nvidia's NCCL](https://developer.nvidia.com/nccl) to implement collectives. `CollectiveCommunication.AUTO` defers the choice to the runtime. The best choice of collective implementation depends upon the number and kind of GPUs, and the network interconnect in the cluster. You can specify them in the following way:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy(
tf.distribute.experimental.CollectiveCommunication.NCCL)
###Output
_____no_output_____
###Markdown
One of the key differences to get multi worker training going, as compared to multi-GPU training, is the multi-worker setup. "TF_CONFIG" environment variable is the standard way in TensorFlow to specify the cluster configuration to each worker that is part of the cluster. See section on ["TF_CONFIG" below](TF_CONFIG) for more details on how this can be done. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. TPUStrategy`tf.distribute.experimental.TPUStrategy` lets users run their TensorFlow training on Tensor Processing Units (TPUs). TPUs are Google's specialized ASICs designed to dramatically accelerate machine learning workloads. They are available on Google Colab, the [TensorFlow Research Cloud](https://www.tensorflow.org/tfrc) and [Google Compute Engine](https://cloud.google.com/tpu).In terms of distributed training architecture, TPUStrategy is the same `MirroredStrategy` - it implements synchronous distributed training. TPUs provide their own implementation of efficient all-reduce and other collective operations across multiple TPU cores, which are used in `TPUStrategy`.Here is how you would instantiate `TPUStrategy`.Note: To run this code in Colab, you should select TPU as the Colab runtime. We will have a tutorial soon that will demonstrate how you can use TPUStrategy.```cluster_resolver = tf.distribute.cluster_resolver.TPUClusterResolver( tpu=tpu_address)tf.config.experimental_connect_to_cluster(cluster_resolver)tf.tpu.experimental.initialize_tpu_system(cluster_resolver)tpu_strategy = tf.distribute.experimental.TPUStrategy(cluster_resolver)``` `TPUClusterResolver` instance helps locate the TPUs. In Colab, you don't need to specify any arguments to it. If you want to use this for Cloud TPUs, you will need to specify the name of your TPU resource in `tpu` argument. We also need to initialize the tpu system explicitly at the start of the program. This is required before TPUs can be used for computation and should ideally be done at the beginning because it also wipes out the TPU memory so all state will be lost. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. ParameterServerStrategy`tf.distribute.experimental.ParameterServerStrategy` supports parameter servers training on multiple machines. In this setup, some machines are designated as workers and some as parameter servers. Each variable of the model is placed on one parameter server. Computation is replicated across all GPUs of all the workers.In terms of code, it looks similar to other strategies:```ps_strategy = tf.distribute.experimental.ParameterServerStrategy()``` For multi worker training, "TF_CONFIG" needs to specify the configuration of parameter servers and workers in your cluster, which you can read more about in ["TF_CONFIG" below](TF_CONFIG) below. So far we've talked about what are the different stategies available and how you can instantiate them. In the next few sections, we will talk about the different ways in which you can use them to distribute your training. We will show short code snippets in this guide and link off to full tutorials which you can run end to end. Using `tf.distribute.Strategy` with KerasWe've integrated `tf.distribute.Strategy` into `tf.keras` which is TensorFlow's implementation of the[Keras API specification](https://keras.io). `tf.keras` is a high-level API to build and train models. By integrating into `tf.keras` backend, we've made it seamless for Keras users to distribute their training written in the Keras training framework. The only things that need to change in a user's program are: (1) Create an instance of the appropriate `tf.distribute.Strategy` and (2) Move the creation and compiling of Keras model inside `strategy.scope`. We support all types of Keras models - sequential, functional and subclassed.Here is a snippet of code to do this for a very simple Keras model with one dense layer:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
model.compile(loss='mse', optimizer='sgd')
###Output
_____no_output_____
###Markdown
In this example we used `MirroredStrategy` so we can run this on a machine with multiple GPUs. `strategy.scope()` indicated which parts of the code to run distributed. Creating a model inside this scope allows us to create mirrored variables instead of regular variables. Compiling under the scope allows us to know that the user intends to train this model using this strategy. Once this is setup, you can fit your model like you would normally. `MirroredStrategy` takes care of replicating the model's training on the available GPUs, aggregating gradients etc.
###Code
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100).batch(10)
model.fit(dataset, epochs=2)
model.evaluate(dataset)
###Output
_____no_output_____
###Markdown
Here we used a `tf.data.Dataset` to provide the training and eval input. You can also use numpy arrays:
###Code
import numpy as np
inputs, targets = np.ones((100, 1)), np.ones((100, 1))
model.fit(inputs, targets, epochs=2, batch_size=10)
###Output
_____no_output_____
###Markdown
In both cases (dataset or numpy), each batch of the given input is divided equally among the multiple replicas. For instance, if using `MirroredStrategy` with 2 GPUs, each batch of size 10 will get divided among the 2 GPUs, with each receiving 5 input examples in each step. Each epoch will then train faster as you add more GPUs. Typically, you would want to increase your batch size as you add more accelerators so as to make effective use of the extra computing power. You will also need to re-tune your learning rate, depending on the model. You can use `strategy.num_replicas_in_sync` to get the number of replicas.
###Code
# Compute global batch size using number of replicas.
BATCH_SIZE_PER_REPLICA = 5
global_batch_size = (BATCH_SIZE_PER_REPLICA *
mirrored_strategy.num_replicas_in_sync)
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100)
dataset = dataset.batch(global_batch_size)
LEARNING_RATES_BY_BATCH_SIZE = {5: 0.1, 10: 0.15}
learning_rate = LEARNING_RATES_BY_BATCH_SIZE[global_batch_size]
###Output
_____no_output_____
###Markdown
What's supported now?In TF 2.0 release, `MirroredStrategy`, `TPUStrategy`, `CentralStorageStrategy` and `MultiWorkerMirroredStrategy` are supported in Keras. Except `MirroredStrategy`, others are currently experimental and are subject to change.Support for other strategies will be coming soon. The API and how to use will be exactly the same as above.| Training API | MirroredStrategy | TPUStrategy | MultiWorkerMirroredStrategy | CentralStorageStrategy | ParameterServerStrategy ||---------------- |--------------------- |----------------------- |----------------------------------- |----------------------------------- |--------------------------- || Keras APIs | Supported | Experimental support | Experimental support | Experimental support | Support planned post 2.0 | Examples and TutorialsHere is a list of tutorials and examples that illustrate the above integration end to end with Keras:1. Tutorial to train [MNIST](../tutorials/distribute/keras.ipynb) with `MirroredStrategy`.2. Official [ResNet50](https://github.com/tensorflow/models/blob/master/official/vision/image_classification/resnet_imagenet_main.py) training with ImageNet data using `MirroredStrategy`.3. [ResNet50](https://github.com/tensorflow/tpu/blob/master/models/experimental/resnet50_keras/resnet50_tf2.py) trained with Imagenet data on Cloud TPUs with `TPUStrategy`.4. [Tutorial](../tutorials/distribute/multi_worker_with_keras.ipynb) to train MNIST using `MultiWorkerMirroredStrategy`.5. [NCF](https://github.com/tensorflow/models/blob/master/official/recommendation/ncf_keras_main.py) trained using `MirroredStrategy`.2. [Transformer]( https://github.com/tensorflow/models/blob/master/official/transformer/v2/transformer_main.py) trained using `MirroredStrategy`. Using `tf.distribute.Strategy` with custom training loopsAs you've seen, using `tf.distribute.Strategy` with high level APIs is only a couple lines of code change. With a little more effort, `tf.distribute.Strategy` can also be used by other users who are not using these frameworks.TensorFlow is used for a wide variety of use cases and some users (such as researchers) require more flexibility and control over their training loops. This makes it hard for them to use the high level frameworks such as Estimator or Keras. For instance, someone using a GAN may want to take a different number of generator or discriminator steps each round. Similarly, the high level frameworks are not very suitable for Reinforcement Learning training. So these users will usually write their own training loops.For these users, we provide a core set of methods through the `tf.distribute.Strategy` classes. Using these may require minor restructuring of the code initially, but once that is done, the user should be able to switch between GPUs / TPUs / multiple machines by just changing the strategy instance.Here we will show a brief snippet illustrating this use case for a simple training example using the same Keras model as before. First, we create the model and optimizer inside the strategy's scope. This ensures that any variables created with the model and optimizer are mirrored variables.
###Code
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
optimizer = tf.keras.optimizers.SGD()
###Output
_____no_output_____
###Markdown
Next, we create the input dataset and call `tf.distribute.Strategy.experimental_distribute_dataset` to distribute the dataset based on the strategy.
###Code
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(1000).batch(
global_batch_size)
dist_dataset = mirrored_strategy.experimental_distribute_dataset(dataset)
###Output
_____no_output_____
###Markdown
Then, we define one step of the training. We will use `tf.GradientTape` to compute gradients and optimizer to apply those gradients to update our model's variables. To distribute this training step, we put in in a function `step_fn` and pass it to `tf.distrbute.Strategy.experimental_run_v2` along with the dataset inputs that we get from `dist_dataset` created before:
###Code
@tf.function
def train_step(dist_inputs):
def step_fn(inputs):
features, labels = inputs
with tf.GradientTape() as tape:
logits = model(features)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(
logits=logits, labels=labels)
loss = tf.reduce_sum(cross_entropy) * (1.0 / global_batch_size)
grads = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(list(zip(grads, model.trainable_variables)))
return cross_entropy
per_example_losses = mirrored_strategy.experimental_run_v2(
step_fn, args=(dist_inputs,))
mean_loss = mirrored_strategy.reduce(
tf.distribute.ReduceOp.MEAN, per_example_losses, axis=0)
return mean_loss
###Output
_____no_output_____
###Markdown
A few other things to note in the code above:1. We used `tf.nn.softmax_cross_entropy_with_logits` to compute the loss. And then we scaled the total loss by the global batch size. This is important because all the replicas are training in sync and number of examples in each step of training is the global batch. So the loss needs to be divided by the global batch size and not by the replica (local) batch size.2. We used the `tf.distribute.Strategy.reduce` API to aggregate the results returned by `tf.distribute.Strategy.experimental_run_v2`. `tf.distribute.Strategy.experimental_run_v2` returns results from each local replica in the strategy, and there are multiple ways to consume this result. You can `reduce` them to get an aggregated value. You can also do `tf.distribute.Strategy.experimental_local_results` to get the list of values contained in the result, one per local replica.3. When `apply_gradients` is called within a distribution strategy scope, its behavior is modified. Specifically, before applying gradients on each parallel instance during synchronous training, it performs a sum-over-all-replicas of the gradients. Finally, once we have defined the training step, we can iterate over `dist_dataset` and run the training in a loop:
###Code
with mirrored_strategy.scope():
for inputs in dist_dataset:
print(train_step(inputs))
###Output
_____no_output_____
###Markdown
In the example above, we iterated over the `dist_dataset` to provide input to your training. We also provide the `tf.distribute.Strategy.make_experimental_numpy_dataset` to support numpy inputs. You can use this API to create a dataset before calling `tf.distribute.Strategy.experimental_distribute_dataset`.Another way of iterating over your data is to explicitly use iterators. You may want to do this when you want to run for a given number of steps as opposed to iterating over the entire dataset.The above iteration would now be modified to first create an iterator and then explicity call `next` on it to get the input data.
###Code
with mirrored_strategy.scope():
iterator = iter(dist_dataset)
for _ in range(10):
print(train_step(next(iterator)))
###Output
_____no_output_____
###Markdown
This covers the simplest case of using `tf.distribute.Strategy` API to distribute custom training loops. We are in the process of improving these APIs. Since this use case requires more work on the part of the user, we will be publishing a separate detailed guide in the future. What's supported now?In TF 2.0 release, training with custom training loops is supported using `MirroredStrategy` as shown above and `TPUStrategy`. `MultiWorkerMirorredStrategy` support will be coming in the future.| Training API | MirroredStrategy | TPUStrategy | MultiWorkerMirroredStrategy | CentralStorageStrategy | ParameterServerStrategy ||:----------------------- |:------------------- |:------------------- |:----------------------------- |:------------------------ |:------------------------- || Custom Training Loop | Experimental support | Experimental support | Support planned post 2.0 | Support planned post 2.0 | No support yet | Examples and TutorialsHere are some examples for using distribution strategy with custom training loops:1. [Tutorial](../tutorials/distribute/training_loops.ipynb) to train MNIST using `MirroredStrategy`.2. [DenseNet](https://github.com/tensorflow/examples/blob/master/tensorflow_examples/models/densenet/distributed_train.py) example using `MirroredStrategy`.1. [BERT](https://github.com/tensorflow/models/blob/master/official/bert/run_classifier.py) example trained using `MirroredStrategy` and `TPUStrategy`.This example is particularly helpful for understanding how to load from a checkpoint and generate periodic checkpoints during distributed training etc.2. [NCF](https://github.com/tensorflow/models/blob/master/official/recommendation/ncf_keras_main.py) example trained using `MirroredStrategy` and `TPUStrategy` that can be enabled using the `keras_use_ctl` flag.3. [NMT](https://github.com/tensorflow/examples/blob/master/tensorflow_examples/models/nmt_with_attention/distributed_train.py) example trained using `MirroredStrategy`. Using `tf.distribute.Strategy` with Estimator (Limited support)`tf.estimator` is a distributed training TensorFlow API that originally supported the async parameter server approach. Like with Keras, we've integrated `tf.distribute.Strategy` into `tf.Estimator` so that a user who is using Estimator for their training can easily change their training is distributed with very few changes to your their code. With this, estimator users can now do synchronous distributed training on multiple GPUs and multiple workers, as well as use TPUs. This support in estimator is, however, limited. See [What's supported now](estimator_support) section below for more details.The usage of `tf.distribute.Strategy` with Estimator is slightly different than the Keras case. Instead of using `strategy.scope`, now we pass the strategy object into the [`RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig) for the Estimator.Here is a snippet of code that shows this with a premade estimator `LinearRegressor` and `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
config = tf.estimator.RunConfig(
train_distribute=mirrored_strategy, eval_distribute=mirrored_strategy)
regressor = tf.estimator.LinearRegressor(
feature_columns=[tf.feature_column.numeric_column('feats')],
optimizer='SGD',
config=config)
###Output
_____no_output_____
###Markdown
We use a premade Estimator here, but the same code works with a custom Estimator as well. `train_distribute` determines how training will be distributed, and `eval_distribute` determines how evaluation will be distributed. This is another difference from Keras where we use the same strategy for both training and eval.Now we can train and evaluate this Estimator with an input function:
###Code
def input_fn():
dataset = tf.data.Dataset.from_tensors(({"feats":[1.]}, [1.]))
return dataset.repeat(1000).batch(10)
regressor.train(input_fn=input_fn, steps=10)
regressor.evaluate(input_fn=input_fn, steps=10)
###Output
_____no_output_____
###Markdown
Copyright 2018 The TensorFlow Authors.
###Code
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###Output
_____no_output_____
###Markdown
Distributed training in TensorFlow View on TensorFlow.org Run in Google Colab View source on GitHub Overview`tf.distribute.Strategy` is a TensorFlow API to distribute training across multiple GPUs, multiple machines or TPUs. Using this API, users can distribute their existing models and training code with minimal code changes.`tf.distribute.Strategy` has been designed with these key goals in mind:* Easy to use and support multiple user segments, including researchers, ML engineers, etc.* Provide good performance out of the box.* Easy switching between strategies.`tf.distribute.Strategy` can be used with TensorFlow's high level APIs, [tf.keras](https://www.tensorflow.org/guide/keras) and [tf.estimator](https://www.tensorflow.org/guide/estimators), with just a couple of lines of code change. It also provides an API that can be used to distribute custom training loops (and in general any computation using TensorFlow).In TensorFlow 2.0, users can execute their programs eagerly, or in a graph using [`tf.function`](../tutorials/eager/tf_function.ipynb). `tf.distribute.Strategy` intends to support both these modes of execution. Note that we may talk about training most of the time in this guide, but this API can also be used for distributing evaluation and prediction on different platforms.As you will see in a bit, very few changes are needed to use `tf.distribute.Strategy` with your code. This is because we have changed the underlying components of TensorFlow to become strategy-aware. This includes variables, layers, models, optimizers, metrics, summaries, and checkpoints.In this guide, we will talk about various types of strategies and how one can use them in a different situations.
###Code
# Import TensorFlow
from __future__ import absolute_import, division, print_function, unicode_literals
!pip install tensorflow-gpu==2.0.0-beta0
import tensorflow as tf
###Output
_____no_output_____
###Markdown
Types of strategies`tf.distribute.Strategy` intends to cover a number of use cases along different axes. Some of these combinations are currently supported and others will be added in the future. Some of these axes are:* Synchronous vs asynchronous training: These are two common ways of distributing training with data parallelism. In sync training, all workers train over different slices of input data in sync, and aggregating gradients at each step. In async training, all workers are independently training over the input data and updating variables asynchronously. Typically sync training is supported via all-reduce and async through parameter server architecture.* Hardware platform: Users may want to scale their training onto multiple GPUs on one machine, or multiple machines in a network (with 0 or more GPUs each), or on Cloud TPUs.In order to support these use cases, we have 5 strategies available. In the next section we will talk about which of these are supported in which scenarios in TF 2.0-beta at this time. Here is a quick overview:| Training API | MirroredStrategy | TPUStrategy | MultiWorkerMirroredStrategy | CentralStorageStrategy | ParameterServerStrategy ||:----------------------- |:------------------- |:--------------------- |:--------------------------------- |:--------------------------------- |:-------------------------- || **Keras API** | Supported | Support planned in 2.0 RC | Experimental support | Experimental support | Supported planned in post 2.0 || **Custom training loop** | Experimental support | Experimental support | Support planned in 2.0 RC | Support planned in 2.0 RC | No support yet || **Estimator API** | Supported | Supported | Supported | Supported | Supported | MirroredStrategy`tf.distribute.MirroredStrategy` supports synchronous distributed training on multiple GPUs on one machine. It creates one replica per GPU device. Each variable in the model is mirrored across all the replicas. Together, these variables form a single conceptual variable called `MirroredVariable`. These variables are kept in sync with each other by applying identical updates.Efficient all-reduce algorithms are used to communicate the variable updates across the devices.All-reduce aggregates tensors across all the devices by adding them up, and makes them available on each device.It’s a fused algorithm that is very efficient and can reduce the overhead of synchronization significantly. There are many all-reduce algorithms and implementations available, depending on the type of communication available between devices. By default, it uses NVIDIA NCCL as the all-reduce implementation. The user can also choose between a few other options we provide, or write their own.Here is the simplest way of creating `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
###Output
_____no_output_____
###Markdown
This will create a `MirroredStrategy` instance which will use all the GPUs that are visible to TensorFlow, and use NCCL as the cross device communication.If you wish to use only some of the GPUs on your machine, you can do so like this:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(devices=["/gpu:0", "/gpu:1"])
###Output
_____no_output_____
###Markdown
If you wish to override the cross device communication, you can do so using the `cross_device_ops` argument by supplying an instance of `tf.distribute.CrossDeviceOps`. Currently we provide `tf.distribute.HierarchicalCopyAllReduce` and `tf.distribute.ReductionToOneDevice` as 2 other options other than `tf.distribute.NcclAllReduce` which is the default.
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(
cross_device_ops=tf.distribute.HierarchicalCopyAllReduce())
###Output
_____no_output_____
###Markdown
CentralStorageStrategy`tf.distribute.experimental.CentralStorageStrategy` does synchronous training as well. Variables are not mirrored, instead they are placed on the CPU and operations are replicated across all local GPUs. If there is only one GPU, all variables and operations will be placed on that GPU.Create an instance of `CentralStorageStrategy` by:
###Code
central_storage_strategy = tf.distribute.experimental.CentralStorageStrategy()
###Output
_____no_output_____
###Markdown
This will create a `CentralStorageStrategy` instance which will use all visible GPUs and CPU. Update to variables on replicas will be aggregated before being applied to variables. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. MultiWorkerMirroredStrategy`tf.distribute.experimental.MultiWorkerMirroredStrategy` is very similar to `MirroredStrategy`. It implements synchronous distributed training across multiple workers, each with potentially multiple GPUs. Similar to `MirroredStrategy`, it creates copies of all variables in the model on each device across all workers.It uses [CollectiveOps](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/collective_ops.py) as the multi-worker all-reduce communication method used to keep variables in sync. A collective op is a single op in the TensorFlow graph which can automatically choose an all-reduce algorithm in the TensorFlow runtime according to hardware, network topology and tensor sizes.It also implements additional performance optimizations. For example, it includes a static optimization that converts multiple all-reductions on small tensors into fewer all-reductions on larger tensors. In addition, we are designing it to have a plugin architecture - so that in the future, users will be able to plugin algorithms that are better tuned for their hardware. Note that collective ops also implement other collective operations such as broadcast and all-gather.Here is the simplest way of creating `MultiWorkerMirroredStrategy`:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()
###Output
_____no_output_____
###Markdown
`MultiWorkerMirroredStrategy` currently allows you to choose between two different implementations of collective ops. `CollectiveCommunication.RING` implements ring-based collectives using gRPC as the communication layer. `CollectiveCommunication.NCCL` uses [Nvidia's NCCL](https://developer.nvidia.com/nccl) to implement collectives. `CollectiveCommunication.AUTO` defers the choice to the runtime. The best choice of collective implementation depends upon the number and kind of GPUs, and the network interconnect in the cluster. You can specify them in the following way:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy(
tf.distribute.experimental.CollectiveCommunication.NCCL)
###Output
_____no_output_____
###Markdown
One of the key differences to get multi worker training going, as compared to multi-GPU training, is the multi-worker setup. "TF_CONFIG" environment variable is the standard way in TensorFlow to specify the cluster configuration to each worker that is part of the cluster. See section on ["TF_CONFIG" below](TF_CONFIG) for more details on how this can be done. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. TPUStrategy`tf.distribute.experimental.TPUStrategy` lets users run their TensorFlow training on Tensor Processing Units (TPUs). TPUs are Google's specialized ASICs designed to dramatically accelerate machine learning workloads. They are available on Google Colab, the [TensorFlow Research Cloud](https://www.tensorflow.org/tfrc) and [Google Compute Engine](https://cloud.google.com/tpu).In terms of distributed training architecture, TPUStrategy is the same `MirroredStrategy` - it implements synchronous distributed training. TPUs provide their own implementation of efficient all-reduce and other collective operations across multiple TPU cores, which are used in `TPUStrategy`.Here is how you would instantiate `TPUStrategy`.Note: To run this code in Colab, you should select TPU as the Colab runtime. We will have a tutorial soon that will demonstrate how you can use TPUStrategy.```cluster_resolver = tf.distribute.cluster_resolver.TPUClusterResolver( tpu=tpu_address)tf.config.experimental_connect_to_host(cluster_resolver.master())tf.tpu.experimental.initialize_tpu_system(cluster_resolver)tpu_strategy = tf.distribute.experimental.TPUStrategy(cluster_resolver)``` `TPUClusterResolver` instance helps locate the TPUs. In Colab, you don't need to specify any arguments to it. If you want to use this for Cloud TPUs, you will need to specify the name of your TPU resource in `tpu` argument. We also need to initialize the tpu system explicitly at the start of the program. This is required before TPUs can be used for computation and should ideally be done at the beginning because it also wipes out the TPU memory so all state will be lost. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. ParameterServerStrategy`tf.distribute.experimental.ParameterServerStrategy` supports parameter servers training on multiple machines. In this setup, some machines are designated as workers and some as parameter servers. Each variable of the model is placed on one parameter server. Computation is replicated across all GPUs of the all the workers.In terms of code, it looks similar to other strategies:```ps_strategy = tf.distribute.experimental.ParameterServerStrategy()``` For multi worker training, "TF_CONFIG" needs to specify the configuration of parameter servers and workers in your cluster, which you can read more about in ["TF_CONFIG" below](TF_CONFIG) below. So far we've talked about what are the different stategies available and how you can instantiate them. In the next few sections, we will talk about the different ways in which you can use them to distribute your training. We will show short code snippets in this guide and link off to full tutorials which you can run end to end. Using `tf.distribute.Strategy` with KerasWe've integrated `tf.distribute.Strategy` into `tf.keras` which is TensorFlow's implementation of the[Keras API specification](https://keras.io). `tf.keras` is a high-level API to build and train models. By integrating into `tf.keras` backend, we've made it seamless for Keras users to distribute their training written in the Keras training framework. The only things that need to change in a user's program are: (1) Create an instance of the appropriate `tf.distribute.Strategy` and (2) Move the creation and compiling of Keras model inside `strategy.scope`. We support all types of Keras models - sequential, functional and subclassed.Here is a snippet of code to do this for a very simple Keras model with one dense layer:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
model.compile(loss='mse', optimizer='sgd')
###Output
_____no_output_____
###Markdown
In this example we used `MirroredStrategy` so we can run this on a machine with multiple GPUs. `strategy.scope()` indicated which parts of the code to run distributed. Creating a model inside this scope allows us to create mirrored variables instead of regular variables. Compiling under the scope allows us to know that the user intends to train this model using this strategy. Once this is setup, you can fit your model like you would normally. `MirroredStrategy` takes care of replicating the model's training on the available GPUs, aggregating gradients etc.
###Code
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100).batch(10)
model.fit(dataset, epochs=2)
model.evaluate(dataset)
###Output
_____no_output_____
###Markdown
Here we used a `tf.data.Dataset` to provide the training and eval input. You can also use numpy arrays:
###Code
import numpy as np
inputs, targets = np.ones((100, 1)), np.ones((100, 1))
model.fit(inputs, targets, epochs=2, batch_size=10)
###Output
_____no_output_____
###Markdown
In both cases (dataset or numpy), each batch of the given input is divided equally among the multiple replicas. For instance, if using `MirroredStrategy` with 2 GPUs, each batch of size 10 will get divided among the 2 GPUs, with each receiving 5 input examples in each step. Each epoch will then train faster as you add more GPUs. Typically, you would want to increase your batch size as you add more accelerators so as to make effective use of the extra computing power. You will also need to re-tune your learning rate, depending on the model. You can use `strategy.num_replicas_in_sync` to get the number of replicas.
###Code
# Compute global batch size using number of replicas.
BATCH_SIZE_PER_REPLICA = 5
global_batch_size = (BATCH_SIZE_PER_REPLICA *
mirrored_strategy.num_replicas_in_sync)
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100)
dataset = dataset.batch(global_batch_size)
LEARNING_RATES_BY_BATCH_SIZE = {5: 0.1, 10: 0.15}
learning_rate = LEARNING_RATES_BY_BATCH_SIZE[global_batch_size]
###Output
_____no_output_____
###Markdown
What's supported now?In TF 2.0 beta release, we support training with Keras using `MirroredStrategy`, `CentralStorageStrategy` and `MultiWorkerMirroredStrategy`. Both `CentralStorageStrategy` and `MultiWorkerMirroredStrategy` are currently experimental APIs and are subject to change.Support for other strategies will be coming soon. The API and how to use will be exactly the same as above.| Training API | MirroredStrategy | TPUStrategy | MultiWorkerMirroredStrategy | CentralStorageStrategy | ParameterServerStrategy ||---------------- |--------------------- |----------------------- |----------------------------------- |----------------------------------- |--------------------------- || Keras APIs | Supported | Support planned in 2.0 RC | Experimental support | Experimental support | Support planned in post 2.0 | Examples and TutorialsHere is a list of tutorials and examples that illustrate the above integration end to end with Keras:1. Tutorial to train [MNIST](../tutorials/distribute/keras.ipynb) with `MirroredStrategy`.2. Official [ResNet50](https://github.com/tensorflow/models/blob/master/official/resnet/keras/keras_imagenet_main.py) training with ImageNet data using `MirroredStrategy`.3. [ResNet50](https://github.com/tensorflow/tpu/blob/master/models/experimental/resnet50_keras/resnet50.py) trained with Imagenet data on Cloud TPus with `TPUStrategy`. Note that this example only works with TensorFlow 1.x currently.4. [Tutorial](../tutorials/distribute/multi_worker_with_keras.ipynb) to train MNIST using `MultiWorkerMirroredStrategy`.5. [NCF](https://github.com/tensorflow/models/blob/master/official/recommendation/ncf_keras_main.py) trained using `MirroredStrategy`.2. [Transformer]( https://github.com/tensorflow/models/blob/master/official/transformer/v2/transformer_main.py) trained using `MirroredStrategy`. Using `tf.distribute.Strategy` with Estimator`tf.estimator` is a distributed training TensorFlow API that originally supported the async parameter server approach. Like with Keras, we've integrated `tf.distribute.Strategy` into `tf.Estimator` so that a user who is using Estimator for their training can easily change their training is distributed with very few changes to your their code. With this, estimator users can now do synchronous distributed training on multiple GPUs and multiple workers, as well as use TPUs.The usage of `tf.distribute.Strategy` with Estimator is slightly different than the Keras case. Instead of using `strategy.scope`, now we pass the strategy object into the [`RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig) for the Estimator.Here is a snippet of code that shows this with a premade estimator `LinearRegressor` and `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
config = tf.estimator.RunConfig(
train_distribute=mirrored_strategy, eval_distribute=mirrored_strategy)
regressor = tf.estimator.LinearRegressor(
feature_columns=[tf.feature_column.numeric_column('feats')],
optimizer='SGD',
config=config)
###Output
_____no_output_____
###Markdown
We use a premade Estimator here, but the same code works with a custom Estimator as well. `train_distribute` determines how training will be distributed, and `eval_distribute` determines how evaluation will be distributed. This is another difference from Keras where we use the same strategy for both training and eval.Now we can train and evaluate this Estimator with an input function:
###Code
def input_fn():
dataset = tf.data.Dataset.from_tensors(({"feats":[1.]}, [1.]))
return dataset.repeat(1000).batch(10)
regressor.train(input_fn=input_fn, steps=10)
regressor.evaluate(input_fn=input_fn, steps=10)
###Output
_____no_output_____
###Markdown
Another difference to highlight here between Estimator and Keras is the input handling. In Keras, we mentioned that each batch of the dataset is split across the multiple replicas. In Estimator, however, the user provides an `input_fn` and have full control over how they want their data to be distributed across workers and devices. We do not do automatic splitting of batch, nor automatically shard the data across different workers. The provided `input_fn` is called once per worker, thus giving one dataset per worker. Then one batch from that dataset is fed to one replica on that worker, thereby consuming N batches for N replicas on 1 worker. In other words, the dataset returned by the `input_fn` should provide batches of size `PER_REPLICA_BATCH_SIZE`. And the global batch size for a step can be obtained as `PER_REPLICA_BATCH_SIZE * strategy.num_replicas_in_sync`. When doing multi worker training, users will also want to either split their data across the workers, or shuffle with a random seed on each. You can see an example of how to do this in the [Multi-worker Training with Estimator](../tutorials/distribute/multi_worker_with_estimator.ipynb). We showed an example of using `MirroredStrategy` with Estimator. You can also use `TPUStrategy` with Estimator as well, in the exact same way:```config = tf.estimator.RunConfig( train_distribute=tpu_strategy, eval_distribute=tpu_strategy)``` And similarly, you can use multi worker and parameter server strategies as well. The code remains the same, but you need to use `tf.estimator.train_and_evaluate`, and set "TF_CONFIG" environment variables for each binary running in your cluster. What's supported now?In TF 2.0 beta release, we support training with Estimator using all strategies.| Training API | MirroredStrategy | TPUStrategy | MultiWorkerMirroredStrategy | CentralStorageStrategy | ParameterServerStrategy ||:--------------- |:------------------ |:------------- |:----------------------------- |:------------------------ |:------------------------- || Estimator API | Supported | Supported | Supported | Supported | Supported | Examples and TutorialsHere are some examples that show end to end usage of various strategies with Estimator:1. [Multi-worker Training with Estimator](../tutorials/distribute/multi_worker_with_estimator.ipynb) to train MNIST with multiple workers using `MultiWorkerMirroredStrategy`.2. [End to end example](https://github.com/tensorflow/ecosystem/tree/master/distribution_strategy) for multi worker training in tensorflow/ecosystem using Kuberentes templates. This example starts with a Keras model and converts it to an Estimator using the `tf.keras.estimator.model_to_estimator` API.3. Official [ResNet50](https://github.com/tensorflow/models/blob/master/official/resnet/imagenet_main.py) model, which can be trained using either `MirroredStrategy` or `MultiWorkerMirroredStrategy`.4. [ResNet50](https://github.com/tensorflow/tpu/blob/master/models/experimental/distribution_strategy/resnet_estimator.py) example with TPUStrategy. Using `tf.distribute.Strategy` with custom training loopsAs you've seen, using `tf.distribute.Strategy` with high level APIs is only a couple lines of code change. With a little more effort, `tf.distribute.Strategy` can also be used by other users who are not using these frameworks.TensorFlow is used for a wide variety of use cases and some users (such as researchers) require more flexibility and control over their training loops. This makes it hard for them to use the high level frameworks such as Estimator or Keras. For instance, someone using a GAN may want to take a different number of generator or discriminator steps each round. Similarly, the high level frameworks are not very suitable for Reinforcement Learning training. So these users will usually write their own training loops.For these users, we provide a core set of methods through the `tf.distribute.Strategy` classes. Using these may require minor restructuring of the code initially, but once that is done, the user should be able to switch between GPUs / TPUs / multiple machines by just changing the strategy instance.Here we will show a brief snippet illustrating this use case for a simple training example using the same Keras model as before. First, we create the model and optimizer inside the strategy's scope. This ensures that any variables created with the model and optimizer are mirrored variables.
###Code
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
optimizer = tf.keras.optimizers.SGD()
###Output
_____no_output_____
###Markdown
Next, we create the input dataset and call `tf.distribute.Strategy.experimental_distribute_dataset` to distribute the dataset based on the strategy.
###Code
with mirrored_strategy.scope():
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(1000).batch(
global_batch_size)
dist_dataset = mirrored_strategy.experimental_distribute_dataset(dataset)
###Output
_____no_output_____
###Markdown
Then, we define one step of the training. We will use `tf.GradientTape` to compute gradients and optimizer to apply those gradients to update our model's variables. To distribute this training step, we put in in a function `step_fn` and pass it to `tf.distrbute.Strategy.experimental_run_v2` along with the dataset inputs that we get from `dist_dataset` created before:
###Code
@tf.function
def train_step(dist_inputs):
def step_fn(inputs):
features, labels = inputs
with tf.GradientTape() as tape:
logits = model(features)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(
logits=logits, labels=labels)
loss = tf.reduce_sum(cross_entropy) * (1.0 / global_batch_size)
grads = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(list(zip(grads, model.trainable_variables)))
return cross_entropy
per_example_losses = mirrored_strategy.experimental_run_v2(
step_fn, args=(dist_inputs,))
mean_loss = mirrored_strategy.reduce(
tf.distribute.ReduceOp.MEAN, per_example_losses, axis=0)
return mean_loss
###Output
_____no_output_____
###Markdown
A few other things to note in the code above:1. We used `tf.nn.softmax_cross_entropy_with_logits` to compute the loss. And then we scaled the total loss by the global batch size. This is important because all the replicas are training in sync and number of examples in each step of training is the global batch. So the loss needs to be divided by the global batch size and not by the replica (local) batch size.2. We used the `tf.distribute.Strategy.reduce` API to aggregate the results returned by `tf.distribute.Strategy.experimental_run_v2`. `tf.distribute.Strategy.experimental_run_v2` returns results from each local replica in the strategy, and there are multiple ways to consume this result. You can `reduce` them to get an aggregated value. You can also do `tf.distribute.Strategy.experimental_local_results` to get the list of values contained in the result, one per local replica.3. When `apply_gradients` is called within a distribution strategy scope, its behavior is modified. Specifically, before applying gradients on each parallel instance during synchronous training, it performs a sum-over-all-replicas of the gradients. Finally, once we have defined the training step, we can iterate over `dist_dataset` and run the training in a loop:
###Code
with mirrored_strategy.scope():
for inputs in dist_dataset:
print(train_step(inputs))
###Output
_____no_output_____
###Markdown
In the example above, we iterated over the `dist_dataset` to provide input to your training. We also provide the `tf.distribute.Strategy.make_experimental_numpy_dataset` to support numpy inputs. You can use this API to create a dataset before calling `tf.distribute.Strategy.experimental_distribute_dataset`.Another way of iterating over your data is to explicitly use iterators. You may want to do this when you want to run for a given number of steps as opposed to iterating over the entire dataset.The above iteration would now be modified to first create an iterator and then explicity call `next` on it to get the input data.
###Code
with mirrored_strategy.scope():
iterator = iter(dist_dataset)
for _ in range(10):
print(train_step(next(iterator)))
###Output
_____no_output_____
###Markdown
Copyright 2018 The TensorFlow Authors.
###Code
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###Output
_____no_output_____
###Markdown
Distributed Training in TensorFlow View on TensorFlow.org Run in Google Colab View source on GitHub Overview`tf.distribute.Strategy` is a TensorFlow API to distribute trainingacross multiple GPUs, multiple machines or TPUs. Using this API, users can distribute their existing models and training code with minimal code changes.`tf.distribute.Strategy` has been designed with these key goals in mind:* Easy to use and support multiple user segments, including researchers, ML engineers, etc.* Provide good performance out of the box.* Easy switching between strategies.`tf.distribute.Strategy` can be used with TensorFlow's high level APIs, [tf.keras](https://www.tensorflow.org/guide/keras) and [tf.estimator](https://www.tensorflow.org/guide/estimators), with just a couple of lines of code change. It also provides an API that can be used to distribute custom training loops (and in general any computation using TensorFlow).In TensorFlow 2.0, users can execute their programs eagerly, or in a graph using [`tf.function`](../tutorials/eager/tf_function.ipynb). `tf.distribute.Strategy` intends to support both these modes of execution. Note that we may talk about training most of the time in this guide, but this API can also be used for distributing evaluation and prediction on different platforms.As you will see in a bit, very few changes are needed to use `tf.distribute.Strategy` with your code. This is because we have changed the underlying components of TensorFlow to become strategy-aware. This includes variables, layers, models, optimizers, metrics, summaries, and checkpoints.In this guide, we will talk about various types of strategies and how one can use them in a different situations.
###Code
# Import TensorFlow
from __future__ import absolute_import, division, print_function, unicode_literals
!pip install tensorflow-gpu==2.0.0-alpha0
import tensorflow as tf
###Output
_____no_output_____
###Markdown
Types of strategies`tf.distribute.Strategy` intends to cover a number of use cases along different axes. Some of these combinations are currently supported and others will be added in the future. Some of these axes are:* Syncronous vs asynchronous training: These are two common ways of distributing training with data parallelism. In sync training, all workers train over different slices of input data in sync, and aggregating gradients at each step. In async training, all workers are independently training over the input data and updating variables asynchronously. Typically sync training is supported via all-reduce and async through parameter server architecture.* Hardware platform: Users may want to scale their training onto multiple GPUs on one machine, or multiple machines in a network (with 0 or more GPUs each), or on Cloud TPUs.In order to support these use cases, we have 4 strategies available. In the next section we will talk about which of these are supported in which scenarios in TF 2.0-alpha at this time. MirroredStrategy`tf.distribute.MirroredStrategy` support synchronous distributed training on multiple GPUs on one machine. It creates one replica per GPU device. Each variable in the model is mirrored across all the replicas. Together, these variables form a single conceptual variable called `MirroredVariable`. These variables are kept in sync with each other by applying identical updates.Efficient all-reduce algorithms are used to communicate the variable updates across the devices.All-reduce aggregates tensors across all the devices by adding them up, and makes them available on each device.It’s a fused algorithm that is very efficient and can reduce the overhead of synchronization significantly. There are many all-reduce algorithms and implementations available, depending on the type of communication available between devices. By default, it uses NVIDIA NCCL as the all-reduce implementation. The user can also choose between a few other options we provide, or write their own.Here is the simplest way of creating `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
###Output
_____no_output_____
###Markdown
This will create a `MirroredStrategy` instance which will use all the GPUs that are visible to TensorFlow, and use NCCL as the cross device communication.If you wish to use only some of the GPUs on your machine, you can do so like this:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(devices=["/gpu:0", "/gpu:1"])
###Output
_____no_output_____
###Markdown
If you wish to override the cross device communication, you can do so using the `cross_device_ops` argument by supplying an instance of `tf.distribute.CrossDeviceOps`. Currently we provide `tf.distribute.HierarchicalCopyAllReduce` and `tf.distribute.ReductionToOneDevice` as 2 other options other than `tf.distribute.NcclAllReduce` which is the default.
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(
cross_device_ops=tf.distribute.HierarchicalCopyAllReduce())
###Output
_____no_output_____
###Markdown
MultiWorkerMirroredStrategy`tf.distribute.experimental.MultiWorkerMirroredStrategy` is very similar to `MirroredStrategy`. It implements synchronous distributed training across multiple workers, each with potentially multiple GPUs. Similar to `MirroredStrategy`, it creates copies of all variables in the model on each device across all workers.It uses [CollectiveOps](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/collective_ops.py) as the multi-worker all-reduce communication method used to keep variables in sync. A collective op is a single op in the TensorFlow graph which can automatically choose an all-reduce algorithm in the TensorFlow runtime according to hardware, network topology and tensor sizes.It also implements additional performance optimizations. For example, it includes a static optimization that converts multiple all-reductions on small tensors into fewer all-reductions on larger tensors. In addition, we are designing it to have a plugin architecture - so that in the future, users will be able to plugin algorithms that are better tuned for their hardware. Note that collective ops also implement other collective operations such as broadcast and all-gather.Here is the simplest way of creating `MultiWorkerMirroredStrategy`:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()
###Output
_____no_output_____
###Markdown
`MultiWorkerMirroredStrategy` currently allows you to choose between two different implementations of collective ops. `CollectiveCommunication.RING` implements ring-based collectives using gRPC as the communication layer. `CollectiveCommunication.NCCL` uses [Nvidia's NCCL](https://developer.nvidia.com/nccl) to implement collectives. `CollectiveCommunication.AUTO` defers the choice to the runtime. The best choice of collective implementation depends upon the number and kind of GPUs, and the network interconnect in the cluster. You can specify them like so:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy(
tf.distribute.experimental.CollectiveCommunication.NCCL)
###Output
_____no_output_____
###Markdown
One of the key differences to get multi worker training going, as compared to multi-GPU training, is the multi-worker setup. "TF_CONFIG" environment variable is the standard way in TensorFlow to specify the cluster configuration to each worker that is part of the cluster. See section on ["TF_CONFIG" below](TF_CONFIG) for more details on how this can be done. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. TPUStrategy`tf.distribute.experimental.TPUStrategy` lets users run their TensorFlow training on Tensor Processing Units (TPUs). TPUs are Google's specialized ASICs designed to dramatically accelerate machine learning workloads. They are available on Google Colab, the [TensorFlow Research Cloud](https://www.tensorflow.org/tfrc) and [Google Compute Engine](https://cloud.google.com/tpu).In terms of distributed training architecture, TPUStrategy is the same `MirroredStrategy` - it implements synchronous distributed training. TPUs provide their own implementation of efficient all-reduce and other collective operations across multiple TPU cores, which are used in `TPUStrategy`.Here is how you would instantiate `TPUStrategy`.Note: To run this code in Colab, you should select TPU as the Colab runtime. See [Using TPUs]( tpu.ipynb) guide for a runnable version.```resolver = tf.distribute.cluster_resolver.TPUClusterResolver()tf.tpu.experimental.initialize_tpu_system(resolver)tpu_strategy = tf.distribute.experimental.TPUStrategy(resolver)``` `TPUClusterResolver` instance helps locate the TPUs. In Colab, you don't need to specify any arguments to it. If you want to use this for Cloud TPUs, you will need to specify the name of your TPU resource in `tpu` argument. We also need to initialize the tpu system explicitly at the start of the program. This is required before TPUs can be used for computation and should ideally be done at the beginning because it also wipes out the TPU memory so all state will be lost. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. ParameterServerStrategy`tf.distribute.experimental.ParameterServerStrategy` supports parameter servers training. It can be used either for multi-GPU synchronous local training or asynchronous multi-machine training. When used to train locally on one machine, variables are not mirrored, instead they are placed on the CPU and operations are replicated across all local GPUs. In a multi-machine setting, some machines are designated as workers and some as parameter servers. Each variable of the model is placed on one parameter server. Computation is replicated across all GPUs of the all the workers.In terms of code, it looks similar to other strategies:
###Code
ps_strategy = tf.distribute.experimental.ParameterServerStrategy()
###Output
_____no_output_____
###Markdown
For multi worker training, "TF_CONFIG" needs to specify the configuration of parameter servers and workers in your cluster, which you can read more about in ["TF_CONFIG" below](TF_CONFIG) below. So far we've talked about what are the different stategies available and how you can instantiate them. In the next few sections, we will talk about the different ways in which you can use them to distribute your training. We will show short code snippets in this guide and link off to full tutorials which you can run end to end. Using `tf.distribute.Strategy` with KerasWe've integrated `tf.distribute.Strategy` into `tf.keras` which is TensorFlow's implementation of the[Keras API specification](https://keras.io). `tf.keras` is a high-level API to build and train models. By integrating into `tf.keras` backend, we've made it seamless for Keras users to distribute their training written in the Keras training framework. The only things that need to change in a user's program are: (1) Create an instance of the appropriate `tf.distribute.Strategy` and (2) Move the creation and compiling of Keras model inside `strategy.scope`.Here is a snippet of code to do this for a very simple Keras model with one dense layer:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
model.compile(loss='mse', optimizer='sgd')
###Output
_____no_output_____
###Markdown
In this example we used `MirroredStrategy` so we can run this on a machine with multiple GPUs. `strategy.scope()` indicated which parts of the code to run distributed. Creating a model inside this scope allows us to create mirrored variables instead of regular variables. Compiling under the scope allows us to know that the user intends to train this model using this strategy. Once this is setup, you can fit your model like you would normally. `MirroredStrategy` takes care of replicating the model's training on the available GPUs, aggregating gradients etc.
###Code
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100).batch(10)
model.fit(dataset, epochs=2)
model.evaluate(dataset)
###Output
_____no_output_____
###Markdown
Here we used a `tf.data.Dataset` to provide the training and eval input. You can also use numpy arrays:
###Code
import numpy as np
inputs, targets = np.ones((100, 1)), np.ones((100, 1))
model.fit(inputs, targets, epochs=2, batch_size=10)
###Output
_____no_output_____
###Markdown
In both cases (dataset or numpy), each batch of the given input is divided equally among the multiple replicas. For instance, if using `MirroredStrategy` with 2 GPUs, each batch of size 10 will get divided among the 2 GPUs, with each receiving 5 input examples in each step. Each epoch will then train faster as you add more GPUs. Typically, you would want to increase your batch size as you add more accelerators so as to make effective use of the extra computing power. You will also need to re-tune your learning rate, depending on the model. You can use `strategy.num_replicas_in_sync` to get the number of replicas.
###Code
# Compute global batch size using number of replicas.
BATCH_SIZE_PER_REPLICA = 5
global_batch_size = (BATCH_SIZE_PER_REPLICA *
mirrored_strategy.num_replicas_in_sync)
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100)
dataset = dataset.batch(global_batch_size)
LEARNING_RATES_BY_BATCH_SIZE = {5: 0.1, 10: 0.15}
learning_rate = LEARNING_RATES_BY_BATCH_SIZE[global_batch_size]
###Output
_____no_output_____
###Markdown
What's supported now?In TF 2.0 alpha release, we support training with Keras using `MirroredStrategy`, as well as one machine parameter server using `ParameterServerStrategy`.Support for other strategies will be coming soon. The API and how to use will be exactly the same as above. If you wish to use the other strategies like `TPUStrategy` or `MultiWorkerMirorredStrategy` in Keras in TF 2.0, you can currently do so by disabling eager execution (`tf.compat.v1.disable_eager_execution()`). Another thing to note is that when using `MultiWorkerMirorredStrategy` for multiple workers with Keras, currently the user will have to explicitly shard or shuffle the data for different workers, but we will change this in the future to automatically shard the input data intelligently. Examples and TutorialsHere is a list of tutorials and examples that illustrate the above integration end to end with Keras:1. [Tutorial](../tutorials/distribute/keras.ipynb) to train MNIST with `MirroredStrategy`.2. [Tutorial](tpu.ipynb) to train Fashion MNIST with `TPUStrategy` (currently uses `disable_eager_execution`)3. Official [ResNet50](https://github.com/tensorflow/models/blob/master/official/resnet/keras/keras_imagenet_main.py) training with ImageNet data using `MirroredStrategy`.4. [ResNet50](https://github.com/tensorflow/tpu/blob/master/models/experimental/resnet50_keras/resnet50.py) trained with Imagenet data on Cloud TPus with `TPUStrategy`. Note that this example only works with TensorFlow 1.x currently. Using `tf.distribute.Strategy` with Estimator`tf.estimator` is a distributed training TensorFlow API that originally supported the async parameter server approach. Like with Keras, we've integrated `tf.distribute.Strategy` into `tf.Estimator` so that a user who is using Estimator for their training can easily change their training is distributed with very few changes to your their code. With this, estimator users can now do synchronous distributed training on multiple GPUs and multiple workers, as well as use TPUs.The usage of `tf.distribute.Strategy` with Estimator is slightly different than the Keras case. Instead of using `strategy.scope`, now we pass the strategy object into the [`RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig) for the Estimator.Here is a snippet of code that shows this with a premade estimator `LinearRegressor` and `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
config = tf.estimator.RunConfig(
train_distribute=mirrored_strategy, eval_distribute=mirrored_strategy)
regressor = tf.estimator.LinearRegressor(
feature_columns=[tf.feature_column.numeric_column('feats')],
optimizer='SGD',
config=config)
###Output
_____no_output_____
###Markdown
We use a premade Estimator here, but the same code works with a custom Estimator as well. `train_distribute` determines how training will be distributed, and `eval_distribute` determines how evaluation will be distributed. This is another difference from Keras where we use the same strategy for both training and eval.Now we can train and evaluate this Estimator with an input function:
###Code
def input_fn():
dataset = tf.data.Dataset.from_tensors(({"feats":[1.]}, [1.]))
return dataset.repeat(1000).batch(10)
regressor.train(input_fn=input_fn, steps=10)
regressor.evaluate(input_fn=input_fn, steps=10)
###Output
_____no_output_____
###Markdown
Another difference to highlight here between Estimator and Keras is the input handling. In Keras, we mentioned that each batch of the dataset is split across the multiple replicas. In Estimator, however, the user provides an `input_fn` and have full control over how they want their data to be distributed across workers and devices. We do not do automatic splitting of batch, nor automatically shard the data across different workers. The provided `input_fn` is called once per worker, thus giving one dataset per worker. Then one batch from that dataset is fed to one replica on that worker, thereby consuming N batches for N replicas on 1 worker. In other words, the dataset returned by the `input_fn` should provide batches of size `PER_REPLICA_BATCH_SIZE`. And the global batch size for a step can be obtained as `PER_REPLICA_BATCH_SIZE * strategy.num_replicas_in_sync`. When doing multi worker training, users will also want to either split their data across the workers, or shuffle with a random seed on each. You can see an example of how to do this in the [multi-worker tutorial](../tutorials/distribute/multi_worker.ipynb). We showed an example of using `MirroredStrategy` with Estimator. You can also use `TPUStrategy` with Estimator as well, in the exact same way:```config = tf.estimator.RunConfig( train_distribute=tpu_strategy, eval_distribute=tpu_strategy)``` And similarly, you can use multi worker and parameter server strategies as well. The code remains the same, but you need to use `tf.estimator.train_and_evaluate`, and set "TF_CONFIG" environment variables for each binary running in your cluster. What's supported now?In TF 2.0 alpha release, we support training with Estimator using all strategies. Examples and TutorialsHere are some examples that show end to end usage of various strategies with Estimator:1. [Tutorial]((../tutorials/distribute/multi_worker.ipynb) to train MNIST with multiple workers using `MultiWorkerMirroredStrategy`.2. [End to end example](https://github.com/tensorflow/ecosystem/tree/master/distribution_strategy) for multi worker training in tensorflow/ecosystem using Kuberentes templates. This example starts with a Keras model and converts it to an Estimator using the `tf.keras.estimator.model_to_estimator` API.3. Official [ResNet50](https://github.com/tensorflow/models/blob/master/official/resnet/imagenet_main.py) model, which can be trained using either `MirroredStrategy` or `MultiWorkerMirroredStrategy`.4. [ResNet50](https://github.com/tensorflow/tpu/blob/master/models/experimental/distribution_strategy/resnet_estimator.py) example with TPUStrategy. Using `tf.distribute.Strategy` with custom training loopsAs you've seen, using `tf.distrbute.Strategy` with high level APIs is only a couple lines of code change. With a little more effort, `tf.distrbute.Strategy` can also be used by other users who are not using these frameworks.TensorFlow is used for a wide variety of use cases and some users (such as researchers) require more flexibility and control over their training loops. This makes it hard for them to use the high level frameworks such as Estimator or Keras. For instance, someone using a GAN may want to take a different number of generator or discriminator steps each round. Similarly, the high level frameworks are not very suitable for Reinforcement Learning training. So these users will usually write their own training loops.For these users, we provide a core set of methods through the `tf.distrbute.Strategy` classes. Using these may require minor restructuring of the code initially, but once that is done, the user should be able to switch between GPUs / TPUs / multiple machines by just changing the strategy instance.Here we will show a brief snippet illustrating this use case for a simple training example using the same Keras model as before.Note: These APIs are still experimental and we are improving them to make them more user friendly in TensorFlow 2.0. First, we create the model and optimizer inside the strategy's scope. This ensures that any variables created with the model and optimizer are mirrored variables.
###Code
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
optimizer = tf.keras.optimizers.SGD()
###Output
_____no_output_____
###Markdown
Next, we create the input dataset and call `make_dataset_iterator` to distribute the dataset based on the strategy. This API is expected to change in the near future.
###Code
with mirrored_strategy.scope():
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(1000).batch(
global_batch_size)
input_iterator = mirrored_strategy.make_dataset_iterator(dataset)
###Output
_____no_output_____
###Markdown
Then, we define one step of the training. We will use `tf.GradientTape` to compute gradients and optimizer to apply those gradients to update our model's variables. To distribute this training step, we put in in a function `step_fn` and pass it to `strategy.experimental_run` along with the iterator created before:
###Code
@tf.function
def train_step():
def step_fn(inputs):
features, labels = inputs
with tf.GradientTape() as tape:
logits = model(features)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(
logits=logits, labels=labels)
loss = tf.reduce_sum(cross_entropy) * (1.0 / global_batch_size)
grads = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(list(zip(grads, model.trainable_variables)))
return loss
per_replica_losses = mirrored_strategy.experimental_run(
step_fn, input_iterator)
mean_loss = mirrored_strategy.reduce(
tf.distribute.ReduceOp.MEAN, per_replica_losses)
return mean_loss
###Output
_____no_output_____
###Markdown
A few other things to note in the code above:1. We used `tf.nn.softmax_cross_entropy_with_logits` to compute the loss. And then we scaled the total loss by the global batch size. This is important because all the replicas are training in sync and number of examples in each step of training is the global batch. If you're using TensorFlow's standard losses from `tf.losses` or `tf.keras.losses`, they are distribution aware and will take care of the scaling by number of replicas whenever a strategy is in scope.2. We used the `strategy.reduce` API to aggregate the results returned by `experimental_run`. `experimental_run` returns results from each local replica in the strategy, and there are multiple ways to consume this result. You can `reduce` them to get an aggregated value. You can also do `strategy.unwrap(results)`* to get the list of values contained in the result, one per local replica.*expected to change Finally, once we have defined the training step, we can initialize the iterator and run the training in a loop:
###Code
with mirrored_strategy.scope():
input_iterator.initialize()
for _ in range(10):
print(train_step())
###Output
_____no_output_____
###Markdown
Copyright 2018 The TensorFlow Authors.
###Code
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###Output
_____no_output_____
###Markdown
Distributed Training in TensorFlow View on TensorFlow.org Run in Google Colab View source on GitHub OverviewThe `tf.distribute.Strategy` API is an easy way to distribute your trainingacross multiple devices/machines. Our goal is to allow users to use existingmodels and training code with minimal changes to enable distributed training.Currently, in core TensorFlow, we support `tf.distribute.MirroredStrategy`. Thisdoes in-graph replication with synchronous training on many GPUs on one machine.Essentially, we create copies of all variables in the model's layers on eachdevice. We then use all-reduce to combine gradients across the devices beforeapplying them to the variables to keep them in sync.Many other strategies are available in TensorFlow 1.12+ contrib and will soon beavailable in core TensorFlow. You can find more information about them in thecontrib[README](https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/distribute).You can also read the[public design review](https://github.com/tensorflow/community/blob/master/rfcs/20181016-replicator.md)for updating the `tf.distribute.Strategy` API as part of the move from contribto core TF. Example with Keras APILet's see how to scale to multiple GPUs on one machine using `MirroredStrategy`with [tf.keras](https://www.tensorflow.org/guide/keras).We will take a very simple model consisting of a single layer. First, we will import Tensorflow.
###Code
!pip install tf-nightly
!pip install tf-nightly-2.0-preview
import tensorflow as tf
###Output
_____no_output_____
###Markdown
To distribute a Keras model on multiple GPUs using `MirroredStrategy`, we first instantiate a `MirroredStrategy` object.
###Code
strategy = tf.distribute.MirroredStrategy()
###Output
_____no_output_____
###Markdown
We then create and compile the Keras model in `strategy.scope`.
###Code
with strategy.scope():
inputs = tf.keras.layers.Input(shape=(1,))
predictions = tf.keras.layers.Dense(1)(inputs)
model = tf.keras.models.Model(inputs=inputs, outputs=predictions)
model.compile(loss='mse',
optimizer=tf.keras.optimizers.SGD(learning_rate=0.2))
###Output
_____no_output_____
###Markdown
Let's also define a simple input dataset for training this model.
###Code
train_dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(10000).batch(10)
###Output
_____no_output_____
###Markdown
To train the model we call Keras `fit` API using the input dataset that wecreated earlier, same as how we would in a non-distributed case.
###Code
model.fit(train_dataset, epochs=5, steps_per_epoch=10)
###Output
_____no_output_____
###Markdown
Similarly, we can also call `evaluate` and `predict` as before using appropriatedatasets.
###Code
eval_dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100).batch(10)
model.evaluate(eval_dataset, steps=10)
predict_dataset = tf.data.Dataset.from_tensors(([1.])).repeat(10).batch(2)
model.predict(predict_dataset, steps=5)
###Output
_____no_output_____
###Markdown
That's all you need to train your model with Keras on multiple GPUs with`MirroredStrategy`. It will take care of splitting upthe input dataset, replicating layers and variables on each device, andcombining and applying gradients.The model and input code does not have to change because we have changed theunderlying components of TensorFlow (such as optimizer, batch norm andsummaries) to become strategy-aware. That means those components know how tocombine their state across devices. Further, saving and checkpointing worksseamlessly, so you can save with one or no distribute strategy and resume withanother. Example with Estimator APIYou can also use `tf.distribute.Strategy` API with[`Estimator`](https://www.tensorflow.org/api_docs/python/tf/estimator/Estimator).Let's see a simple example of it's usage with `MirroredStrategy`.We will use the `LinearRegressor` premade estimator as an example. To use `MirroredStrategy` with Estimator, all we need to do is:* Create an instance of the `MirroredStrategy` class.* Pass it to the[`RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig)parameter of the custom or premade `Estimator`.
###Code
strategy = tf.distribute.MirroredStrategy()
config = tf.estimator.RunConfig(
train_distribute=strategy, eval_distribute=strategy)
regressor = tf.estimator.LinearRegressor(
feature_columns=[tf.feature_column.numeric_column('feats')],
optimizer='SGD',
config=config)
###Output
_____no_output_____
###Markdown
We will define a simple input function to feed data for training this model.
###Code
def input_fn():
return tf.data.Dataset.from_tensors(({"feats":[1.]}, [1.])).repeat(10000).batch(10)
###Output
_____no_output_____
###Markdown
Then we can call `train` on the regressor instance to train the model.
###Code
regressor.train(input_fn=input_fn, steps=10)
###Output
_____no_output_____
###Markdown
And we can `evaluate` to evaluate the trained model.
###Code
regressor.evaluate(input_fn=input_fn, steps=10)
###Output
_____no_output_____
###Markdown
Copyright 2018 The TensorFlow Authors.
###Code
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###Output
_____no_output_____
###Markdown
Distributed training in TensorFlow View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook Overview`tf.distribute.Strategy` is a TensorFlow API to distribute training across multiple GPUs, multiple machines or TPUs. Using this API, users can distribute their existing models and training code with minimal code changes.`tf.distribute.Strategy` has been designed with these key goals in mind:* Easy to use and support multiple user segments, including researchers, ML engineers, etc.* Provide good performance out of the box.* Easy switching between strategies.`tf.distribute.Strategy` can be used with TensorFlow's high level APIs, [tf.keras](https://www.tensorflow.org/guide/keras) and [tf.estimator](https://www.tensorflow.org/guide/estimators), with just a couple of lines of code change. It also provides an API that can be used to distribute custom training loops (and in general any computation using TensorFlow).In TensorFlow 2.0, users can execute their programs eagerly, or in a graph using [`tf.function`](../tutorials/eager/tf_function.ipynb). `tf.distribute.Strategy` intends to support both these modes of execution. Note that we may talk about training most of the time in this guide, but this API can also be used for distributing evaluation and prediction on different platforms.As you will see in a bit, very few changes are needed to use `tf.distribute.Strategy` with your code. This is because we have changed the underlying components of TensorFlow to become strategy-aware. This includes variables, layers, models, optimizers, metrics, summaries, and checkpoints.In this guide, we will talk about various types of strategies and how one can use them in a different situations.
###Code
# Import TensorFlow
from __future__ import absolute_import, division, print_function, unicode_literals
try:
# %tensorflow_version only exists in Colab.
%tensorflow_version 2.x
except Exception:
pass
import tensorflow as tf
###Output
_____no_output_____
###Markdown
Types of strategies`tf.distribute.Strategy` intends to cover a number of use cases along different axes. Some of these combinations are currently supported and others will be added in the future. Some of these axes are:* Synchronous vs asynchronous training: These are two common ways of distributing training with data parallelism. In sync training, all workers train over different slices of input data in sync, and aggregating gradients at each step. In async training, all workers are independently training over the input data and updating variables asynchronously. Typically sync training is supported via all-reduce and async through parameter server architecture.* Hardware platform: Users may want to scale their training onto multiple GPUs on one machine, or multiple machines in a network (with 0 or more GPUs each), or on Cloud TPUs.In order to support these use cases, we have 5 strategies available. In the next section we will talk about which of these are supported in which scenarios in TF 2.0-beta at this time. Here is a quick overview:| Training API | MirroredStrategy | TPUStrategy | MultiWorkerMirroredStrategy | CentralStorageStrategy | ParameterServerStrategy ||:----------------------- |:------------------- |:--------------------- |:--------------------------------- |:--------------------------------- |:-------------------------- || **Keras API** | Supported | Support planned in 2.0 RC | Experimental support | Experimental support | Supported planned post 2.0 || **Custom training loop** | Experimental support | Experimental support | Support planned post 2.0 RC | Support planned in 2.0 RC | No support yet || **Estimator API** | Limited Support | Limited Support | Limited Support | Limited Support | Limited Support | MirroredStrategy`tf.distribute.MirroredStrategy` supports synchronous distributed training on multiple GPUs on one machine. It creates one replica per GPU device. Each variable in the model is mirrored across all the replicas. Together, these variables form a single conceptual variable called `MirroredVariable`. These variables are kept in sync with each other by applying identical updates.Efficient all-reduce algorithms are used to communicate the variable updates across the devices.All-reduce aggregates tensors across all the devices by adding them up, and makes them available on each device.It’s a fused algorithm that is very efficient and can reduce the overhead of synchronization significantly. There are many all-reduce algorithms and implementations available, depending on the type of communication available between devices. By default, it uses NVIDIA NCCL as the all-reduce implementation. The user can also choose between a few other options we provide, or write their own.Here is the simplest way of creating `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
###Output
_____no_output_____
###Markdown
This will create a `MirroredStrategy` instance which will use all the GPUs that are visible to TensorFlow, and use NCCL as the cross device communication.If you wish to use only some of the GPUs on your machine, you can do so like this:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(devices=["/gpu:0", "/gpu:1"])
###Output
_____no_output_____
###Markdown
If you wish to override the cross device communication, you can do so using the `cross_device_ops` argument by supplying an instance of `tf.distribute.CrossDeviceOps`. Currently we provide `tf.distribute.HierarchicalCopyAllReduce` and `tf.distribute.ReductionToOneDevice` as 2 other options other than `tf.distribute.NcclAllReduce` which is the default.
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(
cross_device_ops=tf.distribute.HierarchicalCopyAllReduce())
###Output
_____no_output_____
###Markdown
CentralStorageStrategy`tf.distribute.experimental.CentralStorageStrategy` does synchronous training as well. Variables are not mirrored, instead they are placed on the CPU and operations are replicated across all local GPUs. If there is only one GPU, all variables and operations will be placed on that GPU.Create an instance of `CentralStorageStrategy` by:
###Code
central_storage_strategy = tf.distribute.experimental.CentralStorageStrategy()
###Output
_____no_output_____
###Markdown
This will create a `CentralStorageStrategy` instance which will use all visible GPUs and CPU. Update to variables on replicas will be aggregated before being applied to variables. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. MultiWorkerMirroredStrategy`tf.distribute.experimental.MultiWorkerMirroredStrategy` is very similar to `MirroredStrategy`. It implements synchronous distributed training across multiple workers, each with potentially multiple GPUs. Similar to `MirroredStrategy`, it creates copies of all variables in the model on each device across all workers.It uses [CollectiveOps](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/collective_ops.py) as the multi-worker all-reduce communication method used to keep variables in sync. A collective op is a single op in the TensorFlow graph which can automatically choose an all-reduce algorithm in the TensorFlow runtime according to hardware, network topology and tensor sizes.It also implements additional performance optimizations. For example, it includes a static optimization that converts multiple all-reductions on small tensors into fewer all-reductions on larger tensors. In addition, we are designing it to have a plugin architecture - so that in the future, users will be able to plugin algorithms that are better tuned for their hardware. Note that collective ops also implement other collective operations such as broadcast and all-gather.Here is the simplest way of creating `MultiWorkerMirroredStrategy`:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()
###Output
_____no_output_____
###Markdown
`MultiWorkerMirroredStrategy` currently allows you to choose between two different implementations of collective ops. `CollectiveCommunication.RING` implements ring-based collectives using gRPC as the communication layer. `CollectiveCommunication.NCCL` uses [Nvidia's NCCL](https://developer.nvidia.com/nccl) to implement collectives. `CollectiveCommunication.AUTO` defers the choice to the runtime. The best choice of collective implementation depends upon the number and kind of GPUs, and the network interconnect in the cluster. You can specify them in the following way:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy(
tf.distribute.experimental.CollectiveCommunication.NCCL)
###Output
_____no_output_____
###Markdown
One of the key differences to get multi worker training going, as compared to multi-GPU training, is the multi-worker setup. "TF_CONFIG" environment variable is the standard way in TensorFlow to specify the cluster configuration to each worker that is part of the cluster. See section on ["TF_CONFIG" below](TF_CONFIG) for more details on how this can be done. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. TPUStrategy`tf.distribute.experimental.TPUStrategy` lets users run their TensorFlow training on Tensor Processing Units (TPUs). TPUs are Google's specialized ASICs designed to dramatically accelerate machine learning workloads. They are available on Google Colab, the [TensorFlow Research Cloud](https://www.tensorflow.org/tfrc) and [Google Compute Engine](https://cloud.google.com/tpu).In terms of distributed training architecture, TPUStrategy is the same `MirroredStrategy` - it implements synchronous distributed training. TPUs provide their own implementation of efficient all-reduce and other collective operations across multiple TPU cores, which are used in `TPUStrategy`.Here is how you would instantiate `TPUStrategy`.Note: To run this code in Colab, you should select TPU as the Colab runtime. We will have a tutorial soon that will demonstrate how you can use TPUStrategy.```cluster_resolver = tf.distribute.cluster_resolver.TPUClusterResolver( tpu=tpu_address)tf.config.experimental_connect_to_host(cluster_resolver.master())tf.tpu.experimental.initialize_tpu_system(cluster_resolver)tpu_strategy = tf.distribute.experimental.TPUStrategy(cluster_resolver)``` `TPUClusterResolver` instance helps locate the TPUs. In Colab, you don't need to specify any arguments to it. If you want to use this for Cloud TPUs, you will need to specify the name of your TPU resource in `tpu` argument. We also need to initialize the tpu system explicitly at the start of the program. This is required before TPUs can be used for computation and should ideally be done at the beginning because it also wipes out the TPU memory so all state will be lost. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. ParameterServerStrategy`tf.distribute.experimental.ParameterServerStrategy` supports parameter servers training on multiple machines. In this setup, some machines are designated as workers and some as parameter servers. Each variable of the model is placed on one parameter server. Computation is replicated across all GPUs of all the workers.In terms of code, it looks similar to other strategies:```ps_strategy = tf.distribute.experimental.ParameterServerStrategy()``` For multi worker training, "TF_CONFIG" needs to specify the configuration of parameter servers and workers in your cluster, which you can read more about in ["TF_CONFIG" below](TF_CONFIG) below. So far we've talked about what are the different stategies available and how you can instantiate them. In the next few sections, we will talk about the different ways in which you can use them to distribute your training. We will show short code snippets in this guide and link off to full tutorials which you can run end to end. Using `tf.distribute.Strategy` with KerasWe've integrated `tf.distribute.Strategy` into `tf.keras` which is TensorFlow's implementation of the[Keras API specification](https://keras.io). `tf.keras` is a high-level API to build and train models. By integrating into `tf.keras` backend, we've made it seamless for Keras users to distribute their training written in the Keras training framework. The only things that need to change in a user's program are: (1) Create an instance of the appropriate `tf.distribute.Strategy` and (2) Move the creation and compiling of Keras model inside `strategy.scope`. We support all types of Keras models - sequential, functional and subclassed.Here is a snippet of code to do this for a very simple Keras model with one dense layer:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
model.compile(loss='mse', optimizer='sgd')
###Output
_____no_output_____
###Markdown
In this example we used `MirroredStrategy` so we can run this on a machine with multiple GPUs. `strategy.scope()` indicated which parts of the code to run distributed. Creating a model inside this scope allows us to create mirrored variables instead of regular variables. Compiling under the scope allows us to know that the user intends to train this model using this strategy. Once this is setup, you can fit your model like you would normally. `MirroredStrategy` takes care of replicating the model's training on the available GPUs, aggregating gradients etc.
###Code
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100).batch(10)
model.fit(dataset, epochs=2)
model.evaluate(dataset)
###Output
_____no_output_____
###Markdown
Here we used a `tf.data.Dataset` to provide the training and eval input. You can also use numpy arrays:
###Code
import numpy as np
inputs, targets = np.ones((100, 1)), np.ones((100, 1))
model.fit(inputs, targets, epochs=2, batch_size=10)
###Output
_____no_output_____
###Markdown
In both cases (dataset or numpy), each batch of the given input is divided equally among the multiple replicas. For instance, if using `MirroredStrategy` with 2 GPUs, each batch of size 10 will get divided among the 2 GPUs, with each receiving 5 input examples in each step. Each epoch will then train faster as you add more GPUs. Typically, you would want to increase your batch size as you add more accelerators so as to make effective use of the extra computing power. You will also need to re-tune your learning rate, depending on the model. You can use `strategy.num_replicas_in_sync` to get the number of replicas.
###Code
# Compute global batch size using number of replicas.
BATCH_SIZE_PER_REPLICA = 5
global_batch_size = (BATCH_SIZE_PER_REPLICA *
mirrored_strategy.num_replicas_in_sync)
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100)
dataset = dataset.batch(global_batch_size)
LEARNING_RATES_BY_BATCH_SIZE = {5: 0.1, 10: 0.15}
learning_rate = LEARNING_RATES_BY_BATCH_SIZE[global_batch_size]
###Output
_____no_output_____
###Markdown
What's supported now?In TF 2.0 beta release, we support training with Keras using `MirroredStrategy`, `CentralStorageStrategy` and `MultiWorkerMirroredStrategy`. Both `CentralStorageStrategy` and `MultiWorkerMirroredStrategy` are currently experimental APIs and are subject to change.Support for other strategies will be coming soon. The API and how to use will be exactly the same as above.| Training API | MirroredStrategy | TPUStrategy | MultiWorkerMirroredStrategy | CentralStorageStrategy | ParameterServerStrategy ||---------------- |--------------------- |----------------------- |----------------------------------- |----------------------------------- |--------------------------- || Keras APIs | Supported | Support planned in 2.0 RC | Experimental support | Experimental support | Support planned in post 2.0 | Examples and TutorialsHere is a list of tutorials and examples that illustrate the above integration end to end with Keras:1. Tutorial to train [MNIST](../tutorials/distribute/keras.ipynb) with `MirroredStrategy`.2. Official [ResNet50](https://github.com/tensorflow/models/blob/master/official/resnet/keras/keras_imagenet_main.py) training with ImageNet data using `MirroredStrategy`.3. [ResNet50](https://github.com/tensorflow/tpu/blob/master/models/experimental/resnet50_keras/resnet50.py) trained with Imagenet data on Cloud TPus with `TPUStrategy`. Note that this example only works with TensorFlow 1.x currently.4. [Tutorial](../tutorials/distribute/multi_worker_with_keras.ipynb) to train MNIST using `MultiWorkerMirroredStrategy`.5. [NCF](https://github.com/tensorflow/models/blob/master/official/recommendation/ncf_keras_main.py) trained using `MirroredStrategy`.2. [Transformer]( https://github.com/tensorflow/models/blob/master/official/transformer/v2/transformer_main.py) trained using `MirroredStrategy`. Using `tf.distribute.Strategy` with custom training loopsAs you've seen, using `tf.distribute.Strategy` with high level APIs is only a couple lines of code change. With a little more effort, `tf.distribute.Strategy` can also be used by other users who are not using these frameworks.TensorFlow is used for a wide variety of use cases and some users (such as researchers) require more flexibility and control over their training loops. This makes it hard for them to use the high level frameworks such as Estimator or Keras. For instance, someone using a GAN may want to take a different number of generator or discriminator steps each round. Similarly, the high level frameworks are not very suitable for Reinforcement Learning training. So these users will usually write their own training loops.For these users, we provide a core set of methods through the `tf.distribute.Strategy` classes. Using these may require minor restructuring of the code initially, but once that is done, the user should be able to switch between GPUs / TPUs / multiple machines by just changing the strategy instance.Here we will show a brief snippet illustrating this use case for a simple training example using the same Keras model as before. First, we create the model and optimizer inside the strategy's scope. This ensures that any variables created with the model and optimizer are mirrored variables.
###Code
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
optimizer = tf.keras.optimizers.SGD()
###Output
_____no_output_____
###Markdown
Next, we create the input dataset and call `tf.distribute.Strategy.experimental_distribute_dataset` to distribute the dataset based on the strategy.
###Code
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(1000).batch(
global_batch_size)
dist_dataset = mirrored_strategy.experimental_distribute_dataset(dataset)
###Output
_____no_output_____
###Markdown
Then, we define one step of the training. We will use `tf.GradientTape` to compute gradients and optimizer to apply those gradients to update our model's variables. To distribute this training step, we put in in a function `step_fn` and pass it to `tf.distrbute.Strategy.experimental_run_v2` along with the dataset inputs that we get from `dist_dataset` created before:
###Code
@tf.function
def train_step(dist_inputs):
def step_fn(inputs):
features, labels = inputs
with tf.GradientTape() as tape:
logits = model(features)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(
logits=logits, labels=labels)
loss = tf.reduce_sum(cross_entropy) * (1.0 / global_batch_size)
grads = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(list(zip(grads, model.trainable_variables)))
return cross_entropy
per_example_losses = mirrored_strategy.experimental_run_v2(
step_fn, args=(dist_inputs,))
mean_loss = mirrored_strategy.reduce(
tf.distribute.ReduceOp.MEAN, per_example_losses, axis=0)
return mean_loss
###Output
_____no_output_____
###Markdown
A few other things to note in the code above:1. We used `tf.nn.softmax_cross_entropy_with_logits` to compute the loss. And then we scaled the total loss by the global batch size. This is important because all the replicas are training in sync and number of examples in each step of training is the global batch. So the loss needs to be divided by the global batch size and not by the replica (local) batch size.2. We used the `tf.distribute.Strategy.reduce` API to aggregate the results returned by `tf.distribute.Strategy.experimental_run_v2`. `tf.distribute.Strategy.experimental_run_v2` returns results from each local replica in the strategy, and there are multiple ways to consume this result. You can `reduce` them to get an aggregated value. You can also do `tf.distribute.Strategy.experimental_local_results` to get the list of values contained in the result, one per local replica.3. When `apply_gradients` is called within a distribution strategy scope, its behavior is modified. Specifically, before applying gradients on each parallel instance during synchronous training, it performs a sum-over-all-replicas of the gradients. Finally, once we have defined the training step, we can iterate over `dist_dataset` and run the training in a loop:
###Code
with mirrored_strategy.scope():
for inputs in dist_dataset:
print(train_step(inputs))
###Output
_____no_output_____
###Markdown
In the example above, we iterated over the `dist_dataset` to provide input to your training. We also provide the `tf.distribute.Strategy.make_experimental_numpy_dataset` to support numpy inputs. You can use this API to create a dataset before calling `tf.distribute.Strategy.experimental_distribute_dataset`.Another way of iterating over your data is to explicitly use iterators. You may want to do this when you want to run for a given number of steps as opposed to iterating over the entire dataset.The above iteration would now be modified to first create an iterator and then explicity call `next` on it to get the input data.
###Code
with mirrored_strategy.scope():
iterator = iter(dist_dataset)
for _ in range(10):
print(train_step(next(iterator)))
###Output
_____no_output_____
###Markdown
This covers the simplest case of using `tf.distribute.Strategy` API to distribute custom training loops. We are in the process of improving these APIs. Since this use case requires more work on the part of the user, we will be publishing a separate detailed guide in the future. What's supported now?In TF 2.0 beta release, we support training with custom training loops using `MirroredStrategy` as shown above and `TPUStrategy`. `MultiWorkerMirorredStrategy` support will be coming in the future.| Training API | MirroredStrategy | TPUStrategy | MultiWorkerMirroredStrategy | CentralStorageStrategy | ParameterServerStrategy ||:----------------------- |:------------------- |:------------------- |:----------------------------- |:------------------------ |:------------------------- || Custom Training Loop | Supported | Supported | Support planned in 2.0 RC | Support planned in 2.0 RC | No support yet | Examples and TutorialsHere are some examples for using distribution strategy with custom training loops:1. [Tutorial](../tutorials/distribute/training_loops.ipynb) to train MNIST using `MirroredStrategy`.2. [DenseNet](https://github.com/tensorflow/examples/blob/master/tensorflow_examples/models/densenet/distributed_train.py) example using `MirroredStrategy`.1. [BERT](https://github.com/tensorflow/models/blob/master/official/bert/run_classifier.py) example trained using `MirroredStrategy` and `TPUStrategy`.This example is particularly helpful for understanding how to load from a checkpoint and generate periodic checkpoints during distributed training etc.2. [NCF](https://github.com/tensorflow/models/blob/master/official/recommendation/ncf_keras_main.py) example trained using `MirroredStrategy` that can be enabled using the `keras_use_ctl` flag.3. [NMT](https://github.com/tensorflow/examples/blob/master/tensorflow_examples/models/nmt_with_attention/distributed_train.py) example trained using `MirroredStrategy`. Using `tf.distribute.Strategy` with Estimator`tf.estimator` is a distributed training TensorFlow API that originally supported the async parameter server approach. Like with Keras, we've integrated `tf.distribute.Strategy` into `tf.Estimator` so that a user who is using Estimator for their training can easily change their training is distributed with very few changes to your their code. With this, estimator users can now do synchronous distributed training on multiple GPUs and multiple workers, as well as use TPUs. This support in estimator is, however, limited. See [What's supported now](estimator_support) section below for more details.The usage of `tf.distribute.Strategy` with Estimator is slightly different than the Keras case. Instead of using `strategy.scope`, now we pass the strategy object into the [`RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig) for the Estimator.Here is a snippet of code that shows this with a premade estimator `LinearRegressor` and `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
config = tf.estimator.RunConfig(
train_distribute=mirrored_strategy, eval_distribute=mirrored_strategy)
regressor = tf.estimator.LinearRegressor(
feature_columns=[tf.feature_column.numeric_column('feats')],
optimizer='SGD',
config=config)
###Output
_____no_output_____
###Markdown
We use a premade Estimator here, but the same code works with a custom Estimator as well. `train_distribute` determines how training will be distributed, and `eval_distribute` determines how evaluation will be distributed. This is another difference from Keras where we use the same strategy for both training and eval.Now we can train and evaluate this Estimator with an input function:
###Code
def input_fn():
dataset = tf.data.Dataset.from_tensors(({"feats":[1.]}, [1.]))
return dataset.repeat(1000).batch(10)
regressor.train(input_fn=input_fn, steps=10)
regressor.evaluate(input_fn=input_fn, steps=10)
###Output
_____no_output_____
###Markdown
Copyright 2018 The TensorFlow Authors.
###Code
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###Output
_____no_output_____
###Markdown
Distributed training in TensorFlow View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook Overview`tf.distribute.Strategy` is a TensorFlow API to distribute training across multiple GPUs, multiple machines or TPUs. Using this API, users can distribute their existing models and training code with minimal code changes.`tf.distribute.Strategy` has been designed with these key goals in mind:* Easy to use and support multiple user segments, including researchers, ML engineers, etc.* Provide good performance out of the box.* Easy switching between strategies.`tf.distribute.Strategy` can be used with TensorFlow's high level APIs, [tf.keras](https://www.tensorflow.org/guide/keras) and [tf.estimator](https://www.tensorflow.org/guide/estimators), with just a couple of lines of code change. It also provides an API that can be used to distribute custom training loops (and in general any computation using TensorFlow).In TensorFlow 2.0, users can execute their programs eagerly, or in a graph using [`tf.function`](../tutorials/eager/tf_function.ipynb). `tf.distribute.Strategy` intends to support both these modes of execution. Note that we may talk about training most of the time in this guide, but this API can also be used for distributing evaluation and prediction on different platforms.As you will see in a bit, very few changes are needed to use `tf.distribute.Strategy` with your code. This is because we have changed the underlying components of TensorFlow to become strategy-aware. This includes variables, layers, models, optimizers, metrics, summaries, and checkpoints.In this guide, we will talk about various types of strategies and how one can use them in a different situations.
###Code
# Import TensorFlow
from __future__ import absolute_import, division, print_function, unicode_literals
!pip install tensorflow-gpu==2.0.0-beta0
import tensorflow as tf
###Output
_____no_output_____
###Markdown
Types of strategies`tf.distribute.Strategy` intends to cover a number of use cases along different axes. Some of these combinations are currently supported and others will be added in the future. Some of these axes are:* Synchronous vs asynchronous training: These are two common ways of distributing training with data parallelism. In sync training, all workers train over different slices of input data in sync, and aggregating gradients at each step. In async training, all workers are independently training over the input data and updating variables asynchronously. Typically sync training is supported via all-reduce and async through parameter server architecture.* Hardware platform: Users may want to scale their training onto multiple GPUs on one machine, or multiple machines in a network (with 0 or more GPUs each), or on Cloud TPUs.In order to support these use cases, we have 5 strategies available. In the next section we will talk about which of these are supported in which scenarios in TF 2.0-beta at this time. Here is a quick overview:| Training API | MirroredStrategy | TPUStrategy | MultiWorkerMirroredStrategy | CentralStorageStrategy | ParameterServerStrategy ||:----------------------- |:------------------- |:--------------------- |:--------------------------------- |:--------------------------------- |:-------------------------- || **Keras API** | Supported | Support planned in 2.0 RC | Experimental support | Experimental support | Supported planned in post 2.0 || **Custom training loop** | Experimental support | Experimental support | Support planned in 2.0 RC | Support planned in 2.0 RC | No support yet || **Estimator API** | Supported | Supported | Supported | Supported | Supported | MirroredStrategy`tf.distribute.MirroredStrategy` supports synchronous distributed training on multiple GPUs on one machine. It creates one replica per GPU device. Each variable in the model is mirrored across all the replicas. Together, these variables form a single conceptual variable called `MirroredVariable`. These variables are kept in sync with each other by applying identical updates.Efficient all-reduce algorithms are used to communicate the variable updates across the devices.All-reduce aggregates tensors across all the devices by adding them up, and makes them available on each device.It’s a fused algorithm that is very efficient and can reduce the overhead of synchronization significantly. There are many all-reduce algorithms and implementations available, depending on the type of communication available between devices. By default, it uses NVIDIA NCCL as the all-reduce implementation. The user can also choose between a few other options we provide, or write their own.Here is the simplest way of creating `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
###Output
_____no_output_____
###Markdown
This will create a `MirroredStrategy` instance which will use all the GPUs that are visible to TensorFlow, and use NCCL as the cross device communication.If you wish to use only some of the GPUs on your machine, you can do so like this:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(devices=["/gpu:0", "/gpu:1"])
###Output
_____no_output_____
###Markdown
If you wish to override the cross device communication, you can do so using the `cross_device_ops` argument by supplying an instance of `tf.distribute.CrossDeviceOps`. Currently we provide `tf.distribute.HierarchicalCopyAllReduce` and `tf.distribute.ReductionToOneDevice` as 2 other options other than `tf.distribute.NcclAllReduce` which is the default.
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(
cross_device_ops=tf.distribute.HierarchicalCopyAllReduce())
###Output
_____no_output_____
###Markdown
CentralStorageStrategy`tf.distribute.experimental.CentralStorageStrategy` does synchronous training as well. Variables are not mirrored, instead they are placed on the CPU and operations are replicated across all local GPUs. If there is only one GPU, all variables and operations will be placed on that GPU.Create an instance of `CentralStorageStrategy` by:
###Code
central_storage_strategy = tf.distribute.experimental.CentralStorageStrategy()
###Output
_____no_output_____
###Markdown
This will create a `CentralStorageStrategy` instance which will use all visible GPUs and CPU. Update to variables on replicas will be aggregated before being applied to variables. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. MultiWorkerMirroredStrategy`tf.distribute.experimental.MultiWorkerMirroredStrategy` is very similar to `MirroredStrategy`. It implements synchronous distributed training across multiple workers, each with potentially multiple GPUs. Similar to `MirroredStrategy`, it creates copies of all variables in the model on each device across all workers.It uses [CollectiveOps](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/collective_ops.py) as the multi-worker all-reduce communication method used to keep variables in sync. A collective op is a single op in the TensorFlow graph which can automatically choose an all-reduce algorithm in the TensorFlow runtime according to hardware, network topology and tensor sizes.It also implements additional performance optimizations. For example, it includes a static optimization that converts multiple all-reductions on small tensors into fewer all-reductions on larger tensors. In addition, we are designing it to have a plugin architecture - so that in the future, users will be able to plugin algorithms that are better tuned for their hardware. Note that collective ops also implement other collective operations such as broadcast and all-gather.Here is the simplest way of creating `MultiWorkerMirroredStrategy`:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()
###Output
_____no_output_____
###Markdown
`MultiWorkerMirroredStrategy` currently allows you to choose between two different implementations of collective ops. `CollectiveCommunication.RING` implements ring-based collectives using gRPC as the communication layer. `CollectiveCommunication.NCCL` uses [Nvidia's NCCL](https://developer.nvidia.com/nccl) to implement collectives. `CollectiveCommunication.AUTO` defers the choice to the runtime. The best choice of collective implementation depends upon the number and kind of GPUs, and the network interconnect in the cluster. You can specify them in the following way:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy(
tf.distribute.experimental.CollectiveCommunication.NCCL)
###Output
_____no_output_____
###Markdown
One of the key differences to get multi worker training going, as compared to multi-GPU training, is the multi-worker setup. "TF_CONFIG" environment variable is the standard way in TensorFlow to specify the cluster configuration to each worker that is part of the cluster. See section on ["TF_CONFIG" below](TF_CONFIG) for more details on how this can be done. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. TPUStrategy`tf.distribute.experimental.TPUStrategy` lets users run their TensorFlow training on Tensor Processing Units (TPUs). TPUs are Google's specialized ASICs designed to dramatically accelerate machine learning workloads. They are available on Google Colab, the [TensorFlow Research Cloud](https://www.tensorflow.org/tfrc) and [Google Compute Engine](https://cloud.google.com/tpu).In terms of distributed training architecture, TPUStrategy is the same `MirroredStrategy` - it implements synchronous distributed training. TPUs provide their own implementation of efficient all-reduce and other collective operations across multiple TPU cores, which are used in `TPUStrategy`.Here is how you would instantiate `TPUStrategy`.Note: To run this code in Colab, you should select TPU as the Colab runtime. We will have a tutorial soon that will demonstrate how you can use TPUStrategy.```cluster_resolver = tf.distribute.cluster_resolver.TPUClusterResolver( tpu=tpu_address)tf.config.experimental_connect_to_host(cluster_resolver.master())tf.tpu.experimental.initialize_tpu_system(cluster_resolver)tpu_strategy = tf.distribute.experimental.TPUStrategy(cluster_resolver)``` `TPUClusterResolver` instance helps locate the TPUs. In Colab, you don't need to specify any arguments to it. If you want to use this for Cloud TPUs, you will need to specify the name of your TPU resource in `tpu` argument. We also need to initialize the tpu system explicitly at the start of the program. This is required before TPUs can be used for computation and should ideally be done at the beginning because it also wipes out the TPU memory so all state will be lost. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. ParameterServerStrategy`tf.distribute.experimental.ParameterServerStrategy` supports parameter servers training on multiple machines. In this setup, some machines are designated as workers and some as parameter servers. Each variable of the model is placed on one parameter server. Computation is replicated across all GPUs of the all the workers.In terms of code, it looks similar to other strategies:```ps_strategy = tf.distribute.experimental.ParameterServerStrategy()``` For multi worker training, "TF_CONFIG" needs to specify the configuration of parameter servers and workers in your cluster, which you can read more about in ["TF_CONFIG" below](TF_CONFIG) below. So far we've talked about what are the different stategies available and how you can instantiate them. In the next few sections, we will talk about the different ways in which you can use them to distribute your training. We will show short code snippets in this guide and link off to full tutorials which you can run end to end. Using `tf.distribute.Strategy` with KerasWe've integrated `tf.distribute.Strategy` into `tf.keras` which is TensorFlow's implementation of the[Keras API specification](https://keras.io). `tf.keras` is a high-level API to build and train models. By integrating into `tf.keras` backend, we've made it seamless for Keras users to distribute their training written in the Keras training framework. The only things that need to change in a user's program are: (1) Create an instance of the appropriate `tf.distribute.Strategy` and (2) Move the creation and compiling of Keras model inside `strategy.scope`. We support all types of Keras models - sequential, functional and subclassed.Here is a snippet of code to do this for a very simple Keras model with one dense layer:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
model.compile(loss='mse', optimizer='sgd')
###Output
_____no_output_____
###Markdown
In this example we used `MirroredStrategy` so we can run this on a machine with multiple GPUs. `strategy.scope()` indicated which parts of the code to run distributed. Creating a model inside this scope allows us to create mirrored variables instead of regular variables. Compiling under the scope allows us to know that the user intends to train this model using this strategy. Once this is setup, you can fit your model like you would normally. `MirroredStrategy` takes care of replicating the model's training on the available GPUs, aggregating gradients etc.
###Code
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100).batch(10)
model.fit(dataset, epochs=2)
model.evaluate(dataset)
###Output
_____no_output_____
###Markdown
Here we used a `tf.data.Dataset` to provide the training and eval input. You can also use numpy arrays:
###Code
import numpy as np
inputs, targets = np.ones((100, 1)), np.ones((100, 1))
model.fit(inputs, targets, epochs=2, batch_size=10)
###Output
_____no_output_____
###Markdown
In both cases (dataset or numpy), each batch of the given input is divided equally among the multiple replicas. For instance, if using `MirroredStrategy` with 2 GPUs, each batch of size 10 will get divided among the 2 GPUs, with each receiving 5 input examples in each step. Each epoch will then train faster as you add more GPUs. Typically, you would want to increase your batch size as you add more accelerators so as to make effective use of the extra computing power. You will also need to re-tune your learning rate, depending on the model. You can use `strategy.num_replicas_in_sync` to get the number of replicas.
###Code
# Compute global batch size using number of replicas.
BATCH_SIZE_PER_REPLICA = 5
global_batch_size = (BATCH_SIZE_PER_REPLICA *
mirrored_strategy.num_replicas_in_sync)
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100)
dataset = dataset.batch(global_batch_size)
LEARNING_RATES_BY_BATCH_SIZE = {5: 0.1, 10: 0.15}
learning_rate = LEARNING_RATES_BY_BATCH_SIZE[global_batch_size]
###Output
_____no_output_____
###Markdown
What's supported now?In TF 2.0 beta release, we support training with Keras using `MirroredStrategy`, `CentralStorageStrategy` and `MultiWorkerMirroredStrategy`. Both `CentralStorageStrategy` and `MultiWorkerMirroredStrategy` are currently experimental APIs and are subject to change.Support for other strategies will be coming soon. The API and how to use will be exactly the same as above.| Training API | MirroredStrategy | TPUStrategy | MultiWorkerMirroredStrategy | CentralStorageStrategy | ParameterServerStrategy ||---------------- |--------------------- |----------------------- |----------------------------------- |----------------------------------- |--------------------------- || Keras APIs | Supported | Support planned in 2.0 RC | Experimental support | Experimental support | Support planned in post 2.0 | Examples and TutorialsHere is a list of tutorials and examples that illustrate the above integration end to end with Keras:1. Tutorial to train [MNIST](../tutorials/distribute/keras.ipynb) with `MirroredStrategy`.2. Official [ResNet50](https://github.com/tensorflow/models/blob/master/official/resnet/keras/keras_imagenet_main.py) training with ImageNet data using `MirroredStrategy`.3. [ResNet50](https://github.com/tensorflow/tpu/blob/master/models/experimental/resnet50_keras/resnet50.py) trained with Imagenet data on Cloud TPus with `TPUStrategy`. Note that this example only works with TensorFlow 1.x currently.4. [Tutorial](../tutorials/distribute/multi_worker_with_keras.ipynb) to train MNIST using `MultiWorkerMirroredStrategy`.5. [NCF](https://github.com/tensorflow/models/blob/master/official/recommendation/ncf_keras_main.py) trained using `MirroredStrategy`.2. [Transformer]( https://github.com/tensorflow/models/blob/master/official/transformer/v2/transformer_main.py) trained using `MirroredStrategy`. Using `tf.distribute.Strategy` with Estimator`tf.estimator` is a distributed training TensorFlow API that originally supported the async parameter server approach. Like with Keras, we've integrated `tf.distribute.Strategy` into `tf.Estimator` so that a user who is using Estimator for their training can easily change their training is distributed with very few changes to your their code. With this, estimator users can now do synchronous distributed training on multiple GPUs and multiple workers, as well as use TPUs.The usage of `tf.distribute.Strategy` with Estimator is slightly different than the Keras case. Instead of using `strategy.scope`, now we pass the strategy object into the [`RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig) for the Estimator.Here is a snippet of code that shows this with a premade estimator `LinearRegressor` and `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
config = tf.estimator.RunConfig(
train_distribute=mirrored_strategy, eval_distribute=mirrored_strategy)
regressor = tf.estimator.LinearRegressor(
feature_columns=[tf.feature_column.numeric_column('feats')],
optimizer='SGD',
config=config)
###Output
_____no_output_____
###Markdown
We use a premade Estimator here, but the same code works with a custom Estimator as well. `train_distribute` determines how training will be distributed, and `eval_distribute` determines how evaluation will be distributed. This is another difference from Keras where we use the same strategy for both training and eval.Now we can train and evaluate this Estimator with an input function:
###Code
def input_fn():
dataset = tf.data.Dataset.from_tensors(({"feats":[1.]}, [1.]))
return dataset.repeat(1000).batch(10)
regressor.train(input_fn=input_fn, steps=10)
regressor.evaluate(input_fn=input_fn, steps=10)
###Output
_____no_output_____
###Markdown
Another difference to highlight here between Estimator and Keras is the input handling. In Keras, we mentioned that each batch of the dataset is split across the multiple replicas. In Estimator, however, the user provides an `input_fn` and have full control over how they want their data to be distributed across workers and devices. We do not do automatic splitting of batch, nor automatically shard the data across different workers. The provided `input_fn` is called once per worker, thus giving one dataset per worker. Then one batch from that dataset is fed to one replica on that worker, thereby consuming N batches for N replicas on 1 worker. In other words, the dataset returned by the `input_fn` should provide batches of size `PER_REPLICA_BATCH_SIZE`. And the global batch size for a step can be obtained as `PER_REPLICA_BATCH_SIZE * strategy.num_replicas_in_sync`. When doing multi worker training, users will also want to either split their data across the workers, or shuffle with a random seed on each. You can see an example of how to do this in the [Multi-worker Training with Estimator](../tutorials/distribute/multi_worker_with_estimator.ipynb). We showed an example of using `MirroredStrategy` with Estimator. You can also use `TPUStrategy` with Estimator as well, in the exact same way:```config = tf.estimator.RunConfig( train_distribute=tpu_strategy, eval_distribute=tpu_strategy)``` And similarly, you can use multi worker and parameter server strategies as well. The code remains the same, but you need to use `tf.estimator.train_and_evaluate`, and set "TF_CONFIG" environment variables for each binary running in your cluster. What's supported now?In TF 2.0 beta release, we support training with Estimator using all strategies.| Training API | MirroredStrategy | TPUStrategy | MultiWorkerMirroredStrategy | CentralStorageStrategy | ParameterServerStrategy ||:--------------- |:------------------ |:------------- |:----------------------------- |:------------------------ |:------------------------- || Estimator API | Supported | Supported | Supported | Supported | Supported | Examples and TutorialsHere are some examples that show end to end usage of various strategies with Estimator:1. [Multi-worker Training with Estimator](../tutorials/distribute/multi_worker_with_estimator.ipynb) to train MNIST with multiple workers using `MultiWorkerMirroredStrategy`.2. [End to end example](https://github.com/tensorflow/ecosystem/tree/master/distribution_strategy) for multi worker training in tensorflow/ecosystem using Kuberentes templates. This example starts with a Keras model and converts it to an Estimator using the `tf.keras.estimator.model_to_estimator` API.3. Official [ResNet50](https://github.com/tensorflow/models/blob/master/official/resnet/imagenet_main.py) model, which can be trained using either `MirroredStrategy` or `MultiWorkerMirroredStrategy`.4. [ResNet50](https://github.com/tensorflow/tpu/blob/master/models/experimental/distribution_strategy/resnet_estimator.py) example with TPUStrategy. Using `tf.distribute.Strategy` with custom training loopsAs you've seen, using `tf.distribute.Strategy` with high level APIs is only a couple lines of code change. With a little more effort, `tf.distribute.Strategy` can also be used by other users who are not using these frameworks.TensorFlow is used for a wide variety of use cases and some users (such as researchers) require more flexibility and control over their training loops. This makes it hard for them to use the high level frameworks such as Estimator or Keras. For instance, someone using a GAN may want to take a different number of generator or discriminator steps each round. Similarly, the high level frameworks are not very suitable for Reinforcement Learning training. So these users will usually write their own training loops.For these users, we provide a core set of methods through the `tf.distribute.Strategy` classes. Using these may require minor restructuring of the code initially, but once that is done, the user should be able to switch between GPUs / TPUs / multiple machines by just changing the strategy instance.Here we will show a brief snippet illustrating this use case for a simple training example using the same Keras model as before. First, we create the model and optimizer inside the strategy's scope. This ensures that any variables created with the model and optimizer are mirrored variables.
###Code
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
optimizer = tf.keras.optimizers.SGD()
###Output
_____no_output_____
###Markdown
Next, we create the input dataset and call `tf.distribute.Strategy.experimental_distribute_dataset` to distribute the dataset based on the strategy.
###Code
with mirrored_strategy.scope():
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(1000).batch(
global_batch_size)
dist_dataset = mirrored_strategy.experimental_distribute_dataset(dataset)
###Output
_____no_output_____
###Markdown
Then, we define one step of the training. We will use `tf.GradientTape` to compute gradients and optimizer to apply those gradients to update our model's variables. To distribute this training step, we put in in a function `step_fn` and pass it to `tf.distrbute.Strategy.experimental_run_v2` along with the dataset inputs that we get from `dist_dataset` created before:
###Code
@tf.function
def train_step(dist_inputs):
def step_fn(inputs):
features, labels = inputs
with tf.GradientTape() as tape:
logits = model(features)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(
logits=logits, labels=labels)
loss = tf.reduce_sum(cross_entropy) * (1.0 / global_batch_size)
grads = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(list(zip(grads, model.trainable_variables)))
return cross_entropy
per_example_losses = mirrored_strategy.experimental_run_v2(
step_fn, args=(dist_inputs,))
mean_loss = mirrored_strategy.reduce(
tf.distribute.ReduceOp.MEAN, per_example_losses, axis=0)
return mean_loss
###Output
_____no_output_____
###Markdown
A few other things to note in the code above:1. We used `tf.nn.softmax_cross_entropy_with_logits` to compute the loss. And then we scaled the total loss by the global batch size. This is important because all the replicas are training in sync and number of examples in each step of training is the global batch. So the loss needs to be divided by the global batch size and not by the replica (local) batch size.2. We used the `tf.distribute.Strategy.reduce` API to aggregate the results returned by `tf.distribute.Strategy.experimental_run_v2`. `tf.distribute.Strategy.experimental_run_v2` returns results from each local replica in the strategy, and there are multiple ways to consume this result. You can `reduce` them to get an aggregated value. You can also do `tf.distribute.Strategy.experimental_local_results` to get the list of values contained in the result, one per local replica.3. When `apply_gradients` is called within a distribution strategy scope, its behavior is modified. Specifically, before applying gradients on each parallel instance during synchronous training, it performs a sum-over-all-replicas of the gradients. Finally, once we have defined the training step, we can iterate over `dist_dataset` and run the training in a loop:
###Code
with mirrored_strategy.scope():
for inputs in dist_dataset:
print(train_step(inputs))
###Output
_____no_output_____
###Markdown
In the example above, we iterated over the `dist_dataset` to provide input to your training. We also provide the `tf.distribute.Strategy.make_experimental_numpy_dataset` to support numpy inputs. You can use this API to create a dataset before calling `tf.distribute.Strategy.experimental_distribute_dataset`.Another way of iterating over your data is to explicitly use iterators. You may want to do this when you want to run for a given number of steps as opposed to iterating over the entire dataset.The above iteration would now be modified to first create an iterator and then explicity call `next` on it to get the input data.
###Code
with mirrored_strategy.scope():
iterator = iter(dist_dataset)
for _ in range(10):
print(train_step(next(iterator)))
###Output
_____no_output_____
###Markdown
Copyright 2018 The TensorFlow Authors.
###Code
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###Output
_____no_output_____
###Markdown
Distributed training in TensorFlow View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook Overview`tf.distribute.Strategy` is a TensorFlow API to distribute training across multiple GPUs, multiple machines or TPUs. Using this API, users can distribute their existing models and training code with minimal code changes.`tf.distribute.Strategy` has been designed with these key goals in mind:* Easy to use and support multiple user segments, including researchers, ML engineers, etc.* Provide good performance out of the box.* Easy switching between strategies.`tf.distribute.Strategy` can be used with TensorFlow's high level APIs, [tf.keras](https://www.tensorflow.org/guide/keras) and [tf.estimator](https://www.tensorflow.org/guide/estimators), with just a couple of lines of code change. It also provides an API that can be used to distribute custom training loops (and in general any computation using TensorFlow).In TensorFlow 2.0, users can execute their programs eagerly, or in a graph using [`tf.function`](../tutorials/eager/tf_function.ipynb). `tf.distribute.Strategy` intends to support both these modes of execution. Note that we may talk about training most of the time in this guide, but this API can also be used for distributing evaluation and prediction on different platforms.As you will see in a bit, very few changes are needed to use `tf.distribute.Strategy` with your code. This is because we have changed the underlying components of TensorFlow to become strategy-aware. This includes variables, layers, models, optimizers, metrics, summaries, and checkpoints.In this guide, we will talk about various types of strategies and how one can use them in a different situations.
###Code
# Import TensorFlow
from __future__ import absolute_import, division, print_function, unicode_literals
try:
%tensorflow_version 2.x # Colab only.
except Exception:
pass
import tensorflow as tf
###Output
_____no_output_____
###Markdown
Types of strategies`tf.distribute.Strategy` intends to cover a number of use cases along different axes. Some of these combinations are currently supported and others will be added in the future. Some of these axes are:* Synchronous vs asynchronous training: These are two common ways of distributing training with data parallelism. In sync training, all workers train over different slices of input data in sync, and aggregating gradients at each step. In async training, all workers are independently training over the input data and updating variables asynchronously. Typically sync training is supported via all-reduce and async through parameter server architecture.* Hardware platform: Users may want to scale their training onto multiple GPUs on one machine, or multiple machines in a network (with 0 or more GPUs each), or on Cloud TPUs.In order to support these use cases, we have 5 strategies available. In the next section we will talk about which of these are supported in which scenarios in TF 2.0-beta at this time. Here is a quick overview:| Training API | MirroredStrategy | TPUStrategy | MultiWorkerMirroredStrategy | CentralStorageStrategy | ParameterServerStrategy ||:----------------------- |:------------------- |:--------------------- |:--------------------------------- |:--------------------------------- |:-------------------------- || **Keras API** | Supported | Support planned in 2.0 RC | Experimental support | Experimental support | Supported planned post 2.0 || **Custom training loop** | Experimental support | Experimental support | Support planned post 2.0 RC | Support planned in 2.0 RC | No support yet || **Estimator API** | Limited Support | Limited Support | Limited Support | Limited Support | Limited Support | MirroredStrategy`tf.distribute.MirroredStrategy` supports synchronous distributed training on multiple GPUs on one machine. It creates one replica per GPU device. Each variable in the model is mirrored across all the replicas. Together, these variables form a single conceptual variable called `MirroredVariable`. These variables are kept in sync with each other by applying identical updates.Efficient all-reduce algorithms are used to communicate the variable updates across the devices.All-reduce aggregates tensors across all the devices by adding them up, and makes them available on each device.It’s a fused algorithm that is very efficient and can reduce the overhead of synchronization significantly. There are many all-reduce algorithms and implementations available, depending on the type of communication available between devices. By default, it uses NVIDIA NCCL as the all-reduce implementation. The user can also choose between a few other options we provide, or write their own.Here is the simplest way of creating `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
###Output
_____no_output_____
###Markdown
This will create a `MirroredStrategy` instance which will use all the GPUs that are visible to TensorFlow, and use NCCL as the cross device communication.If you wish to use only some of the GPUs on your machine, you can do so like this:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(devices=["/gpu:0", "/gpu:1"])
###Output
_____no_output_____
###Markdown
If you wish to override the cross device communication, you can do so using the `cross_device_ops` argument by supplying an instance of `tf.distribute.CrossDeviceOps`. Currently we provide `tf.distribute.HierarchicalCopyAllReduce` and `tf.distribute.ReductionToOneDevice` as 2 other options other than `tf.distribute.NcclAllReduce` which is the default.
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(
cross_device_ops=tf.distribute.HierarchicalCopyAllReduce())
###Output
_____no_output_____
###Markdown
CentralStorageStrategy`tf.distribute.experimental.CentralStorageStrategy` does synchronous training as well. Variables are not mirrored, instead they are placed on the CPU and operations are replicated across all local GPUs. If there is only one GPU, all variables and operations will be placed on that GPU.Create an instance of `CentralStorageStrategy` by:
###Code
central_storage_strategy = tf.distribute.experimental.CentralStorageStrategy()
###Output
_____no_output_____
###Markdown
This will create a `CentralStorageStrategy` instance which will use all visible GPUs and CPU. Update to variables on replicas will be aggregated before being applied to variables. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. MultiWorkerMirroredStrategy`tf.distribute.experimental.MultiWorkerMirroredStrategy` is very similar to `MirroredStrategy`. It implements synchronous distributed training across multiple workers, each with potentially multiple GPUs. Similar to `MirroredStrategy`, it creates copies of all variables in the model on each device across all workers.It uses [CollectiveOps](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/collective_ops.py) as the multi-worker all-reduce communication method used to keep variables in sync. A collective op is a single op in the TensorFlow graph which can automatically choose an all-reduce algorithm in the TensorFlow runtime according to hardware, network topology and tensor sizes.It also implements additional performance optimizations. For example, it includes a static optimization that converts multiple all-reductions on small tensors into fewer all-reductions on larger tensors. In addition, we are designing it to have a plugin architecture - so that in the future, users will be able to plugin algorithms that are better tuned for their hardware. Note that collective ops also implement other collective operations such as broadcast and all-gather.Here is the simplest way of creating `MultiWorkerMirroredStrategy`:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()
###Output
_____no_output_____
###Markdown
`MultiWorkerMirroredStrategy` currently allows you to choose between two different implementations of collective ops. `CollectiveCommunication.RING` implements ring-based collectives using gRPC as the communication layer. `CollectiveCommunication.NCCL` uses [Nvidia's NCCL](https://developer.nvidia.com/nccl) to implement collectives. `CollectiveCommunication.AUTO` defers the choice to the runtime. The best choice of collective implementation depends upon the number and kind of GPUs, and the network interconnect in the cluster. You can specify them in the following way:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy(
tf.distribute.experimental.CollectiveCommunication.NCCL)
###Output
_____no_output_____
###Markdown
One of the key differences to get multi worker training going, as compared to multi-GPU training, is the multi-worker setup. "TF_CONFIG" environment variable is the standard way in TensorFlow to specify the cluster configuration to each worker that is part of the cluster. See section on ["TF_CONFIG" below](TF_CONFIG) for more details on how this can be done. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. TPUStrategy`tf.distribute.experimental.TPUStrategy` lets users run their TensorFlow training on Tensor Processing Units (TPUs). TPUs are Google's specialized ASICs designed to dramatically accelerate machine learning workloads. They are available on Google Colab, the [TensorFlow Research Cloud](https://www.tensorflow.org/tfrc) and [Google Compute Engine](https://cloud.google.com/tpu).In terms of distributed training architecture, TPUStrategy is the same `MirroredStrategy` - it implements synchronous distributed training. TPUs provide their own implementation of efficient all-reduce and other collective operations across multiple TPU cores, which are used in `TPUStrategy`.Here is how you would instantiate `TPUStrategy`.Note: To run this code in Colab, you should select TPU as the Colab runtime. We will have a tutorial soon that will demonstrate how you can use TPUStrategy.```cluster_resolver = tf.distribute.cluster_resolver.TPUClusterResolver( tpu=tpu_address)tf.config.experimental_connect_to_host(cluster_resolver.master())tf.tpu.experimental.initialize_tpu_system(cluster_resolver)tpu_strategy = tf.distribute.experimental.TPUStrategy(cluster_resolver)``` `TPUClusterResolver` instance helps locate the TPUs. In Colab, you don't need to specify any arguments to it. If you want to use this for Cloud TPUs, you will need to specify the name of your TPU resource in `tpu` argument. We also need to initialize the tpu system explicitly at the start of the program. This is required before TPUs can be used for computation and should ideally be done at the beginning because it also wipes out the TPU memory so all state will be lost. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. ParameterServerStrategy`tf.distribute.experimental.ParameterServerStrategy` supports parameter servers training on multiple machines. In this setup, some machines are designated as workers and some as parameter servers. Each variable of the model is placed on one parameter server. Computation is replicated across all GPUs of all the workers.In terms of code, it looks similar to other strategies:```ps_strategy = tf.distribute.experimental.ParameterServerStrategy()``` For multi worker training, "TF_CONFIG" needs to specify the configuration of parameter servers and workers in your cluster, which you can read more about in ["TF_CONFIG" below](TF_CONFIG) below. So far we've talked about what are the different stategies available and how you can instantiate them. In the next few sections, we will talk about the different ways in which you can use them to distribute your training. We will show short code snippets in this guide and link off to full tutorials which you can run end to end. Using `tf.distribute.Strategy` with KerasWe've integrated `tf.distribute.Strategy` into `tf.keras` which is TensorFlow's implementation of the[Keras API specification](https://keras.io). `tf.keras` is a high-level API to build and train models. By integrating into `tf.keras` backend, we've made it seamless for Keras users to distribute their training written in the Keras training framework. The only things that need to change in a user's program are: (1) Create an instance of the appropriate `tf.distribute.Strategy` and (2) Move the creation and compiling of Keras model inside `strategy.scope`. We support all types of Keras models - sequential, functional and subclassed.Here is a snippet of code to do this for a very simple Keras model with one dense layer:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
model.compile(loss='mse', optimizer='sgd')
###Output
_____no_output_____
###Markdown
In this example we used `MirroredStrategy` so we can run this on a machine with multiple GPUs. `strategy.scope()` indicated which parts of the code to run distributed. Creating a model inside this scope allows us to create mirrored variables instead of regular variables. Compiling under the scope allows us to know that the user intends to train this model using this strategy. Once this is setup, you can fit your model like you would normally. `MirroredStrategy` takes care of replicating the model's training on the available GPUs, aggregating gradients etc.
###Code
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100).batch(10)
model.fit(dataset, epochs=2)
model.evaluate(dataset)
###Output
_____no_output_____
###Markdown
Here we used a `tf.data.Dataset` to provide the training and eval input. You can also use numpy arrays:
###Code
import numpy as np
inputs, targets = np.ones((100, 1)), np.ones((100, 1))
model.fit(inputs, targets, epochs=2, batch_size=10)
###Output
_____no_output_____
###Markdown
In both cases (dataset or numpy), each batch of the given input is divided equally among the multiple replicas. For instance, if using `MirroredStrategy` with 2 GPUs, each batch of size 10 will get divided among the 2 GPUs, with each receiving 5 input examples in each step. Each epoch will then train faster as you add more GPUs. Typically, you would want to increase your batch size as you add more accelerators so as to make effective use of the extra computing power. You will also need to re-tune your learning rate, depending on the model. You can use `strategy.num_replicas_in_sync` to get the number of replicas.
###Code
# Compute global batch size using number of replicas.
BATCH_SIZE_PER_REPLICA = 5
global_batch_size = (BATCH_SIZE_PER_REPLICA *
mirrored_strategy.num_replicas_in_sync)
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100)
dataset = dataset.batch(global_batch_size)
LEARNING_RATES_BY_BATCH_SIZE = {5: 0.1, 10: 0.15}
learning_rate = LEARNING_RATES_BY_BATCH_SIZE[global_batch_size]
###Output
_____no_output_____
###Markdown
What's supported now?In TF 2.0 beta release, we support training with Keras using `MirroredStrategy`, `CentralStorageStrategy` and `MultiWorkerMirroredStrategy`. Both `CentralStorageStrategy` and `MultiWorkerMirroredStrategy` are currently experimental APIs and are subject to change.Support for other strategies will be coming soon. The API and how to use will be exactly the same as above.| Training API | MirroredStrategy | TPUStrategy | MultiWorkerMirroredStrategy | CentralStorageStrategy | ParameterServerStrategy ||---------------- |--------------------- |----------------------- |----------------------------------- |----------------------------------- |--------------------------- || Keras APIs | Supported | Support planned in 2.0 RC | Experimental support | Experimental support | Support planned in post 2.0 | Examples and TutorialsHere is a list of tutorials and examples that illustrate the above integration end to end with Keras:1. Tutorial to train [MNIST](../tutorials/distribute/keras.ipynb) with `MirroredStrategy`.2. Official [ResNet50](https://github.com/tensorflow/models/blob/master/official/resnet/keras/keras_imagenet_main.py) training with ImageNet data using `MirroredStrategy`.3. [ResNet50](https://github.com/tensorflow/tpu/blob/master/models/experimental/resnet50_keras/resnet50.py) trained with Imagenet data on Cloud TPus with `TPUStrategy`. Note that this example only works with TensorFlow 1.x currently.4. [Tutorial](../tutorials/distribute/multi_worker_with_keras.ipynb) to train MNIST using `MultiWorkerMirroredStrategy`.5. [NCF](https://github.com/tensorflow/models/blob/master/official/recommendation/ncf_keras_main.py) trained using `MirroredStrategy`.2. [Transformer]( https://github.com/tensorflow/models/blob/master/official/transformer/v2/transformer_main.py) trained using `MirroredStrategy`. Using `tf.distribute.Strategy` with custom training loopsAs you've seen, using `tf.distribute.Strategy` with high level APIs is only a couple lines of code change. With a little more effort, `tf.distribute.Strategy` can also be used by other users who are not using these frameworks.TensorFlow is used for a wide variety of use cases and some users (such as researchers) require more flexibility and control over their training loops. This makes it hard for them to use the high level frameworks such as Estimator or Keras. For instance, someone using a GAN may want to take a different number of generator or discriminator steps each round. Similarly, the high level frameworks are not very suitable for Reinforcement Learning training. So these users will usually write their own training loops.For these users, we provide a core set of methods through the `tf.distribute.Strategy` classes. Using these may require minor restructuring of the code initially, but once that is done, the user should be able to switch between GPUs / TPUs / multiple machines by just changing the strategy instance.Here we will show a brief snippet illustrating this use case for a simple training example using the same Keras model as before. First, we create the model and optimizer inside the strategy's scope. This ensures that any variables created with the model and optimizer are mirrored variables.
###Code
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
optimizer = tf.keras.optimizers.SGD()
###Output
_____no_output_____
###Markdown
Next, we create the input dataset and call `tf.distribute.Strategy.experimental_distribute_dataset` to distribute the dataset based on the strategy.
###Code
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(1000).batch(
global_batch_size)
dist_dataset = mirrored_strategy.experimental_distribute_dataset(dataset)
###Output
_____no_output_____
###Markdown
Then, we define one step of the training. We will use `tf.GradientTape` to compute gradients and optimizer to apply those gradients to update our model's variables. To distribute this training step, we put in in a function `step_fn` and pass it to `tf.distrbute.Strategy.experimental_run_v2` along with the dataset inputs that we get from `dist_dataset` created before:
###Code
@tf.function
def train_step(dist_inputs):
def step_fn(inputs):
features, labels = inputs
with tf.GradientTape() as tape:
logits = model(features)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(
logits=logits, labels=labels)
loss = tf.reduce_sum(cross_entropy) * (1.0 / global_batch_size)
grads = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(list(zip(grads, model.trainable_variables)))
return cross_entropy
per_example_losses = mirrored_strategy.experimental_run_v2(
step_fn, args=(dist_inputs,))
mean_loss = mirrored_strategy.reduce(
tf.distribute.ReduceOp.MEAN, per_example_losses, axis=0)
return mean_loss
###Output
_____no_output_____
###Markdown
A few other things to note in the code above:1. We used `tf.nn.softmax_cross_entropy_with_logits` to compute the loss. And then we scaled the total loss by the global batch size. This is important because all the replicas are training in sync and number of examples in each step of training is the global batch. So the loss needs to be divided by the global batch size and not by the replica (local) batch size.2. We used the `tf.distribute.Strategy.reduce` API to aggregate the results returned by `tf.distribute.Strategy.experimental_run_v2`. `tf.distribute.Strategy.experimental_run_v2` returns results from each local replica in the strategy, and there are multiple ways to consume this result. You can `reduce` them to get an aggregated value. You can also do `tf.distribute.Strategy.experimental_local_results` to get the list of values contained in the result, one per local replica.3. When `apply_gradients` is called within a distribution strategy scope, its behavior is modified. Specifically, before applying gradients on each parallel instance during synchronous training, it performs a sum-over-all-replicas of the gradients. Finally, once we have defined the training step, we can iterate over `dist_dataset` and run the training in a loop:
###Code
with mirrored_strategy.scope():
for inputs in dist_dataset:
print(train_step(inputs))
###Output
_____no_output_____
###Markdown
In the example above, we iterated over the `dist_dataset` to provide input to your training. We also provide the `tf.distribute.Strategy.make_experimental_numpy_dataset` to support numpy inputs. You can use this API to create a dataset before calling `tf.distribute.Strategy.experimental_distribute_dataset`.Another way of iterating over your data is to explicitly use iterators. You may want to do this when you want to run for a given number of steps as opposed to iterating over the entire dataset.The above iteration would now be modified to first create an iterator and then explicity call `next` on it to get the input data.
###Code
with mirrored_strategy.scope():
iterator = iter(dist_dataset)
for _ in range(10):
print(train_step(next(iterator)))
###Output
_____no_output_____
###Markdown
This covers the simplest case of using `tf.distribute.Strategy` API to distribute custom training loops. We are in the process of improving these APIs. Since this use case requires more work on the part of the user, we will be publishing a separate detailed guide in the future. What's supported now?In TF 2.0 beta release, we support training with custom training loops using `MirroredStrategy` as shown above and `TPUStrategy`. `MultiWorkerMirorredStrategy` support will be coming in the future.| Training API | MirroredStrategy | TPUStrategy | MultiWorkerMirroredStrategy | CentralStorageStrategy | ParameterServerStrategy ||:----------------------- |:------------------- |:------------------- |:----------------------------- |:------------------------ |:------------------------- || Custom Training Loop | Supported | Supported | Support planned in 2.0 RC | Support planned in 2.0 RC | No support yet | Examples and TutorialsHere are some examples for using distribution strategy with custom training loops:1. [Tutorial](../tutorials/distribute/training_loops.ipynb) to train MNIST using `MirroredStrategy`.2. [DenseNet](https://github.com/tensorflow/examples/blob/master/tensorflow_examples/models/densenet/distributed_train.py) example using `MirroredStrategy`.1. [BERT](https://github.com/tensorflow/models/blob/master/official/bert/run_classifier.py) example trained using `MirroredStrategy` and `TPUStrategy`.This example is particularly helpful for understanding how to load from a checkpoint and generate periodic checkpoints during distributed training etc.2. [NCF](https://github.com/tensorflow/models/blob/master/official/recommendation/ncf_keras_main.py) example trained using `MirroredStrategy` that can be enabled using the `keras_use_ctl` flag.3. [NMT](https://github.com/tensorflow/examples/blob/master/tensorflow_examples/models/nmt_with_attention/distributed_train.py) example trained using `MirroredStrategy`. Using `tf.distribute.Strategy` with Estimator`tf.estimator` is a distributed training TensorFlow API that originally supported the async parameter server approach. Like with Keras, we've integrated `tf.distribute.Strategy` into `tf.Estimator` so that a user who is using Estimator for their training can easily change their training is distributed with very few changes to your their code. With this, estimator users can now do synchronous distributed training on multiple GPUs and multiple workers, as well as use TPUs. This support in estimator is, however, limited. See [What's supported now](estimator_support) section below for more details.The usage of `tf.distribute.Strategy` with Estimator is slightly different than the Keras case. Instead of using `strategy.scope`, now we pass the strategy object into the [`RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig) for the Estimator.Here is a snippet of code that shows this with a premade estimator `LinearRegressor` and `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
config = tf.estimator.RunConfig(
train_distribute=mirrored_strategy, eval_distribute=mirrored_strategy)
regressor = tf.estimator.LinearRegressor(
feature_columns=[tf.feature_column.numeric_column('feats')],
optimizer='SGD',
config=config)
###Output
_____no_output_____
###Markdown
We use a premade Estimator here, but the same code works with a custom Estimator as well. `train_distribute` determines how training will be distributed, and `eval_distribute` determines how evaluation will be distributed. This is another difference from Keras where we use the same strategy for both training and eval.Now we can train and evaluate this Estimator with an input function:
###Code
def input_fn():
dataset = tf.data.Dataset.from_tensors(({"feats":[1.]}, [1.]))
return dataset.repeat(1000).batch(10)
regressor.train(input_fn=input_fn, steps=10)
regressor.evaluate(input_fn=input_fn, steps=10)
###Output
_____no_output_____
###Markdown
Copyright 2018 The TensorFlow Authors.
###Code
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###Output
_____no_output_____
###Markdown
Distributed training in TensorFlow View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook Overview`tf.distribute.Strategy` is a TensorFlow API to distribute training across multiple GPUs, multiple machines or TPUs. Using this API, users can distribute their existing models and training code with minimal code changes.`tf.distribute.Strategy` has been designed with these key goals in mind:* Easy to use and support multiple user segments, including researchers, ML engineers, etc.* Provide good performance out of the box.* Easy switching between strategies.`tf.distribute.Strategy` can be used with TensorFlow's high level APIs, [tf.keras](https://www.tensorflow.org/guide/keras) and [tf.estimator](https://www.tensorflow.org/guide/estimators), with just a couple of lines of code change. It also provides an API that can be used to distribute custom training loops (and in general any computation using TensorFlow).In TensorFlow 2.0, users can execute their programs eagerly, or in a graph using [`tf.function`](../tutorials/eager/tf_function.ipynb). `tf.distribute.Strategy` intends to support both these modes of execution. Note that we may talk about training most of the time in this guide, but this API can also be used for distributing evaluation and prediction on different platforms.As you will see in a bit, very few changes are needed to use `tf.distribute.Strategy` with your code. This is because we have changed the underlying components of TensorFlow to become strategy-aware. This includes variables, layers, models, optimizers, metrics, summaries, and checkpoints.In this guide, we will talk about various types of strategies and how one can use them in a different situations.
###Code
# Import TensorFlow
from __future__ import absolute_import, division, print_function, unicode_literals
!pip install tensorflow-gpu==2.0.0-beta1
import tensorflow as tf
###Output
_____no_output_____
###Markdown
Types of strategies`tf.distribute.Strategy` intends to cover a number of use cases along different axes. Some of these combinations are currently supported and others will be added in the future. Some of these axes are:* Synchronous vs asynchronous training: These are two common ways of distributing training with data parallelism. In sync training, all workers train over different slices of input data in sync, and aggregating gradients at each step. In async training, all workers are independently training over the input data and updating variables asynchronously. Typically sync training is supported via all-reduce and async through parameter server architecture.* Hardware platform: Users may want to scale their training onto multiple GPUs on one machine, or multiple machines in a network (with 0 or more GPUs each), or on Cloud TPUs.In order to support these use cases, we have 5 strategies available. In the next section we will talk about which of these are supported in which scenarios in TF 2.0-beta at this time. Here is a quick overview:| Training API | MirroredStrategy | TPUStrategy | MultiWorkerMirroredStrategy | CentralStorageStrategy | ParameterServerStrategy ||:----------------------- |:------------------- |:--------------------- |:--------------------------------- |:--------------------------------- |:-------------------------- || **Keras API** | Supported | Support planned in 2.0 RC | Experimental support | Experimental support | Supported planned in post 2.0 || **Custom training loop** | Experimental support | Experimental support | Support planned in 2.0 RC | Support planned in 2.0 RC | No support yet || **Estimator API** | Supported | Supported | Supported | Supported | Supported | MirroredStrategy`tf.distribute.MirroredStrategy` supports synchronous distributed training on multiple GPUs on one machine. It creates one replica per GPU device. Each variable in the model is mirrored across all the replicas. Together, these variables form a single conceptual variable called `MirroredVariable`. These variables are kept in sync with each other by applying identical updates.Efficient all-reduce algorithms are used to communicate the variable updates across the devices.All-reduce aggregates tensors across all the devices by adding them up, and makes them available on each device.It’s a fused algorithm that is very efficient and can reduce the overhead of synchronization significantly. There are many all-reduce algorithms and implementations available, depending on the type of communication available between devices. By default, it uses NVIDIA NCCL as the all-reduce implementation. The user can also choose between a few other options we provide, or write their own.Here is the simplest way of creating `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
###Output
_____no_output_____
###Markdown
This will create a `MirroredStrategy` instance which will use all the GPUs that are visible to TensorFlow, and use NCCL as the cross device communication.If you wish to use only some of the GPUs on your machine, you can do so like this:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(devices=["/gpu:0", "/gpu:1"])
###Output
_____no_output_____
###Markdown
If you wish to override the cross device communication, you can do so using the `cross_device_ops` argument by supplying an instance of `tf.distribute.CrossDeviceOps`. Currently we provide `tf.distribute.HierarchicalCopyAllReduce` and `tf.distribute.ReductionToOneDevice` as 2 other options other than `tf.distribute.NcclAllReduce` which is the default.
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(
cross_device_ops=tf.distribute.HierarchicalCopyAllReduce())
###Output
_____no_output_____
###Markdown
CentralStorageStrategy`tf.distribute.experimental.CentralStorageStrategy` does synchronous training as well. Variables are not mirrored, instead they are placed on the CPU and operations are replicated across all local GPUs. If there is only one GPU, all variables and operations will be placed on that GPU.Create an instance of `CentralStorageStrategy` by:
###Code
central_storage_strategy = tf.distribute.experimental.CentralStorageStrategy()
###Output
_____no_output_____
###Markdown
This will create a `CentralStorageStrategy` instance which will use all visible GPUs and CPU. Update to variables on replicas will be aggregated before being applied to variables. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. MultiWorkerMirroredStrategy`tf.distribute.experimental.MultiWorkerMirroredStrategy` is very similar to `MirroredStrategy`. It implements synchronous distributed training across multiple workers, each with potentially multiple GPUs. Similar to `MirroredStrategy`, it creates copies of all variables in the model on each device across all workers.It uses [CollectiveOps](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/collective_ops.py) as the multi-worker all-reduce communication method used to keep variables in sync. A collective op is a single op in the TensorFlow graph which can automatically choose an all-reduce algorithm in the TensorFlow runtime according to hardware, network topology and tensor sizes.It also implements additional performance optimizations. For example, it includes a static optimization that converts multiple all-reductions on small tensors into fewer all-reductions on larger tensors. In addition, we are designing it to have a plugin architecture - so that in the future, users will be able to plugin algorithms that are better tuned for their hardware. Note that collective ops also implement other collective operations such as broadcast and all-gather.Here is the simplest way of creating `MultiWorkerMirroredStrategy`:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()
###Output
_____no_output_____
###Markdown
`MultiWorkerMirroredStrategy` currently allows you to choose between two different implementations of collective ops. `CollectiveCommunication.RING` implements ring-based collectives using gRPC as the communication layer. `CollectiveCommunication.NCCL` uses [Nvidia's NCCL](https://developer.nvidia.com/nccl) to implement collectives. `CollectiveCommunication.AUTO` defers the choice to the runtime. The best choice of collective implementation depends upon the number and kind of GPUs, and the network interconnect in the cluster. You can specify them in the following way:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy(
tf.distribute.experimental.CollectiveCommunication.NCCL)
###Output
_____no_output_____
###Markdown
One of the key differences to get multi worker training going, as compared to multi-GPU training, is the multi-worker setup. "TF_CONFIG" environment variable is the standard way in TensorFlow to specify the cluster configuration to each worker that is part of the cluster. See section on ["TF_CONFIG" below](TF_CONFIG) for more details on how this can be done. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. TPUStrategy`tf.distribute.experimental.TPUStrategy` lets users run their TensorFlow training on Tensor Processing Units (TPUs). TPUs are Google's specialized ASICs designed to dramatically accelerate machine learning workloads. They are available on Google Colab, the [TensorFlow Research Cloud](https://www.tensorflow.org/tfrc) and [Google Compute Engine](https://cloud.google.com/tpu).In terms of distributed training architecture, TPUStrategy is the same `MirroredStrategy` - it implements synchronous distributed training. TPUs provide their own implementation of efficient all-reduce and other collective operations across multiple TPU cores, which are used in `TPUStrategy`.Here is how you would instantiate `TPUStrategy`.Note: To run this code in Colab, you should select TPU as the Colab runtime. We will have a tutorial soon that will demonstrate how you can use TPUStrategy.```cluster_resolver = tf.distribute.cluster_resolver.TPUClusterResolver( tpu=tpu_address)tf.config.experimental_connect_to_host(cluster_resolver.master())tf.tpu.experimental.initialize_tpu_system(cluster_resolver)tpu_strategy = tf.distribute.experimental.TPUStrategy(cluster_resolver)``` `TPUClusterResolver` instance helps locate the TPUs. In Colab, you don't need to specify any arguments to it. If you want to use this for Cloud TPUs, you will need to specify the name of your TPU resource in `tpu` argument. We also need to initialize the tpu system explicitly at the start of the program. This is required before TPUs can be used for computation and should ideally be done at the beginning because it also wipes out the TPU memory so all state will be lost. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. ParameterServerStrategy`tf.distribute.experimental.ParameterServerStrategy` supports parameter servers training on multiple machines. In this setup, some machines are designated as workers and some as parameter servers. Each variable of the model is placed on one parameter server. Computation is replicated across all GPUs of all the workers.In terms of code, it looks similar to other strategies:```ps_strategy = tf.distribute.experimental.ParameterServerStrategy()``` For multi worker training, "TF_CONFIG" needs to specify the configuration of parameter servers and workers in your cluster, which you can read more about in ["TF_CONFIG" below](TF_CONFIG) below. So far we've talked about what are the different stategies available and how you can instantiate them. In the next few sections, we will talk about the different ways in which you can use them to distribute your training. We will show short code snippets in this guide and link off to full tutorials which you can run end to end. Using `tf.distribute.Strategy` with KerasWe've integrated `tf.distribute.Strategy` into `tf.keras` which is TensorFlow's implementation of the[Keras API specification](https://keras.io). `tf.keras` is a high-level API to build and train models. By integrating into `tf.keras` backend, we've made it seamless for Keras users to distribute their training written in the Keras training framework. The only things that need to change in a user's program are: (1) Create an instance of the appropriate `tf.distribute.Strategy` and (2) Move the creation and compiling of Keras model inside `strategy.scope`. We support all types of Keras models - sequential, functional and subclassed.Here is a snippet of code to do this for a very simple Keras model with one dense layer:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
model.compile(loss='mse', optimizer='sgd')
###Output
_____no_output_____
###Markdown
In this example we used `MirroredStrategy` so we can run this on a machine with multiple GPUs. `strategy.scope()` indicated which parts of the code to run distributed. Creating a model inside this scope allows us to create mirrored variables instead of regular variables. Compiling under the scope allows us to know that the user intends to train this model using this strategy. Once this is setup, you can fit your model like you would normally. `MirroredStrategy` takes care of replicating the model's training on the available GPUs, aggregating gradients etc.
###Code
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100).batch(10)
model.fit(dataset, epochs=2)
model.evaluate(dataset)
###Output
_____no_output_____
###Markdown
Here we used a `tf.data.Dataset` to provide the training and eval input. You can also use numpy arrays:
###Code
import numpy as np
inputs, targets = np.ones((100, 1)), np.ones((100, 1))
model.fit(inputs, targets, epochs=2, batch_size=10)
###Output
_____no_output_____
###Markdown
In both cases (dataset or numpy), each batch of the given input is divided equally among the multiple replicas. For instance, if using `MirroredStrategy` with 2 GPUs, each batch of size 10 will get divided among the 2 GPUs, with each receiving 5 input examples in each step. Each epoch will then train faster as you add more GPUs. Typically, you would want to increase your batch size as you add more accelerators so as to make effective use of the extra computing power. You will also need to re-tune your learning rate, depending on the model. You can use `strategy.num_replicas_in_sync` to get the number of replicas.
###Code
# Compute global batch size using number of replicas.
BATCH_SIZE_PER_REPLICA = 5
global_batch_size = (BATCH_SIZE_PER_REPLICA *
mirrored_strategy.num_replicas_in_sync)
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100)
dataset = dataset.batch(global_batch_size)
LEARNING_RATES_BY_BATCH_SIZE = {5: 0.1, 10: 0.15}
learning_rate = LEARNING_RATES_BY_BATCH_SIZE[global_batch_size]
###Output
_____no_output_____
###Markdown
What's supported now?In TF 2.0 beta release, we support training with Keras using `MirroredStrategy`, `CentralStorageStrategy` and `MultiWorkerMirroredStrategy`. Both `CentralStorageStrategy` and `MultiWorkerMirroredStrategy` are currently experimental APIs and are subject to change.Support for other strategies will be coming soon. The API and how to use will be exactly the same as above.| Training API | MirroredStrategy | TPUStrategy | MultiWorkerMirroredStrategy | CentralStorageStrategy | ParameterServerStrategy ||---------------- |--------------------- |----------------------- |----------------------------------- |----------------------------------- |--------------------------- || Keras APIs | Supported | Support planned in 2.0 RC | Experimental support | Experimental support | Support planned in post 2.0 | Examples and TutorialsHere is a list of tutorials and examples that illustrate the above integration end to end with Keras:1. Tutorial to train [MNIST](../tutorials/distribute/keras.ipynb) with `MirroredStrategy`.2. Official [ResNet50](https://github.com/tensorflow/models/blob/master/official/resnet/keras/keras_imagenet_main.py) training with ImageNet data using `MirroredStrategy`.3. [ResNet50](https://github.com/tensorflow/tpu/blob/master/models/experimental/resnet50_keras/resnet50.py) trained with Imagenet data on Cloud TPus with `TPUStrategy`. Note that this example only works with TensorFlow 1.x currently.4. [Tutorial](../tutorials/distribute/multi_worker_with_keras.ipynb) to train MNIST using `MultiWorkerMirroredStrategy`.5. [NCF](https://github.com/tensorflow/models/blob/master/official/recommendation/ncf_keras_main.py) trained using `MirroredStrategy`.2. [Transformer]( https://github.com/tensorflow/models/blob/master/official/transformer/v2/transformer_main.py) trained using `MirroredStrategy`. Using `tf.distribute.Strategy` with Estimator`tf.estimator` is a distributed training TensorFlow API that originally supported the async parameter server approach. Like with Keras, we've integrated `tf.distribute.Strategy` into `tf.Estimator` so that a user who is using Estimator for their training can easily change their training is distributed with very few changes to your their code. With this, estimator users can now do synchronous distributed training on multiple GPUs and multiple workers, as well as use TPUs.The usage of `tf.distribute.Strategy` with Estimator is slightly different than the Keras case. Instead of using `strategy.scope`, now we pass the strategy object into the [`RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig) for the Estimator.Here is a snippet of code that shows this with a premade estimator `LinearRegressor` and `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
config = tf.estimator.RunConfig(
train_distribute=mirrored_strategy, eval_distribute=mirrored_strategy)
regressor = tf.estimator.LinearRegressor(
feature_columns=[tf.feature_column.numeric_column('feats')],
optimizer='SGD',
config=config)
###Output
_____no_output_____
###Markdown
We use a premade Estimator here, but the same code works with a custom Estimator as well. `train_distribute` determines how training will be distributed, and `eval_distribute` determines how evaluation will be distributed. This is another difference from Keras where we use the same strategy for both training and eval.Now we can train and evaluate this Estimator with an input function:
###Code
def input_fn():
dataset = tf.data.Dataset.from_tensors(({"feats":[1.]}, [1.]))
return dataset.repeat(1000).batch(10)
regressor.train(input_fn=input_fn, steps=10)
regressor.evaluate(input_fn=input_fn, steps=10)
###Output
_____no_output_____
###Markdown
Another difference to highlight here between Estimator and Keras is the input handling. In Keras, we mentioned that each batch of the dataset is split across the multiple replicas. In Estimator, however, the user provides an `input_fn` and have full control over how they want their data to be distributed across workers and devices. We do not do automatic splitting of batch, nor automatically shard the data across different workers. The provided `input_fn` is called once per worker, thus giving one dataset per worker. Then one batch from that dataset is fed to one replica on that worker, thereby consuming N batches for N replicas on 1 worker. In other words, the dataset returned by the `input_fn` should provide batches of size `PER_REPLICA_BATCH_SIZE`. And the global batch size for a step can be obtained as `PER_REPLICA_BATCH_SIZE * strategy.num_replicas_in_sync`. When doing multi worker training, users will also want to either split their data across the workers, or shuffle with a random seed on each. You can see an example of how to do this in the [Multi-worker Training with Estimator](../tutorials/distribute/multi_worker_with_estimator.ipynb). We showed an example of using `MirroredStrategy` with Estimator. You can also use `TPUStrategy` with Estimator as well, in the exact same way:```config = tf.estimator.RunConfig( train_distribute=tpu_strategy, eval_distribute=tpu_strategy)``` And similarly, you can use multi worker and parameter server strategies as well. The code remains the same, but you need to use `tf.estimator.train_and_evaluate`, and set "TF_CONFIG" environment variables for each binary running in your cluster. What's supported now?In TF 2.0 beta release, we support training with Estimator using all strategies.| Training API | MirroredStrategy | TPUStrategy | MultiWorkerMirroredStrategy | CentralStorageStrategy | ParameterServerStrategy ||:--------------- |:------------------ |:------------- |:----------------------------- |:------------------------ |:------------------------- || Estimator API | Supported | Supported | Supported | Supported | Supported | Examples and TutorialsHere are some examples that show end to end usage of various strategies with Estimator:1. [Multi-worker Training with Estimator](../tutorials/distribute/multi_worker_with_estimator.ipynb) to train MNIST with multiple workers using `MultiWorkerMirroredStrategy`.2. [End to end example](https://github.com/tensorflow/ecosystem/tree/master/distribution_strategy) for multi worker training in tensorflow/ecosystem using Kuberentes templates. This example starts with a Keras model and converts it to an Estimator using the `tf.keras.estimator.model_to_estimator` API.3. Official [ResNet50](https://github.com/tensorflow/models/blob/master/official/resnet/imagenet_main.py) model, which can be trained using either `MirroredStrategy` or `MultiWorkerMirroredStrategy`.4. [ResNet50](https://github.com/tensorflow/tpu/blob/master/models/experimental/distribution_strategy/resnet_estimator.py) example with TPUStrategy. Using `tf.distribute.Strategy` with custom training loopsAs you've seen, using `tf.distribute.Strategy` with high level APIs is only a couple lines of code change. With a little more effort, `tf.distribute.Strategy` can also be used by other users who are not using these frameworks.TensorFlow is used for a wide variety of use cases and some users (such as researchers) require more flexibility and control over their training loops. This makes it hard for them to use the high level frameworks such as Estimator or Keras. For instance, someone using a GAN may want to take a different number of generator or discriminator steps each round. Similarly, the high level frameworks are not very suitable for Reinforcement Learning training. So these users will usually write their own training loops.For these users, we provide a core set of methods through the `tf.distribute.Strategy` classes. Using these may require minor restructuring of the code initially, but once that is done, the user should be able to switch between GPUs / TPUs / multiple machines by just changing the strategy instance.Here we will show a brief snippet illustrating this use case for a simple training example using the same Keras model as before. First, we create the model and optimizer inside the strategy's scope. This ensures that any variables created with the model and optimizer are mirrored variables.
###Code
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
optimizer = tf.keras.optimizers.SGD()
###Output
_____no_output_____
###Markdown
Next, we create the input dataset and call `tf.distribute.Strategy.experimental_distribute_dataset` to distribute the dataset based on the strategy.
###Code
with mirrored_strategy.scope():
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(1000).batch(
global_batch_size)
dist_dataset = mirrored_strategy.experimental_distribute_dataset(dataset)
###Output
_____no_output_____
###Markdown
Then, we define one step of the training. We will use `tf.GradientTape` to compute gradients and optimizer to apply those gradients to update our model's variables. To distribute this training step, we put in in a function `step_fn` and pass it to `tf.distrbute.Strategy.experimental_run_v2` along with the dataset inputs that we get from `dist_dataset` created before:
###Code
@tf.function
def train_step(dist_inputs):
def step_fn(inputs):
features, labels = inputs
with tf.GradientTape() as tape:
logits = model(features)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(
logits=logits, labels=labels)
loss = tf.reduce_sum(cross_entropy) * (1.0 / global_batch_size)
grads = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(list(zip(grads, model.trainable_variables)))
return cross_entropy
per_example_losses = mirrored_strategy.experimental_run_v2(
step_fn, args=(dist_inputs,))
mean_loss = mirrored_strategy.reduce(
tf.distribute.ReduceOp.MEAN, per_example_losses, axis=0)
return mean_loss
###Output
_____no_output_____
###Markdown
A few other things to note in the code above:1. We used `tf.nn.softmax_cross_entropy_with_logits` to compute the loss. And then we scaled the total loss by the global batch size. This is important because all the replicas are training in sync and number of examples in each step of training is the global batch. So the loss needs to be divided by the global batch size and not by the replica (local) batch size.2. We used the `tf.distribute.Strategy.reduce` API to aggregate the results returned by `tf.distribute.Strategy.experimental_run_v2`. `tf.distribute.Strategy.experimental_run_v2` returns results from each local replica in the strategy, and there are multiple ways to consume this result. You can `reduce` them to get an aggregated value. You can also do `tf.distribute.Strategy.experimental_local_results` to get the list of values contained in the result, one per local replica.3. When `apply_gradients` is called within a distribution strategy scope, its behavior is modified. Specifically, before applying gradients on each parallel instance during synchronous training, it performs a sum-over-all-replicas of the gradients. Finally, once we have defined the training step, we can iterate over `dist_dataset` and run the training in a loop:
###Code
with mirrored_strategy.scope():
for inputs in dist_dataset:
print(train_step(inputs))
###Output
_____no_output_____
###Markdown
In the example above, we iterated over the `dist_dataset` to provide input to your training. We also provide the `tf.distribute.Strategy.make_experimental_numpy_dataset` to support numpy inputs. You can use this API to create a dataset before calling `tf.distribute.Strategy.experimental_distribute_dataset`.Another way of iterating over your data is to explicitly use iterators. You may want to do this when you want to run for a given number of steps as opposed to iterating over the entire dataset.The above iteration would now be modified to first create an iterator and then explicity call `next` on it to get the input data.
###Code
with mirrored_strategy.scope():
iterator = iter(dist_dataset)
for _ in range(10):
print(train_step(next(iterator)))
###Output
_____no_output_____
###Markdown
Copyright 2018 The TensorFlow Authors.
###Code
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###Output
_____no_output_____
###Markdown
Distributed training in TensorFlow View on TensorFlow.org Run in Google Colab View source on GitHub Overview`tf.distribute.Strategy` is a TensorFlow API to distribute training across multiple GPUs, multiple machines or TPUs. Using this API, users can distribute their existing models and training code with minimal code changes.`tf.distribute.Strategy` has been designed with these key goals in mind:* Easy to use and support multiple user segments, including researchers, ML engineers, etc.* Provide good performance out of the box.* Easy switching between strategies.`tf.distribute.Strategy` can be used with TensorFlow's high level APIs, [tf.keras](https://www.tensorflow.org/guide/keras) and [tf.estimator](https://www.tensorflow.org/guide/estimators), with just a couple of lines of code change. It also provides an API that can be used to distribute custom training loops (and in general any computation using TensorFlow).In TensorFlow 2.0, users can execute their programs eagerly, or in a graph using [`tf.function`](../tutorials/eager/tf_function.ipynb). `tf.distribute.Strategy` intends to support both these modes of execution. Note that we may talk about training most of the time in this guide, but this API can also be used for distributing evaluation and prediction on different platforms.As you will see in a bit, very few changes are needed to use `tf.distribute.Strategy` with your code. This is because we have changed the underlying components of TensorFlow to become strategy-aware. This includes variables, layers, models, optimizers, metrics, summaries, and checkpoints.In this guide, we will talk about various types of strategies and how one can use them in a different situations.
###Code
# Import TensorFlow
from __future__ import absolute_import, division, print_function, unicode_literals
!pip install tf-nightly-gpu-2.0-preview
import tensorflow as tf
###Output
_____no_output_____
###Markdown
Types of strategies`tf.distribute.Strategy` intends to cover a number of use cases along different axes. Some of these combinations are currently supported and others will be added in the future. Some of these axes are:* Synchronous vs asynchronous training: These are two common ways of distributing training with data parallelism. In sync training, all workers train over different slices of input data in sync, and aggregating gradients at each step. In async training, all workers are independently training over the input data and updating variables asynchronously. Typically sync training is supported via all-reduce and async through parameter server architecture.* Hardware platform: Users may want to scale their training onto multiple GPUs on one machine, or multiple machines in a network (with 0 or more GPUs each), or on Cloud TPUs.In order to support these use cases, we have 5 strategies available. In the next section we will talk about which of these are supported in which scenarios in TF 2.0-beta at this time. Here is a quick overview:| Training API | MirroredStrategy | TPUStrategy | MultiWorkerMirroredStrategy | CentralStorageStrategy | ParameterServerStrategy ||:----------------------- |:------------------- |:--------------------- |:--------------------------------- |:--------------------------------- |:-------------------------- || **Keras API** | Supported | Support planned in 2.0 RC | Experimental support | Experimental support | Supported planned in post 2.0 || **Custom training loop** | Experimental support | Experimental support | Support planned in 2.0 RC | Support planned in 2.0 RC | No support yet || **Estimator API** | Supported | Supported | Supported | Supported | Supported | MirroredStrategy`tf.distribute.MirroredStrategy` supports synchronous distributed training on multiple GPUs on one machine. It creates one replica per GPU device. Each variable in the model is mirrored across all the replicas. Together, these variables form a single conceptual variable called `MirroredVariable`. These variables are kept in sync with each other by applying identical updates.Efficient all-reduce algorithms are used to communicate the variable updates across the devices.All-reduce aggregates tensors across all the devices by adding them up, and makes them available on each device.It’s a fused algorithm that is very efficient and can reduce the overhead of synchronization significantly. There are many all-reduce algorithms and implementations available, depending on the type of communication available between devices. By default, it uses NVIDIA NCCL as the all-reduce implementation. The user can also choose between a few other options we provide, or write their own.Here is the simplest way of creating `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
###Output
_____no_output_____
###Markdown
This will create a `MirroredStrategy` instance which will use all the GPUs that are visible to TensorFlow, and use NCCL as the cross device communication.If you wish to use only some of the GPUs on your machine, you can do so like this:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(devices=["/gpu:0", "/gpu:1"])
###Output
_____no_output_____
###Markdown
If you wish to override the cross device communication, you can do so using the `cross_device_ops` argument by supplying an instance of `tf.distribute.CrossDeviceOps`. Currently we provide `tf.distribute.HierarchicalCopyAllReduce` and `tf.distribute.ReductionToOneDevice` as 2 other options other than `tf.distribute.NcclAllReduce` which is the default.
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(
cross_device_ops=tf.distribute.HierarchicalCopyAllReduce())
###Output
_____no_output_____
###Markdown
CentralStorageStrategy`tf.distribute.experimental.CentralStorageStrategy` does synchronous training as well. Variables are not mirrored, instead they are placed on the CPU and operations are replicated across all local GPUs. If there is only one GPU, all variables and operations will be placed on that GPU.Create an instance of `CentralStorageStrategy` by:
###Code
central_storage_strategy = tf.distribute.experimental.CentralStorageStrategy()
###Output
_____no_output_____
###Markdown
This will create a `CentralStorageStrategy` instance which will use all visible GPUs and CPU. Update to variables on replicas will be aggregated before being applied to variables. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. MultiWorkerMirroredStrategy`tf.distribute.experimental.MultiWorkerMirroredStrategy` is very similar to `MirroredStrategy`. It implements synchronous distributed training across multiple workers, each with potentially multiple GPUs. Similar to `MirroredStrategy`, it creates copies of all variables in the model on each device across all workers.It uses [CollectiveOps](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/collective_ops.py) as the multi-worker all-reduce communication method used to keep variables in sync. A collective op is a single op in the TensorFlow graph which can automatically choose an all-reduce algorithm in the TensorFlow runtime according to hardware, network topology and tensor sizes.It also implements additional performance optimizations. For example, it includes a static optimization that converts multiple all-reductions on small tensors into fewer all-reductions on larger tensors. In addition, we are designing it to have a plugin architecture - so that in the future, users will be able to plugin algorithms that are better tuned for their hardware. Note that collective ops also implement other collective operations such as broadcast and all-gather.Here is the simplest way of creating `MultiWorkerMirroredStrategy`:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()
###Output
_____no_output_____
###Markdown
`MultiWorkerMirroredStrategy` currently allows you to choose between two different implementations of collective ops. `CollectiveCommunication.RING` implements ring-based collectives using gRPC as the communication layer. `CollectiveCommunication.NCCL` uses [Nvidia's NCCL](https://developer.nvidia.com/nccl) to implement collectives. `CollectiveCommunication.AUTO` defers the choice to the runtime. The best choice of collective implementation depends upon the number and kind of GPUs, and the network interconnect in the cluster. You can specify them in the following way:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy(
tf.distribute.experimental.CollectiveCommunication.NCCL)
###Output
_____no_output_____
###Markdown
One of the key differences to get multi worker training going, as compared to multi-GPU training, is the multi-worker setup. "TF_CONFIG" environment variable is the standard way in TensorFlow to specify the cluster configuration to each worker that is part of the cluster. See section on ["TF_CONFIG" below](TF_CONFIG) for more details on how this can be done. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. TPUStrategy`tf.distribute.experimental.TPUStrategy` lets users run their TensorFlow training on Tensor Processing Units (TPUs). TPUs are Google's specialized ASICs designed to dramatically accelerate machine learning workloads. They are available on Google Colab, the [TensorFlow Research Cloud](https://www.tensorflow.org/tfrc) and [Google Compute Engine](https://cloud.google.com/tpu).In terms of distributed training architecture, TPUStrategy is the same `MirroredStrategy` - it implements synchronous distributed training. TPUs provide their own implementation of efficient all-reduce and other collective operations across multiple TPU cores, which are used in `TPUStrategy`.Here is how you would instantiate `TPUStrategy`.Note: To run this code in Colab, you should select TPU as the Colab runtime. We will have a tutorial soon that will demonstrate how you can use TPUStrategy.```cluster_resolver = tf.distribute.cluster_resolver.TPUClusterResolver( tpu=tpu_address)tf.config.experimental_connect_to_host(cluster_resolver.master())tf.tpu.experimental.initialize_tpu_system(cluster_resolver)tpu_strategy = tf.distribute.experimental.TPUStrategy(cluster_resolver)``` `TPUClusterResolver` instance helps locate the TPUs. In Colab, you don't need to specify any arguments to it. If you want to use this for Cloud TPUs, you will need to specify the name of your TPU resource in `tpu` argument. We also need to initialize the tpu system explicitly at the start of the program. This is required before TPUs can be used for computation and should ideally be done at the beginning because it also wipes out the TPU memory so all state will be lost. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. ParameterServerStrategy`tf.distribute.experimental.ParameterServerStrategy` supports parameter servers training on multiple machines. In this setup, some machines are designated as workers and some as parameter servers. Each variable of the model is placed on one parameter server. Computation is replicated across all GPUs of the all the workers.In terms of code, it looks similar to other strategies:```ps_strategy = tf.distribute.experimental.ParameterServerStrategy()``` For multi worker training, "TF_CONFIG" needs to specify the configuration of parameter servers and workers in your cluster, which you can read more about in ["TF_CONFIG" below](TF_CONFIG) below. So far we've talked about what are the different stategies available and how you can instantiate them. In the next few sections, we will talk about the different ways in which you can use them to distribute your training. We will show short code snippets in this guide and link off to full tutorials which you can run end to end. Using `tf.distribute.Strategy` with KerasWe've integrated `tf.distribute.Strategy` into `tf.keras` which is TensorFlow's implementation of the[Keras API specification](https://keras.io). `tf.keras` is a high-level API to build and train models. By integrating into `tf.keras` backend, we've made it seamless for Keras users to distribute their training written in the Keras training framework. The only things that need to change in a user's program are: (1) Create an instance of the appropriate `tf.distribute.Strategy` and (2) Move the creation and compiling of Keras model inside `strategy.scope`. We support all types of Keras models - sequential, functional and subclassed.Here is a snippet of code to do this for a very simple Keras model with one dense layer:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
model.compile(loss='mse', optimizer='sgd')
###Output
_____no_output_____
###Markdown
In this example we used `MirroredStrategy` so we can run this on a machine with multiple GPUs. `strategy.scope()` indicated which parts of the code to run distributed. Creating a model inside this scope allows us to create mirrored variables instead of regular variables. Compiling under the scope allows us to know that the user intends to train this model using this strategy. Once this is setup, you can fit your model like you would normally. `MirroredStrategy` takes care of replicating the model's training on the available GPUs, aggregating gradients etc.
###Code
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100).batch(10)
model.fit(dataset, epochs=2)
model.evaluate(dataset)
###Output
_____no_output_____
###Markdown
Here we used a `tf.data.Dataset` to provide the training and eval input. You can also use numpy arrays:
###Code
import numpy as np
inputs, targets = np.ones((100, 1)), np.ones((100, 1))
model.fit(inputs, targets, epochs=2, batch_size=10)
###Output
_____no_output_____
###Markdown
In both cases (dataset or numpy), each batch of the given input is divided equally among the multiple replicas. For instance, if using `MirroredStrategy` with 2 GPUs, each batch of size 10 will get divided among the 2 GPUs, with each receiving 5 input examples in each step. Each epoch will then train faster as you add more GPUs. Typically, you would want to increase your batch size as you add more accelerators so as to make effective use of the extra computing power. You will also need to re-tune your learning rate, depending on the model. You can use `strategy.num_replicas_in_sync` to get the number of replicas.
###Code
# Compute global batch size using number of replicas.
BATCH_SIZE_PER_REPLICA = 5
global_batch_size = (BATCH_SIZE_PER_REPLICA *
mirrored_strategy.num_replicas_in_sync)
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100)
dataset = dataset.batch(global_batch_size)
LEARNING_RATES_BY_BATCH_SIZE = {5: 0.1, 10: 0.15}
learning_rate = LEARNING_RATES_BY_BATCH_SIZE[global_batch_size]
###Output
_____no_output_____
###Markdown
What's supported now?In TF 2.0 beta release, we support training with Keras using `MirroredStrategy`, `CentralStorageStrategy` and `MultiWorkerMirroredStrategy`. Both `CentralStorageStrategy` and `MultiWorkerMirroredStrategy` are currently experimental APIs and are subject to change.Support for other strategies will be coming soon. The API and how to use will be exactly the same as above.| Training API | MirroredStrategy | TPUStrategy | MultiWorkerMirroredStrategy | CentralStorageStrategy | ParameterServerStrategy ||---------------- |--------------------- |----------------------- |----------------------------------- |----------------------------------- |--------------------------- || Keras APIs | Supported | Support planned in 2.0 RC | Experimental support | Experimental support | Support planned in post 2.0 | Examples and TutorialsHere is a list of tutorials and examples that illustrate the above integration end to end with Keras:1. Tutorial to train [MNIST](../tutorials/distribute/keras.ipynb) with `MirroredStrategy`.2. Official [ResNet50](https://github.com/tensorflow/models/blob/master/official/resnet/keras/keras_imagenet_main.py) training with ImageNet data using `MirroredStrategy`.3. [ResNet50](https://github.com/tensorflow/tpu/blob/master/models/experimental/resnet50_keras/resnet50.py) trained with Imagenet data on Cloud TPus with `TPUStrategy`. Note that this example only works with TensorFlow 1.x currently.4. [Tutorial](../tutorials/distribute/multi_worker_with_keras.ipynb) to train MNIST using `MultiWorkerMirroredStrategy`.5. [NCF](https://github.com/tensorflow/models/blob/master/official/recommendation/ncf_keras_main.py) trained using `MirroredStrategy`.2. [Transformer]( https://github.com/tensorflow/models/blob/master/official/transformer/v2/transformer_main.py) trained using `MirroredStrategy`. Using `tf.distribute.Strategy` with Estimator`tf.estimator` is a distributed training TensorFlow API that originally supported the async parameter server approach. Like with Keras, we've integrated `tf.distribute.Strategy` into `tf.Estimator` so that a user who is using Estimator for their training can easily change their training is distributed with very few changes to your their code. With this, estimator users can now do synchronous distributed training on multiple GPUs and multiple workers, as well as use TPUs.The usage of `tf.distribute.Strategy` with Estimator is slightly different than the Keras case. Instead of using `strategy.scope`, now we pass the strategy object into the [`RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig) for the Estimator.Here is a snippet of code that shows this with a premade estimator `LinearRegressor` and `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
config = tf.estimator.RunConfig(
train_distribute=mirrored_strategy, eval_distribute=mirrored_strategy)
regressor = tf.estimator.LinearRegressor(
feature_columns=[tf.feature_column.numeric_column('feats')],
optimizer='SGD',
config=config)
###Output
_____no_output_____
###Markdown
We use a premade Estimator here, but the same code works with a custom Estimator as well. `train_distribute` determines how training will be distributed, and `eval_distribute` determines how evaluation will be distributed. This is another difference from Keras where we use the same strategy for both training and eval.Now we can train and evaluate this Estimator with an input function:
###Code
def input_fn():
dataset = tf.data.Dataset.from_tensors(({"feats":[1.]}, [1.]))
return dataset.repeat(1000).batch(10)
regressor.train(input_fn=input_fn, steps=10)
regressor.evaluate(input_fn=input_fn, steps=10)
###Output
_____no_output_____
###Markdown
Another difference to highlight here between Estimator and Keras is the input handling. In Keras, we mentioned that each batch of the dataset is split across the multiple replicas. In Estimator, however, the user provides an `input_fn` and have full control over how they want their data to be distributed across workers and devices. We do not do automatic splitting of batch, nor automatically shard the data across different workers. The provided `input_fn` is called once per worker, thus giving one dataset per worker. Then one batch from that dataset is fed to one replica on that worker, thereby consuming N batches for N replicas on 1 worker. In other words, the dataset returned by the `input_fn` should provide batches of size `PER_REPLICA_BATCH_SIZE`. And the global batch size for a step can be obtained as `PER_REPLICA_BATCH_SIZE * strategy.num_replicas_in_sync`. When doing multi worker training, users will also want to either split their data across the workers, or shuffle with a random seed on each. You can see an example of how to do this in the [Multi-worker Training with Estimator](../tutorials/distribute/multi_worker_with_estimator.ipynb). We showed an example of using `MirroredStrategy` with Estimator. You can also use `TPUStrategy` with Estimator as well, in the exact same way:```config = tf.estimator.RunConfig( train_distribute=tpu_strategy, eval_distribute=tpu_strategy)``` And similarly, you can use multi worker and parameter server strategies as well. The code remains the same, but you need to use `tf.estimator.train_and_evaluate`, and set "TF_CONFIG" environment variables for each binary running in your cluster. What's supported now?In TF 2.0 beta release, we support training with Estimator using all strategies.| Training API | MirroredStrategy | TPUStrategy | MultiWorkerMirroredStrategy | CentralStorageStrategy | ParameterServerStrategy ||:--------------- |:------------------ |:------------- |:----------------------------- |:------------------------ |:------------------------- || Estimator API | Supported | Supported | Supported | Supported | Supported | Examples and TutorialsHere are some examples that show end to end usage of various strategies with Estimator:1. [Multi-worker Training with Estimator](../tutorials/distribute/multi_worker_with_estimator.ipynb) to train MNIST with multiple workers using `MultiWorkerMirroredStrategy`.2. [End to end example](https://github.com/tensorflow/ecosystem/tree/master/distribution_strategy) for multi worker training in tensorflow/ecosystem using Kuberentes templates. This example starts with a Keras model and converts it to an Estimator using the `tf.keras.estimator.model_to_estimator` API.3. Official [ResNet50](https://github.com/tensorflow/models/blob/master/official/resnet/imagenet_main.py) model, which can be trained using either `MirroredStrategy` or `MultiWorkerMirroredStrategy`.4. [ResNet50](https://github.com/tensorflow/tpu/blob/master/models/experimental/distribution_strategy/resnet_estimator.py) example with TPUStrategy. Using `tf.distribute.Strategy` with custom training loopsAs you've seen, using `tf.distribute.Strategy` with high level APIs is only a couple lines of code change. With a little more effort, `tf.distribute.Strategy` can also be used by other users who are not using these frameworks.TensorFlow is used for a wide variety of use cases and some users (such as researchers) require more flexibility and control over their training loops. This makes it hard for them to use the high level frameworks such as Estimator or Keras. For instance, someone using a GAN may want to take a different number of generator or discriminator steps each round. Similarly, the high level frameworks are not very suitable for Reinforcement Learning training. So these users will usually write their own training loops.For these users, we provide a core set of methods through the `tf.distribute.Strategy` classes. Using these may require minor restructuring of the code initially, but once that is done, the user should be able to switch between GPUs / TPUs / multiple machines by just changing the strategy instance.Here we will show a brief snippet illustrating this use case for a simple training example using the same Keras model as before. First, we create the model and optimizer inside the strategy's scope. This ensures that any variables created with the model and optimizer are mirrored variables.
###Code
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
optimizer = tf.keras.optimizers.SGD()
###Output
_____no_output_____
###Markdown
Next, we create the input dataset and call `tf.distribute.Strategy.experimental_distribute_dataset` to distribute the dataset based on the strategy.
###Code
with mirrored_strategy.scope():
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(1000).batch(
global_batch_size)
dist_dataset = mirrored_strategy.experimental_distribute_dataset(dataset)
###Output
_____no_output_____
###Markdown
Then, we define one step of the training. We will use `tf.GradientTape` to compute gradients and optimizer to apply those gradients to update our model's variables. To distribute this training step, we put in in a function `step_fn` and pass it to `tf.distrbute.Strategy.experimental_run_v2` along with the dataset inputs that we get from `dist_dataset` created before:
###Code
@tf.function
def train_step(dist_inputs):
def step_fn(inputs):
features, labels = inputs
with tf.GradientTape() as tape:
logits = model(features)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(
logits=logits, labels=labels)
loss = tf.reduce_sum(cross_entropy) * (1.0 / global_batch_size)
grads = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(list(zip(grads, model.trainable_variables)))
return cross_entropy
per_example_losses = mirrored_strategy.experimental_run_v2(
step_fn, args=(dist_inputs,))
mean_loss = mirrored_strategy.reduce(
tf.distribute.ReduceOp.MEAN, per_example_losses, axis=0)
return mean_loss
###Output
_____no_output_____
###Markdown
A few other things to note in the code above:1. We used `tf.nn.softmax_cross_entropy_with_logits` to compute the loss. And then we scaled the total loss by the global batch size. This is important because all the replicas are training in sync and number of examples in each step of training is the global batch. So the loss needs to be divided by the global batch size and not by the replica (local) batch size.2. We used the `tf.distribute.Strategy.reduce` API to aggregate the results returned by `tf.distribute.Strategy.experimental_run_v2`. `tf.distribute.Strategy.experimental_run_v2` returns results from each local replica in the strategy, and there are multiple ways to consume this result. You can `reduce` them to get an aggregated value. You can also do `tf.distribute.Strategy.experimental_local_results` to get the list of values contained in the result, one per local replica.3. When `apply_gradients` is called within a distribution strategy scope, its behavior is modified. Specifically, before applying gradients on each parallel instance during synchronous training, it performs a sum-over-all-replicas of the gradients. Finally, once we have defined the training step, we can iterate over `dist_dataset` and run the training in a loop:
###Code
with mirrored_strategy.scope():
for inputs in dist_dataset:
print(train_step(inputs))
###Output
_____no_output_____
###Markdown
In the example above, we iterated over the `dist_dataset` to provide input to your training. We also provide the `tf.distribute.Strategy.make_experimental_numpy_dataset` to support numpy inputs. You can use this API to create a dataset before calling `tf.distribute.Strategy.experimental_distribute_dataset`.Another way of iterating over your data is to explicitly use iterators. You may want to do this when you want to run for a given number of steps as opposed to iterating over the entire dataset.The above iteration would now be modified to first create an iterator and then explicity call `next` on it to get the input data.
###Code
with mirrored_strategy.scope():
iterator = iter(dist_dataset)
for _ in range(10):
print(train_step(next(iterator)))
###Output
_____no_output_____
###Markdown
Copyright 2018 The TensorFlow Authors.
###Code
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###Output
_____no_output_____
###Markdown
Distributed training in TensorFlow View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook Overview`tf.distribute.Strategy` is a TensorFlow API to distribute training across multiple GPUs, multiple machines or TPUs. Using this API, users can distribute their existing models and training code with minimal code changes.`tf.distribute.Strategy` has been designed with these key goals in mind:* Easy to use and support multiple user segments, including researchers, ML engineers, etc.* Provide good performance out of the box.* Easy switching between strategies.`tf.distribute.Strategy` can be used with TensorFlow's high level APIs, [tf.keras](https://www.tensorflow.org/guide/keras) and [tf.estimator](https://www.tensorflow.org/guide/estimators), with just a couple of lines of code change. It also provides an API that can be used to distribute custom training loops (and in general any computation using TensorFlow).In TensorFlow 2.0, users can execute their programs eagerly, or in a graph using [`tf.function`](../tutorials/eager/tf_function.ipynb). `tf.distribute.Strategy` intends to support both these modes of execution. Note that we may talk about training most of the time in this guide, but this API can also be used for distributing evaluation and prediction on different platforms.As you will see in a bit, very few changes are needed to use `tf.distribute.Strategy` with your code. This is because we have changed the underlying components of TensorFlow to become strategy-aware. This includes variables, layers, models, optimizers, metrics, summaries, and checkpoints.In this guide, we will talk about various types of strategies and how one can use them in a different situations.
###Code
# Import TensorFlow
from __future__ import absolute_import, division, print_function, unicode_literals
!pip install tensorflow-gpu==2.0.0-beta1
import tensorflow as tf
###Output
_____no_output_____
###Markdown
Types of strategies`tf.distribute.Strategy` intends to cover a number of use cases along different axes. Some of these combinations are currently supported and others will be added in the future. Some of these axes are:* Synchronous vs asynchronous training: These are two common ways of distributing training with data parallelism. In sync training, all workers train over different slices of input data in sync, and aggregating gradients at each step. In async training, all workers are independently training over the input data and updating variables asynchronously. Typically sync training is supported via all-reduce and async through parameter server architecture.* Hardware platform: Users may want to scale their training onto multiple GPUs on one machine, or multiple machines in a network (with 0 or more GPUs each), or on Cloud TPUs.In order to support these use cases, we have 5 strategies available. In the next section we will talk about which of these are supported in which scenarios in TF 2.0-beta at this time. Here is a quick overview:| Training API | MirroredStrategy | TPUStrategy | MultiWorkerMirroredStrategy | CentralStorageStrategy | ParameterServerStrategy ||:----------------------- |:------------------- |:--------------------- |:--------------------------------- |:--------------------------------- |:-------------------------- || **Keras API** | Supported | Support planned in 2.0 RC | Experimental support | Experimental support | Supported planned post 2.0 || **Custom training loop** | Experimental support | Experimental support | Support planned post 2.0 RC | Support planned in 2.0 RC | No support yet || **Estimator API** | Limited Support | Limited Support | Limited Support | Limited Support | Limited Support | MirroredStrategy`tf.distribute.MirroredStrategy` supports synchronous distributed training on multiple GPUs on one machine. It creates one replica per GPU device. Each variable in the model is mirrored across all the replicas. Together, these variables form a single conceptual variable called `MirroredVariable`. These variables are kept in sync with each other by applying identical updates.Efficient all-reduce algorithms are used to communicate the variable updates across the devices.All-reduce aggregates tensors across all the devices by adding them up, and makes them available on each device.It’s a fused algorithm that is very efficient and can reduce the overhead of synchronization significantly. There are many all-reduce algorithms and implementations available, depending on the type of communication available between devices. By default, it uses NVIDIA NCCL as the all-reduce implementation. The user can also choose between a few other options we provide, or write their own.Here is the simplest way of creating `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
###Output
_____no_output_____
###Markdown
This will create a `MirroredStrategy` instance which will use all the GPUs that are visible to TensorFlow, and use NCCL as the cross device communication.If you wish to use only some of the GPUs on your machine, you can do so like this:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(devices=["/gpu:0", "/gpu:1"])
###Output
_____no_output_____
###Markdown
If you wish to override the cross device communication, you can do so using the `cross_device_ops` argument by supplying an instance of `tf.distribute.CrossDeviceOps`. Currently we provide `tf.distribute.HierarchicalCopyAllReduce` and `tf.distribute.ReductionToOneDevice` as 2 other options other than `tf.distribute.NcclAllReduce` which is the default.
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(
cross_device_ops=tf.distribute.HierarchicalCopyAllReduce())
###Output
_____no_output_____
###Markdown
CentralStorageStrategy`tf.distribute.experimental.CentralStorageStrategy` does synchronous training as well. Variables are not mirrored, instead they are placed on the CPU and operations are replicated across all local GPUs. If there is only one GPU, all variables and operations will be placed on that GPU.Create an instance of `CentralStorageStrategy` by:
###Code
central_storage_strategy = tf.distribute.experimental.CentralStorageStrategy()
###Output
_____no_output_____
###Markdown
This will create a `CentralStorageStrategy` instance which will use all visible GPUs and CPU. Update to variables on replicas will be aggregated before being applied to variables. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. MultiWorkerMirroredStrategy`tf.distribute.experimental.MultiWorkerMirroredStrategy` is very similar to `MirroredStrategy`. It implements synchronous distributed training across multiple workers, each with potentially multiple GPUs. Similar to `MirroredStrategy`, it creates copies of all variables in the model on each device across all workers.It uses [CollectiveOps](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/collective_ops.py) as the multi-worker all-reduce communication method used to keep variables in sync. A collective op is a single op in the TensorFlow graph which can automatically choose an all-reduce algorithm in the TensorFlow runtime according to hardware, network topology and tensor sizes.It also implements additional performance optimizations. For example, it includes a static optimization that converts multiple all-reductions on small tensors into fewer all-reductions on larger tensors. In addition, we are designing it to have a plugin architecture - so that in the future, users will be able to plugin algorithms that are better tuned for their hardware. Note that collective ops also implement other collective operations such as broadcast and all-gather.Here is the simplest way of creating `MultiWorkerMirroredStrategy`:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()
###Output
_____no_output_____
###Markdown
`MultiWorkerMirroredStrategy` currently allows you to choose between two different implementations of collective ops. `CollectiveCommunication.RING` implements ring-based collectives using gRPC as the communication layer. `CollectiveCommunication.NCCL` uses [Nvidia's NCCL](https://developer.nvidia.com/nccl) to implement collectives. `CollectiveCommunication.AUTO` defers the choice to the runtime. The best choice of collective implementation depends upon the number and kind of GPUs, and the network interconnect in the cluster. You can specify them in the following way:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy(
tf.distribute.experimental.CollectiveCommunication.NCCL)
###Output
_____no_output_____
###Markdown
One of the key differences to get multi worker training going, as compared to multi-GPU training, is the multi-worker setup. "TF_CONFIG" environment variable is the standard way in TensorFlow to specify the cluster configuration to each worker that is part of the cluster. See section on ["TF_CONFIG" below](TF_CONFIG) for more details on how this can be done. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. TPUStrategy`tf.distribute.experimental.TPUStrategy` lets users run their TensorFlow training on Tensor Processing Units (TPUs). TPUs are Google's specialized ASICs designed to dramatically accelerate machine learning workloads. They are available on Google Colab, the [TensorFlow Research Cloud](https://www.tensorflow.org/tfrc) and [Google Compute Engine](https://cloud.google.com/tpu).In terms of distributed training architecture, TPUStrategy is the same `MirroredStrategy` - it implements synchronous distributed training. TPUs provide their own implementation of efficient all-reduce and other collective operations across multiple TPU cores, which are used in `TPUStrategy`.Here is how you would instantiate `TPUStrategy`.Note: To run this code in Colab, you should select TPU as the Colab runtime. We will have a tutorial soon that will demonstrate how you can use TPUStrategy.```cluster_resolver = tf.distribute.cluster_resolver.TPUClusterResolver( tpu=tpu_address)tf.config.experimental_connect_to_host(cluster_resolver.master())tf.tpu.experimental.initialize_tpu_system(cluster_resolver)tpu_strategy = tf.distribute.experimental.TPUStrategy(cluster_resolver)``` `TPUClusterResolver` instance helps locate the TPUs. In Colab, you don't need to specify any arguments to it. If you want to use this for Cloud TPUs, you will need to specify the name of your TPU resource in `tpu` argument. We also need to initialize the tpu system explicitly at the start of the program. This is required before TPUs can be used for computation and should ideally be done at the beginning because it also wipes out the TPU memory so all state will be lost. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. ParameterServerStrategy`tf.distribute.experimental.ParameterServerStrategy` supports parameter servers training on multiple machines. In this setup, some machines are designated as workers and some as parameter servers. Each variable of the model is placed on one parameter server. Computation is replicated across all GPUs of all the workers.In terms of code, it looks similar to other strategies:```ps_strategy = tf.distribute.experimental.ParameterServerStrategy()``` For multi worker training, "TF_CONFIG" needs to specify the configuration of parameter servers and workers in your cluster, which you can read more about in ["TF_CONFIG" below](TF_CONFIG) below. So far we've talked about what are the different stategies available and how you can instantiate them. In the next few sections, we will talk about the different ways in which you can use them to distribute your training. We will show short code snippets in this guide and link off to full tutorials which you can run end to end. Using `tf.distribute.Strategy` with KerasWe've integrated `tf.distribute.Strategy` into `tf.keras` which is TensorFlow's implementation of the[Keras API specification](https://keras.io). `tf.keras` is a high-level API to build and train models. By integrating into `tf.keras` backend, we've made it seamless for Keras users to distribute their training written in the Keras training framework. The only things that need to change in a user's program are: (1) Create an instance of the appropriate `tf.distribute.Strategy` and (2) Move the creation and compiling of Keras model inside `strategy.scope`. We support all types of Keras models - sequential, functional and subclassed.Here is a snippet of code to do this for a very simple Keras model with one dense layer:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
model.compile(loss='mse', optimizer='sgd')
###Output
_____no_output_____
###Markdown
In this example we used `MirroredStrategy` so we can run this on a machine with multiple GPUs. `strategy.scope()` indicated which parts of the code to run distributed. Creating a model inside this scope allows us to create mirrored variables instead of regular variables. Compiling under the scope allows us to know that the user intends to train this model using this strategy. Once this is setup, you can fit your model like you would normally. `MirroredStrategy` takes care of replicating the model's training on the available GPUs, aggregating gradients etc.
###Code
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100).batch(10)
model.fit(dataset, epochs=2)
model.evaluate(dataset)
###Output
_____no_output_____
###Markdown
Here we used a `tf.data.Dataset` to provide the training and eval input. You can also use numpy arrays:
###Code
import numpy as np
inputs, targets = np.ones((100, 1)), np.ones((100, 1))
model.fit(inputs, targets, epochs=2, batch_size=10)
###Output
_____no_output_____
###Markdown
In both cases (dataset or numpy), each batch of the given input is divided equally among the multiple replicas. For instance, if using `MirroredStrategy` with 2 GPUs, each batch of size 10 will get divided among the 2 GPUs, with each receiving 5 input examples in each step. Each epoch will then train faster as you add more GPUs. Typically, you would want to increase your batch size as you add more accelerators so as to make effective use of the extra computing power. You will also need to re-tune your learning rate, depending on the model. You can use `strategy.num_replicas_in_sync` to get the number of replicas.
###Code
# Compute global batch size using number of replicas.
BATCH_SIZE_PER_REPLICA = 5
global_batch_size = (BATCH_SIZE_PER_REPLICA *
mirrored_strategy.num_replicas_in_sync)
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100)
dataset = dataset.batch(global_batch_size)
LEARNING_RATES_BY_BATCH_SIZE = {5: 0.1, 10: 0.15}
learning_rate = LEARNING_RATES_BY_BATCH_SIZE[global_batch_size]
###Output
_____no_output_____
###Markdown
What's supported now?In TF 2.0 beta release, we support training with Keras using `MirroredStrategy`, `CentralStorageStrategy` and `MultiWorkerMirroredStrategy`. Both `CentralStorageStrategy` and `MultiWorkerMirroredStrategy` are currently experimental APIs and are subject to change.Support for other strategies will be coming soon. The API and how to use will be exactly the same as above.| Training API | MirroredStrategy | TPUStrategy | MultiWorkerMirroredStrategy | CentralStorageStrategy | ParameterServerStrategy ||---------------- |--------------------- |----------------------- |----------------------------------- |----------------------------------- |--------------------------- || Keras APIs | Supported | Support planned in 2.0 RC | Experimental support | Experimental support | Support planned in post 2.0 | Examples and TutorialsHere is a list of tutorials and examples that illustrate the above integration end to end with Keras:1. Tutorial to train [MNIST](../tutorials/distribute/keras.ipynb) with `MirroredStrategy`.2. Official [ResNet50](https://github.com/tensorflow/models/blob/master/official/resnet/keras/keras_imagenet_main.py) training with ImageNet data using `MirroredStrategy`.3. [ResNet50](https://github.com/tensorflow/tpu/blob/master/models/experimental/resnet50_keras/resnet50.py) trained with Imagenet data on Cloud TPus with `TPUStrategy`. Note that this example only works with TensorFlow 1.x currently.4. [Tutorial](../tutorials/distribute/multi_worker_with_keras.ipynb) to train MNIST using `MultiWorkerMirroredStrategy`.5. [NCF](https://github.com/tensorflow/models/blob/master/official/recommendation/ncf_keras_main.py) trained using `MirroredStrategy`.2. [Transformer]( https://github.com/tensorflow/models/blob/master/official/transformer/v2/transformer_main.py) trained using `MirroredStrategy`. Using `tf.distribute.Strategy` with custom training loopsAs you've seen, using `tf.distribute.Strategy` with high level APIs is only a couple lines of code change. With a little more effort, `tf.distribute.Strategy` can also be used by other users who are not using these frameworks.TensorFlow is used for a wide variety of use cases and some users (such as researchers) require more flexibility and control over their training loops. This makes it hard for them to use the high level frameworks such as Estimator or Keras. For instance, someone using a GAN may want to take a different number of generator or discriminator steps each round. Similarly, the high level frameworks are not very suitable for Reinforcement Learning training. So these users will usually write their own training loops.For these users, we provide a core set of methods through the `tf.distribute.Strategy` classes. Using these may require minor restructuring of the code initially, but once that is done, the user should be able to switch between GPUs / TPUs / multiple machines by just changing the strategy instance.Here we will show a brief snippet illustrating this use case for a simple training example using the same Keras model as before. First, we create the model and optimizer inside the strategy's scope. This ensures that any variables created with the model and optimizer are mirrored variables.
###Code
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
optimizer = tf.keras.optimizers.SGD()
###Output
_____no_output_____
###Markdown
Next, we create the input dataset and call `tf.distribute.Strategy.experimental_distribute_dataset` to distribute the dataset based on the strategy.
###Code
with mirrored_strategy.scope():
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(1000).batch(
global_batch_size)
dist_dataset = mirrored_strategy.experimental_distribute_dataset(dataset)
###Output
_____no_output_____
###Markdown
Then, we define one step of the training. We will use `tf.GradientTape` to compute gradients and optimizer to apply those gradients to update our model's variables. To distribute this training step, we put in in a function `step_fn` and pass it to `tf.distrbute.Strategy.experimental_run_v2` along with the dataset inputs that we get from `dist_dataset` created before:
###Code
@tf.function
def train_step(dist_inputs):
def step_fn(inputs):
features, labels = inputs
with tf.GradientTape() as tape:
logits = model(features)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(
logits=logits, labels=labels)
loss = tf.reduce_sum(cross_entropy) * (1.0 / global_batch_size)
grads = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(list(zip(grads, model.trainable_variables)))
return cross_entropy
per_example_losses = mirrored_strategy.experimental_run_v2(
step_fn, args=(dist_inputs,))
mean_loss = mirrored_strategy.reduce(
tf.distribute.ReduceOp.MEAN, per_example_losses, axis=0)
return mean_loss
###Output
_____no_output_____
###Markdown
A few other things to note in the code above:1. We used `tf.nn.softmax_cross_entropy_with_logits` to compute the loss. And then we scaled the total loss by the global batch size. This is important because all the replicas are training in sync and number of examples in each step of training is the global batch. So the loss needs to be divided by the global batch size and not by the replica (local) batch size.2. We used the `tf.distribute.Strategy.reduce` API to aggregate the results returned by `tf.distribute.Strategy.experimental_run_v2`. `tf.distribute.Strategy.experimental_run_v2` returns results from each local replica in the strategy, and there are multiple ways to consume this result. You can `reduce` them to get an aggregated value. You can also do `tf.distribute.Strategy.experimental_local_results` to get the list of values contained in the result, one per local replica.3. When `apply_gradients` is called within a distribution strategy scope, its behavior is modified. Specifically, before applying gradients on each parallel instance during synchronous training, it performs a sum-over-all-replicas of the gradients. Finally, once we have defined the training step, we can iterate over `dist_dataset` and run the training in a loop:
###Code
with mirrored_strategy.scope():
for inputs in dist_dataset:
print(train_step(inputs))
###Output
_____no_output_____
###Markdown
In the example above, we iterated over the `dist_dataset` to provide input to your training. We also provide the `tf.distribute.Strategy.make_experimental_numpy_dataset` to support numpy inputs. You can use this API to create a dataset before calling `tf.distribute.Strategy.experimental_distribute_dataset`.Another way of iterating over your data is to explicitly use iterators. You may want to do this when you want to run for a given number of steps as opposed to iterating over the entire dataset.The above iteration would now be modified to first create an iterator and then explicity call `next` on it to get the input data.
###Code
with mirrored_strategy.scope():
iterator = iter(dist_dataset)
for _ in range(10):
print(train_step(next(iterator)))
###Output
_____no_output_____
###Markdown
This covers the simplest case of using `tf.distribute.Strategy` API to distribute custom training loops. We are in the process of improving these APIs. Since this use case requires more work on the part of the user, we will be publishing a separate detailed guide in the future. What's supported now?In TF 2.0 beta release, we support training with custom training loops using `MirroredStrategy` as shown above and `TPUStrategy`. `MultiWorkerMirorredStrategy` support will be coming in the future.| Training API | MirroredStrategy | TPUStrategy | MultiWorkerMirroredStrategy | CentralStorageStrategy | ParameterServerStrategy ||:----------------------- |:------------------- |:------------------- |:----------------------------- |:------------------------ |:------------------------- || Custom Training Loop | Supported | Supported | Support planned in 2.0 RC | Support planned in 2.0 RC | No support yet | Examples and TutorialsHere are some examples for using distribution strategy with custom training loops:1. [Tutorial](../tutorials/distribute/training_loops.ipynb) to train MNIST using `MirroredStrategy`.2. [DenseNet](https://github.com/tensorflow/examples/blob/master/tensorflow_examples/models/densenet/distributed_train.py) example using `MirroredStrategy`.1. [BERT](https://github.com/tensorflow/models/blob/master/official/bert/run_classifier.py) example trained using `MirroredStrategy` and `TPUStrategy`.This example is particularly helpful for understanding how to load from a checkpoint and generate periodic checkpoints during distributed training etc.2. [NCF](https://github.com/tensorflow/models/blob/master/official/recommendation/ncf_keras_main.py) example trained using `MirroredStrategy` that can be enabled using the `keras_use_ctl` flag.3. [NMT](https://github.com/tensorflow/examples/blob/master/tensorflow_examples/models/nmt_with_attention/distributed_train.py) example trained using `MirroredStrategy`. Using `tf.distribute.Strategy` with Estimator`tf.estimator` is a distributed training TensorFlow API that originally supported the async parameter server approach. Like with Keras, we've integrated `tf.distribute.Strategy` into `tf.Estimator` so that a user who is using Estimator for their training can easily change their training is distributed with very few changes to your their code. With this, estimator users can now do synchronous distributed training on multiple GPUs and multiple workers, as well as use TPUs. This support in estimator is, however, limited. See [What's supported now](estimator_support) section below for more details.The usage of `tf.distribute.Strategy` with Estimator is slightly different than the Keras case. Instead of using `strategy.scope`, now we pass the strategy object into the [`RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig) for the Estimator.Here is a snippet of code that shows this with a premade estimator `LinearRegressor` and `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
config = tf.estimator.RunConfig(
train_distribute=mirrored_strategy, eval_distribute=mirrored_strategy)
regressor = tf.estimator.LinearRegressor(
feature_columns=[tf.feature_column.numeric_column('feats')],
optimizer='SGD',
config=config)
###Output
_____no_output_____
###Markdown
We use a premade Estimator here, but the same code works with a custom Estimator as well. `train_distribute` determines how training will be distributed, and `eval_distribute` determines how evaluation will be distributed. This is another difference from Keras where we use the same strategy for both training and eval.Now we can train and evaluate this Estimator with an input function:
###Code
def input_fn():
dataset = tf.data.Dataset.from_tensors(({"feats":[1.]}, [1.]))
return dataset.repeat(1000).batch(10)
regressor.train(input_fn=input_fn, steps=10)
regressor.evaluate(input_fn=input_fn, steps=10)
###Output
_____no_output_____
###Markdown
Then, we define one step of the training. We will use `tf.GradientTape` to compute gradients and optimizer to apply those gradients to update our model's variables. To distribute this training step, we put in in a function `step_fn` and pass it to `strategy.experimental_run` along with the iterator created before:
###Code
@tf.function
def train_step():
def step_fn(inputs):
features, labels = inputs
with tf.GradientTape() as tape:
logits = model(features)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(
logits=logits, labels=labels)
loss = tf.reduce_sum(cross_entropy) * (1.0 / global_batch_size)
grads = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(list(zip(grads, model.trainable_variables)))
return loss
per_replica_losses = mirrored_strategy.experimental_run(
step_fn, input_iterator)
mean_loss = mirrored_strategy.reduce(
tf.distribute.ReduceOp.SUM, per_replica_losses, axis=None)
return mean_loss
###Output
_____no_output_____
###Markdown
A few other things to note in the code above:1. We used `tf.nn.softmax_cross_entropy_with_logits` to compute the loss. And then we scaled the total loss by the global batch size. This is important because all the replicas are training in sync and number of examples in each step of training is the global batch. So the loss needs to be divided by the global batch size and not by the replica (local) batch size.2. We used the `strategy.reduce` API to aggregate the results returned by `experimental_run`. `experimental_run` returns results from each local replica in the strategy, and there are multiple ways to consume this result. You can `reduce` them to get an aggregated value. You can also do `strategy.unwrap(results)`* to get the list of values contained in the result, one per local replica.3. When `apply_gradients` is called within a distribution strategy scope, its behavior is modified. Specifically, before applying gradients on each parallel instance during synchronous training, it performs a sum-over-all-replicas of the gradients.Note: These APIs are [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. Finally, once we have defined the training step, we can initialize the iterator and run the training in a loop:
###Code
with mirrored_strategy.scope():
input_iterator.initialize()
for _ in range(10):
print(train_step())
###Output
_____no_output_____
###Markdown
Copyright 2018 The TensorFlow Authors.
###Code
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###Output
_____no_output_____
###Markdown
Distributed training in TensorFlow View on TensorFlow.org Run in Google Colab View source on GitHub Overview`tf.distribute.Strategy` is a TensorFlow API to distribute training across multiple GPUs, multiple machines or TPUs. Using this API, users can distribute their existing models and training code with minimal code changes.`tf.distribute.Strategy` has been designed with these key goals in mind:* Easy to use and support multiple user segments, including researchers, ML engineers, etc.* Provide good performance out of the box.* Easy switching between strategies.`tf.distribute.Strategy` can be used with TensorFlow's high level APIs, [tf.keras](https://www.tensorflow.org/guide/keras) and [tf.estimator](https://www.tensorflow.org/guide/estimators), with just a couple of lines of code change. It also provides an API that can be used to distribute custom training loops (and in general any computation using TensorFlow).In TensorFlow 2.0, users can execute their programs eagerly, or in a graph using [`tf.function`](../tutorials/eager/tf_function.ipynb). `tf.distribute.Strategy` intends to support both these modes of execution. Note that we may talk about training most of the time in this guide, but this API can also be used for distributing evaluation and prediction on different platforms.As you will see in a bit, very few changes are needed to use `tf.distribute.Strategy` with your code. This is because we have changed the underlying components of TensorFlow to become strategy-aware. This includes variables, layers, models, optimizers, metrics, summaries, and checkpoints.In this guide, we will talk about various types of strategies and how one can use them in a different situations.
###Code
# Import TensorFlow
from __future__ import absolute_import, division, print_function, unicode_literals
!pip install tf-nightly-gpu-2.0-preview
import tensorflow as tf
###Output
_____no_output_____
###Markdown
Types of strategies`tf.distribute.Strategy` intends to cover a number of use cases along different axes. Some of these combinations are currently supported and others will be added in the future. Some of these axes are:* Synchronous vs asynchronous training: These are two common ways of distributing training with data parallelism. In sync training, all workers train over different slices of input data in sync, and aggregating gradients at each step. In async training, all workers are independently training over the input data and updating variables asynchronously. Typically sync training is supported via all-reduce and async through parameter server architecture.* Hardware platform: Users may want to scale their training onto multiple GPUs on one machine, or multiple machines in a network (with 0 or more GPUs each), or on Cloud TPUs.In order to support these use cases, we have 4 strategies available. In the next section we will talk about which of these are supported in which scenarios in TF 2.0-alpha at this time. MirroredStrategy`tf.distribute.MirroredStrategy` supports synchronous distributed training on multiple GPUs on one machine. It creates one replica per GPU device. Each variable in the model is mirrored across all the replicas. Together, these variables form a single conceptual variable called `MirroredVariable`. These variables are kept in sync with each other by applying identical updates.Efficient all-reduce algorithms are used to communicate the variable updates across the devices.All-reduce aggregates tensors across all the devices by adding them up, and makes them available on each device.It’s a fused algorithm that is very efficient and can reduce the overhead of synchronization significantly. There are many all-reduce algorithms and implementations available, depending on the type of communication available between devices. By default, it uses NVIDIA NCCL as the all-reduce implementation. The user can also choose between a few other options we provide, or write their own.Here is the simplest way of creating `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
###Output
_____no_output_____
###Markdown
This will create a `MirroredStrategy` instance which will use all the GPUs that are visible to TensorFlow, and use NCCL as the cross device communication.If you wish to use only some of the GPUs on your machine, you can do so like this:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(devices=["/gpu:0", "/gpu:1"])
###Output
_____no_output_____
###Markdown
If you wish to override the cross device communication, you can do so using the `cross_device_ops` argument by supplying an instance of `tf.distribute.CrossDeviceOps`. Currently we provide `tf.distribute.HierarchicalCopyAllReduce` and `tf.distribute.ReductionToOneDevice` as 2 other options other than `tf.distribute.NcclAllReduce` which is the default.
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(
cross_device_ops=tf.distribute.HierarchicalCopyAllReduce())
###Output
_____no_output_____
###Markdown
CentralStorageStrategy`tf.distribute.experimental.CentralStorageStrategy` does synchronous training as well. Variables are not mirrored, instead they are placed on the CPU and operations are replicated across all local GPUs. If there is only one GPU, all variables and operations will be placed on that GPU.Create a `CentralStorageStrategy` by:
###Code
central_storage_strategy = tf.distribute.experimental.CentralStorageStrategy()
###Output
_____no_output_____
###Markdown
This will create a `CentralStorageStrategy` instance which will use all visible GPUs and CPU. Update to variables on replicas will be aggragated before being applied to variables. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. MultiWorkerMirroredStrategy`tf.distribute.experimental.MultiWorkerMirroredStrategy` is very similar to `MirroredStrategy`. It implements synchronous distributed training across multiple workers, each with potentially multiple GPUs. Similar to `MirroredStrategy`, it creates copies of all variables in the model on each device across all workers.It uses [CollectiveOps](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/collective_ops.py) as the multi-worker all-reduce communication method used to keep variables in sync. A collective op is a single op in the TensorFlow graph which can automatically choose an all-reduce algorithm in the TensorFlow runtime according to hardware, network topology and tensor sizes.It also implements additional performance optimizations. For example, it includes a static optimization that converts multiple all-reductions on small tensors into fewer all-reductions on larger tensors. In addition, we are designing it to have a plugin architecture - so that in the future, users will be able to plugin algorithms that are better tuned for their hardware. Note that collective ops also implement other collective operations such as broadcast and all-gather.Here is the simplest way of creating `MultiWorkerMirroredStrategy`:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()
###Output
_____no_output_____
###Markdown
`MultiWorkerMirroredStrategy` currently allows you to choose between two different implementations of collective ops. `CollectiveCommunication.RING` implements ring-based collectives using gRPC as the communication layer. `CollectiveCommunication.NCCL` uses [Nvidia's NCCL](https://developer.nvidia.com/nccl) to implement collectives. `CollectiveCommunication.AUTO` defers the choice to the runtime. The best choice of collective implementation depends upon the number and kind of GPUs, and the network interconnect in the cluster. You can specify them like so:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy(
tf.distribute.experimental.CollectiveCommunication.NCCL)
###Output
_____no_output_____
###Markdown
One of the key differences to get multi worker training going, as compared to multi-GPU training, is the multi-worker setup. "TF_CONFIG" environment variable is the standard way in TensorFlow to specify the cluster configuration to each worker that is part of the cluster. See section on ["TF_CONFIG" below](TF_CONFIG) for more details on how this can be done. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. TPUStrategy`tf.distribute.experimental.TPUStrategy` lets users run their TensorFlow training on Tensor Processing Units (TPUs). TPUs are Google's specialized ASICs designed to dramatically accelerate machine learning workloads. They are available on Google Colab, the [TensorFlow Research Cloud](https://www.tensorflow.org/tfrc) and [Google Compute Engine](https://cloud.google.com/tpu).In terms of distributed training architecture, TPUStrategy is the same `MirroredStrategy` - it implements synchronous distributed training. TPUs provide their own implementation of efficient all-reduce and other collective operations across multiple TPU cores, which are used in `TPUStrategy`.Here is how you would instantiate `TPUStrategy`.Note: To run this code in Colab, you should select TPU as the Colab runtime. See [Using TPUs]( tpu.ipynb) guide for a runnable version.```resolver = tf.distribute.cluster_resolver.TPUClusterResolver()tf.tpu.experimental.initialize_tpu_system(resolver)tpu_strategy = tf.distribute.experimental.TPUStrategy(resolver)``` `TPUClusterResolver` instance helps locate the TPUs. In Colab, you don't need to specify any arguments to it. If you want to use this for Cloud TPUs, you will need to specify the name of your TPU resource in `tpu` argument. We also need to initialize the tpu system explicitly at the start of the program. This is required before TPUs can be used for computation and should ideally be done at the beginning because it also wipes out the TPU memory so all state will be lost. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. ParameterServerStrategy`tf.distribute.experimental.ParameterServerStrategy` supports parameter servers training on multiple machines. In this setup, some machines are designated as workers and some as parameter servers. Each variable of the model is placed on one parameter server. Computation is replicated across all GPUs of the all the workers.In terms of code, it looks similar to other strategies:```ps_strategy = tf.distribute.experimental.ParameterServerStrategy()``` For multi worker training, "TF_CONFIG" needs to specify the configuration of parameter servers and workers in your cluster, which you can read more about in ["TF_CONFIG" below](TF_CONFIG) below. So far we've talked about what are the different stategies available and how you can instantiate them. In the next few sections, we will talk about the different ways in which you can use them to distribute your training. We will show short code snippets in this guide and link off to full tutorials which you can run end to end. Using `tf.distribute.Strategy` with KerasWe've integrated `tf.distribute.Strategy` into `tf.keras` which is TensorFlow's implementation of the[Keras API specification](https://keras.io). `tf.keras` is a high-level API to build and train models. By integrating into `tf.keras` backend, we've made it seamless for Keras users to distribute their training written in the Keras training framework. The only things that need to change in a user's program are: (1) Create an instance of the appropriate `tf.distribute.Strategy` and (2) Move the creation and compiling of Keras model inside `strategy.scope`.Here is a snippet of code to do this for a very simple Keras model with one dense layer:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
model.compile(loss='mse', optimizer='sgd')
###Output
_____no_output_____
###Markdown
In this example we used `MirroredStrategy` so we can run this on a machine with multiple GPUs. `strategy.scope()` indicated which parts of the code to run distributed. Creating a model inside this scope allows us to create mirrored variables instead of regular variables. Compiling under the scope allows us to know that the user intends to train this model using this strategy. Once this is setup, you can fit your model like you would normally. `MirroredStrategy` takes care of replicating the model's training on the available GPUs, aggregating gradients etc.
###Code
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100).batch(10)
model.fit(dataset, epochs=2)
model.evaluate(dataset)
###Output
_____no_output_____
###Markdown
Here we used a `tf.data.Dataset` to provide the training and eval input. You can also use numpy arrays:
###Code
import numpy as np
inputs, targets = np.ones((100, 1)), np.ones((100, 1))
model.fit(inputs, targets, epochs=2, batch_size=10)
###Output
_____no_output_____
###Markdown
In both cases (dataset or numpy), each batch of the given input is divided equally among the multiple replicas. For instance, if using `MirroredStrategy` with 2 GPUs, each batch of size 10 will get divided among the 2 GPUs, with each receiving 5 input examples in each step. Each epoch will then train faster as you add more GPUs. Typically, you would want to increase your batch size as you add more accelerators so as to make effective use of the extra computing power. You will also need to re-tune your learning rate, depending on the model. You can use `strategy.num_replicas_in_sync` to get the number of replicas.
###Code
# Compute global batch size using number of replicas.
BATCH_SIZE_PER_REPLICA = 5
global_batch_size = (BATCH_SIZE_PER_REPLICA *
mirrored_strategy.num_replicas_in_sync)
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100)
dataset = dataset.batch(global_batch_size)
LEARNING_RATES_BY_BATCH_SIZE = {5: 0.1, 10: 0.15}
learning_rate = LEARNING_RATES_BY_BATCH_SIZE[global_batch_size]
###Output
_____no_output_____
###Markdown
What's supported now?In TF 2.0 alpha release, we support training with Keras using `MirroredStrategy`, as well as one machine parameter server using `ParameterServerStrategy`.Support for other strategies will be coming soon. The API and how to use will be exactly the same as above. If you wish to use the other strategies like `TPUStrategy` or `MultiWorkerMirorredStrategy` in Keras in TF 2.0, you can currently do so by disabling eager execution (`tf.compat.v1.disable_eager_execution()`). Examples and TutorialsHere is a list of tutorials and examples that illustrate the above integration end to end with Keras:1. [Tutorial](../tutorials/distribute/keras.ipynb) to train MNIST with `MirroredStrategy`.2. Official [ResNet50](https://github.com/tensorflow/models/blob/master/official/resnet/keras/keras_imagenet_main.py) training with ImageNet data using `MirroredStrategy`.3. [ResNet50](https://github.com/tensorflow/tpu/blob/master/models/experimental/resnet50_keras/resnet50.py) trained with Imagenet data on Cloud TPus with `TPUStrategy`. Note that this example only works with TensorFlow 1.x currently. Using `tf.distribute.Strategy` with Estimator`tf.estimator` is a distributed training TensorFlow API that originally supported the async parameter server approach. Like with Keras, we've integrated `tf.distribute.Strategy` into `tf.Estimator` so that a user who is using Estimator for their training can easily change their training is distributed with very few changes to your their code. With this, estimator users can now do synchronous distributed training on multiple GPUs and multiple workers, as well as use TPUs.The usage of `tf.distribute.Strategy` with Estimator is slightly different than the Keras case. Instead of using `strategy.scope`, now we pass the strategy object into the [`RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig) for the Estimator.Here is a snippet of code that shows this with a premade estimator `LinearRegressor` and `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
config = tf.estimator.RunConfig(
train_distribute=mirrored_strategy, eval_distribute=mirrored_strategy)
regressor = tf.estimator.LinearRegressor(
feature_columns=[tf.feature_column.numeric_column('feats')],
optimizer='SGD',
config=config)
###Output
_____no_output_____
###Markdown
We use a premade Estimator here, but the same code works with a custom Estimator as well. `train_distribute` determines how training will be distributed, and `eval_distribute` determines how evaluation will be distributed. This is another difference from Keras where we use the same strategy for both training and eval.Now we can train and evaluate this Estimator with an input function:
###Code
def input_fn():
dataset = tf.data.Dataset.from_tensors(({"feats":[1.]}, [1.]))
return dataset.repeat(1000).batch(10)
regressor.train(input_fn=input_fn, steps=10)
regressor.evaluate(input_fn=input_fn, steps=10)
###Output
_____no_output_____
###Markdown
Another difference to highlight here between Estimator and Keras is the input handling. In Keras, we mentioned that each batch of the dataset is split across the multiple replicas. In Estimator, however, the user provides an `input_fn` and have full control over how they want their data to be distributed across workers and devices. We do not do automatic splitting of batch, nor automatically shard the data across different workers. The provided `input_fn` is called once per worker, thus giving one dataset per worker. Then one batch from that dataset is fed to one replica on that worker, thereby consuming N batches for N replicas on 1 worker. In other words, the dataset returned by the `input_fn` should provide batches of size `PER_REPLICA_BATCH_SIZE`. And the global batch size for a step can be obtained as `PER_REPLICA_BATCH_SIZE * strategy.num_replicas_in_sync`. When doing multi worker training, users will also want to either split their data across the workers, or shuffle with a random seed on each. You can see an example of how to do this in the [Multi-worker Training with Estimator](../tutorials/distribute/multi_worker_with_estimator.ipynb). We showed an example of using `MirroredStrategy` with Estimator. You can also use `TPUStrategy` with Estimator as well, in the exact same way:```config = tf.estimator.RunConfig( train_distribute=tpu_strategy, eval_distribute=tpu_strategy)``` And similarly, you can use multi worker and parameter server strategies as well. The code remains the same, but you need to use `tf.estimator.train_and_evaluate`, and set "TF_CONFIG" environment variables for each binary running in your cluster. What's supported now?In TF 2.0 alpha release, we support training with Estimator using all strategies. Examples and TutorialsHere are some examples that show end to end usage of various strategies with Estimator:1. [Multi-worker Training with Estimator](../tutorials/distribute/multi_worker_with_estimator.ipynb) to train MNIST with multiple workers using `MultiWorkerMirroredStrategy`.2. [End to end example](https://github.com/tensorflow/ecosystem/tree/master/distribution_strategy) for multi worker training in tensorflow/ecosystem using Kuberentes templates. This example starts with a Keras model and converts it to an Estimator using the `tf.keras.estimator.model_to_estimator` API.3. Official [ResNet50](https://github.com/tensorflow/models/blob/master/official/resnet/imagenet_main.py) model, which can be trained using either `MirroredStrategy` or `MultiWorkerMirroredStrategy`.4. [ResNet50](https://github.com/tensorflow/tpu/blob/master/models/experimental/distribution_strategy/resnet_estimator.py) example with TPUStrategy. Using `tf.distribute.Strategy` with custom training loopsAs you've seen, using `tf.distribute.Strategy` with high level APIs is only a couple lines of code change. With a little more effort, `tf.distribute.Strategy` can also be used by other users who are not using these frameworks.TensorFlow is used for a wide variety of use cases and some users (such as researchers) require more flexibility and control over their training loops. This makes it hard for them to use the high level frameworks such as Estimator or Keras. For instance, someone using a GAN may want to take a different number of generator or discriminator steps each round. Similarly, the high level frameworks are not very suitable for Reinforcement Learning training. So these users will usually write their own training loops.For these users, we provide a core set of methods through the `tf.distribute.Strategy` classes. Using these may require minor restructuring of the code initially, but once that is done, the user should be able to switch between GPUs / TPUs / multiple machines by just changing the strategy instance.Here we will show a brief snippet illustrating this use case for a simple training example using the same Keras model as before.Note: These APIs are still experimental and we are improving them to make them more user friendly in TensorFlow 2.0. First, we create the model and optimizer inside the strategy's scope. This ensures that any variables created with the model and optimizer are mirrored variables.
###Code
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
optimizer = tf.keras.optimizers.SGD()
###Output
_____no_output_____
###Markdown
Next, we create the input dataset and call `tf.distribute.Strategy.experimental_distribute_dataset` to distribute the dataset based on the strategy.
###Code
with mirrored_strategy.scope():
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(1000).batch(
global_batch_size)
dist_dataset = mirrored_strategy.experimental_distribute_dataset(dataset)
###Output
_____no_output_____
###Markdown
Then, we define one step of the training. We will use `tf.GradientTape` to compute gradients and optimizer to apply those gradients to update our model's variables. To distribute this training step, we put in in a function `step_fn` and pass it to `tf.distrbute.Strategy.experimental_run_v2` along with the dataset inputs that we get from `dist_dataset` created before:
###Code
@tf.function
def train_step(dist_inputs):
def step_fn(inputs):
features, labels = inputs
with tf.GradientTape() as tape:
logits = model(features)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(
logits=logits, labels=labels)
loss = tf.reduce_sum(cross_entropy) * (1.0 / global_batch_size)
grads = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(list(zip(grads, model.trainable_variables)))
return cross_entropy
per_example_losses = mirrored_strategy.experimental_run_v2(
step_fn, args=(dist_inputs,))
mean_loss = mirrored_strategy.reduce(
tf.distribute.ReduceOp.MEAN, per_example_losses, axis=0)
return mean_loss
###Output
_____no_output_____
###Markdown
A few other things to note in the code above:1. We used `tf.nn.softmax_cross_entropy_with_logits` to compute the loss. And then we scaled the total loss by the global batch size. This is important because all the replicas are training in sync and number of examples in each step of training is the global batch. So the loss needs to be divided by the global batch size and not by the replica (local) batch size.2. We used the `tf.distribute.Strategy.reduce` API to aggregate the results returned by `tf.distribute.Strategy.experimental_run_v2`. `tf.distribute.Strategy.experimental_run_v2` returns results from each local replica in the strategy, and there are multiple ways to consume this result. You can `reduce` them to get an aggregated value. You can also do `tf.distribute.Strategy.experimental_local_results` to get the list of values contained in the result, one per local replica.3. When `apply_gradients` is called within a distribution strategy scope, its behavior is modified. Specifically, before applying gradients on each parallel instance during synchronous training, it performs a sum-over-all-replicas of the gradients. Finally, once we have defined the training step, we can iterate over `dist_dataset` and run the training in a loop:
###Code
with mirrored_strategy.scope():
for inputs in dist_dataset:
print(train_step(inputs))
###Output
_____no_output_____
###Markdown
In the example above, we iterated over the `dist_dataset` to provide input to your training. We also provide the `tf.distribute.Strategy.make_experimental_numpy_dataset` to support numpy inputs. You can use this API to create a dataset before calling `tf.distribute.Strategy.experimental_distribute_dataset`.Another way of iterating over your data is to explicitly use iterators. You may want to do this when you want to run for a given number of steps as opposed to iterating over the entire dataset.The above iteration would now be modified to first create an iterator and then explicity call `next` on it to get the input data.
###Code
with mirrored_strategy.scope():
iterator = iter(dist_dataset)
for _ in range(10):
print(train_step(next(iterator)))
###Output
_____no_output_____
###Markdown
Copyright 2018 The TensorFlow Authors.
###Code
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###Output
_____no_output_____
###Markdown
Distributed Training in TensorFlow View on TensorFlow.org Run in Google Colab View source on GitHub Overview`tf.distribute.Strategy` is a TensorFlow API to distribute trainingacross multiple GPUs, multiple machines or TPUs. Using this API, users can distribute their existing models and training code with minimal code changes.`tf.distribute.Strategy` has been designed with these key goals in mind:* Easy to use and support multiple user segments, including researchers, ML engineers, etc.* Provide good performance out of the box.* Easy switching between strategies.`tf.distribute.Strategy` can be used with TensorFlow's high level APIs, [tf.keras](https://www.tensorflow.org/guide/keras) and [tf.estimator](https://www.tensorflow.org/guide/estimators), with just a couple of lines of code change. It also provides an API that can be used to distribute custom training loops (and in general any computation using TensorFlow).In TensorFlow 2.0, users can execute their programs eagerly, or in a graph using [`tf.function`](../tutorials/eager/tf_function.ipynb). `tf.distribute.Strategy` intends to support both these modes of execution. Note that we may talk about training most of the time in this guide, but this API can also be used for distributing evaluation and prediction on different platforms.As you will see in a bit, very few changes are needed to use `tf.distribute.Strategy` with your code. This is because we have changed the underlying components of TensorFlow to become strategy-aware. This includes variables, layers, models, optimizers, metrics, summaries, and checkpoints.In this guide, we will talk about various types of strategies and how one can use them in a different situations.
###Code
# Import TensorFlow
from __future__ import absolute_import, division, print_function, unicode_literals
!pip install tf-nightly-gpu-2.0-preview
import tensorflow as tf
###Output
_____no_output_____
###Markdown
Types of strategies`tf.distribute.Strategy` intends to cover a number of use cases along different axes. Some of these combinations are currently supported and others will be added in the future. Some of these axes are:* Syncronous vs asynchronous training: These are two common ways of distributing training with data parallelism. In sync training, all workers train over different slices of input data in sync, and aggregating gradients at each step. In async training, all workers are independently training over the input data and updating variables asynchronously. Typically sync training is supported via all-reduce and async through parameter server architecture.* Hardware platform: Users may want to scale their training onto multiple GPUs on one machine, or multiple machines in a network (with 0 or more GPUs each), or on Cloud TPUs.In order to support these use cases, we have 4 strategies available. In the next section we will talk about which of these are supported in which scenarios in TF 2.0-alpha at this time. MirroredStrategy`tf.distribute.MirroredStrategy` support synchronous distributed training on multiple GPUs on one machine. It creates one replica per GPU device. Each variable in the model is mirrored across all the replicas. Together, these variables form a single conceptual variable called `MirroredVariable`. These variables are kept in sync with each other by applying identical updates.Efficient all-reduce algorithms are used to communicate the variable updates across the devices.All-reduce aggregates tensors across all the devices by adding them up, and makes them available on each device.It’s a fused algorithm that is very efficient and can reduce the overhead of synchronization significantly. There are many all-reduce algorithms and implementations available, depending on the type of communication available between devices. By default, it uses NVIDIA NCCL as the all-reduce implementation. The user can also choose between a few other options we provide, or write their own.Here is the simplest way of creating `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
###Output
_____no_output_____
###Markdown
This will create a `MirroredStrategy` instance which will use all the GPUs that are visible to TensorFlow, and use NCCL as the cross device communication.If you wish to use only some of the GPUs on your machine, you can do so like this:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(devices=["/gpu:0", "/gpu:1"])
###Output
_____no_output_____
###Markdown
If you wish to override the cross device communication, you can do so using the `cross_device_ops` argument by supplying an instance of `tf.distribute.CrossDeviceOps`. Currently we provide `tf.distribute.HierarchicalCopyAllReduce` and `tf.distribute.ReductionToOneDevice` as 2 other options other than `tf.distribute.NcclAllReduce` which is the default.
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(
cross_device_ops=tf.distribute.HierarchicalCopyAllReduce())
###Output
_____no_output_____
###Markdown
CentralStorageStrategy`tf.distribute.experimental.CentralStorageStrategy` does synchronous training as well. Variables are not mirrored, instead they are placed on the CPU and operations are replicated across all local GPUs. If there is only one GPU, all variables and operations will be placed on that GPU.Create a `CentralStorageStrategy` by:
###Code
central_storage_strategy = tf.distribute.experimental.CentralStorageStrategy()
###Output
_____no_output_____
###Markdown
This will create a `CentralStorageStrategy` instance which will use all visible GPUs and CPU. Update to variables on replicas will be aggragated before being applied to variables. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. MultiWorkerMirroredStrategy`tf.distribute.experimental.MultiWorkerMirroredStrategy` is very similar to `MirroredStrategy`. It implements synchronous distributed training across multiple workers, each with potentially multiple GPUs. Similar to `MirroredStrategy`, it creates copies of all variables in the model on each device across all workers.It uses [CollectiveOps](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/collective_ops.py) as the multi-worker all-reduce communication method used to keep variables in sync. A collective op is a single op in the TensorFlow graph which can automatically choose an all-reduce algorithm in the TensorFlow runtime according to hardware, network topology and tensor sizes.It also implements additional performance optimizations. For example, it includes a static optimization that converts multiple all-reductions on small tensors into fewer all-reductions on larger tensors. In addition, we are designing it to have a plugin architecture - so that in the future, users will be able to plugin algorithms that are better tuned for their hardware. Note that collective ops also implement other collective operations such as broadcast and all-gather.Here is the simplest way of creating `MultiWorkerMirroredStrategy`:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()
###Output
_____no_output_____
###Markdown
`MultiWorkerMirroredStrategy` currently allows you to choose between two different implementations of collective ops. `CollectiveCommunication.RING` implements ring-based collectives using gRPC as the communication layer. `CollectiveCommunication.NCCL` uses [Nvidia's NCCL](https://developer.nvidia.com/nccl) to implement collectives. `CollectiveCommunication.AUTO` defers the choice to the runtime. The best choice of collective implementation depends upon the number and kind of GPUs, and the network interconnect in the cluster. You can specify them like so:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy(
tf.distribute.experimental.CollectiveCommunication.NCCL)
###Output
_____no_output_____
###Markdown
One of the key differences to get multi worker training going, as compared to multi-GPU training, is the multi-worker setup. "TF_CONFIG" environment variable is the standard way in TensorFlow to specify the cluster configuration to each worker that is part of the cluster. See section on ["TF_CONFIG" below](TF_CONFIG) for more details on how this can be done. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. TPUStrategy`tf.distribute.experimental.TPUStrategy` lets users run their TensorFlow training on Tensor Processing Units (TPUs). TPUs are Google's specialized ASICs designed to dramatically accelerate machine learning workloads. They are available on Google Colab, the [TensorFlow Research Cloud](https://www.tensorflow.org/tfrc) and [Google Compute Engine](https://cloud.google.com/tpu).In terms of distributed training architecture, TPUStrategy is the same `MirroredStrategy` - it implements synchronous distributed training. TPUs provide their own implementation of efficient all-reduce and other collective operations across multiple TPU cores, which are used in `TPUStrategy`.Here is how you would instantiate `TPUStrategy`.Note: To run this code in Colab, you should select TPU as the Colab runtime. See [Using TPUs]( tpu.ipynb) guide for a runnable version.```resolver = tf.distribute.cluster_resolver.TPUClusterResolver()tf.tpu.experimental.initialize_tpu_system(resolver)tpu_strategy = tf.distribute.experimental.TPUStrategy(resolver)``` `TPUClusterResolver` instance helps locate the TPUs. In Colab, you don't need to specify any arguments to it. If you want to use this for Cloud TPUs, you will need to specify the name of your TPU resource in `tpu` argument. We also need to initialize the tpu system explicitly at the start of the program. This is required before TPUs can be used for computation and should ideally be done at the beginning because it also wipes out the TPU memory so all state will be lost. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. ParameterServerStrategy`tf.distribute.experimental.ParameterServerStrategy` supports parameter servers training on multiple machines. In this setup, some machines are designated as workers and some as parameter servers. Each variable of the model is placed on one parameter server. Computation is replicated across all GPUs of the all the workers.In terms of code, it looks similar to other strategies:```ps_strategy = tf.distribute.experimental.ParameterServerStrategy()``` For multi worker training, "TF_CONFIG" needs to specify the configuration of parameter servers and workers in your cluster, which you can read more about in ["TF_CONFIG" below](TF_CONFIG) below. So far we've talked about what are the different stategies available and how you can instantiate them. In the next few sections, we will talk about the different ways in which you can use them to distribute your training. We will show short code snippets in this guide and link off to full tutorials which you can run end to end. Using `tf.distribute.Strategy` with KerasWe've integrated `tf.distribute.Strategy` into `tf.keras` which is TensorFlow's implementation of the[Keras API specification](https://keras.io). `tf.keras` is a high-level API to build and train models. By integrating into `tf.keras` backend, we've made it seamless for Keras users to distribute their training written in the Keras training framework. The only things that need to change in a user's program are: (1) Create an instance of the appropriate `tf.distribute.Strategy` and (2) Move the creation and compiling of Keras model inside `strategy.scope`.Here is a snippet of code to do this for a very simple Keras model with one dense layer:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
model.compile(loss='mse', optimizer='sgd')
###Output
_____no_output_____
###Markdown
In this example we used `MirroredStrategy` so we can run this on a machine with multiple GPUs. `strategy.scope()` indicated which parts of the code to run distributed. Creating a model inside this scope allows us to create mirrored variables instead of regular variables. Compiling under the scope allows us to know that the user intends to train this model using this strategy. Once this is setup, you can fit your model like you would normally. `MirroredStrategy` takes care of replicating the model's training on the available GPUs, aggregating gradients etc.
###Code
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100).batch(10)
model.fit(dataset, epochs=2)
model.evaluate(dataset)
###Output
_____no_output_____
###Markdown
Here we used a `tf.data.Dataset` to provide the training and eval input. You can also use numpy arrays:
###Code
import numpy as np
inputs, targets = np.ones((100, 1)), np.ones((100, 1))
model.fit(inputs, targets, epochs=2, batch_size=10)
###Output
_____no_output_____
###Markdown
In both cases (dataset or numpy), each batch of the given input is divided equally among the multiple replicas. For instance, if using `MirroredStrategy` with 2 GPUs, each batch of size 10 will get divided among the 2 GPUs, with each receiving 5 input examples in each step. Each epoch will then train faster as you add more GPUs. Typically, you would want to increase your batch size as you add more accelerators so as to make effective use of the extra computing power. You will also need to re-tune your learning rate, depending on the model. You can use `strategy.num_replicas_in_sync` to get the number of replicas.
###Code
# Compute global batch size using number of replicas.
BATCH_SIZE_PER_REPLICA = 5
global_batch_size = (BATCH_SIZE_PER_REPLICA *
mirrored_strategy.num_replicas_in_sync)
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100)
dataset = dataset.batch(global_batch_size)
LEARNING_RATES_BY_BATCH_SIZE = {5: 0.1, 10: 0.15}
learning_rate = LEARNING_RATES_BY_BATCH_SIZE[global_batch_size]
###Output
_____no_output_____
###Markdown
What's supported now?In TF 2.0 alpha release, we support training with Keras using `MirroredStrategy`, as well as one machine parameter server using `ParameterServerStrategy`.Support for other strategies will be coming soon. The API and how to use will be exactly the same as above. If you wish to use the other strategies like `TPUStrategy` or `MultiWorkerMirorredStrategy` in Keras in TF 2.0, you can currently do so by disabling eager execution (`tf.compat.v1.disable_eager_execution()`). Examples and TutorialsHere is a list of tutorials and examples that illustrate the above integration end to end with Keras:1. [Tutorial](../tutorials/distribute/keras.ipynb) to train MNIST with `MirroredStrategy`.2. Official [ResNet50](https://github.com/tensorflow/models/blob/master/official/resnet/keras/keras_imagenet_main.py) training with ImageNet data using `MirroredStrategy`.3. [ResNet50](https://github.com/tensorflow/tpu/blob/master/models/experimental/resnet50_keras/resnet50.py) trained with Imagenet data on Cloud TPus with `TPUStrategy`. Note that this example only works with TensorFlow 1.x currently. Using `tf.distribute.Strategy` with Estimator`tf.estimator` is a distributed training TensorFlow API that originally supported the async parameter server approach. Like with Keras, we've integrated `tf.distribute.Strategy` into `tf.Estimator` so that a user who is using Estimator for their training can easily change their training is distributed with very few changes to your their code. With this, estimator users can now do synchronous distributed training on multiple GPUs and multiple workers, as well as use TPUs.The usage of `tf.distribute.Strategy` with Estimator is slightly different than the Keras case. Instead of using `strategy.scope`, now we pass the strategy object into the [`RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig) for the Estimator.Here is a snippet of code that shows this with a premade estimator `LinearRegressor` and `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
config = tf.estimator.RunConfig(
train_distribute=mirrored_strategy, eval_distribute=mirrored_strategy)
regressor = tf.estimator.LinearRegressor(
feature_columns=[tf.feature_column.numeric_column('feats')],
optimizer='SGD',
config=config)
###Output
_____no_output_____
###Markdown
We use a premade Estimator here, but the same code works with a custom Estimator as well. `train_distribute` determines how training will be distributed, and `eval_distribute` determines how evaluation will be distributed. This is another difference from Keras where we use the same strategy for both training and eval.Now we can train and evaluate this Estimator with an input function:
###Code
def input_fn():
dataset = tf.data.Dataset.from_tensors(({"feats":[1.]}, [1.]))
return dataset.repeat(1000).batch(10)
regressor.train(input_fn=input_fn, steps=10)
regressor.evaluate(input_fn=input_fn, steps=10)
###Output
_____no_output_____
###Markdown
Another difference to highlight here between Estimator and Keras is the input handling. In Keras, we mentioned that each batch of the dataset is split across the multiple replicas. In Estimator, however, the user provides an `input_fn` and have full control over how they want their data to be distributed across workers and devices. We do not do automatic splitting of batch, nor automatically shard the data across different workers. The provided `input_fn` is called once per worker, thus giving one dataset per worker. Then one batch from that dataset is fed to one replica on that worker, thereby consuming N batches for N replicas on 1 worker. In other words, the dataset returned by the `input_fn` should provide batches of size `PER_REPLICA_BATCH_SIZE`. And the global batch size for a step can be obtained as `PER_REPLICA_BATCH_SIZE * strategy.num_replicas_in_sync`. When doing multi worker training, users will also want to either split their data across the workers, or shuffle with a random seed on each. You can see an example of how to do this in the [multi-worker tutorial](../tutorials/distribute/multi_worker.ipynb). We showed an example of using `MirroredStrategy` with Estimator. You can also use `TPUStrategy` with Estimator as well, in the exact same way:```config = tf.estimator.RunConfig( train_distribute=tpu_strategy, eval_distribute=tpu_strategy)``` And similarly, you can use multi worker and parameter server strategies as well. The code remains the same, but you need to use `tf.estimator.train_and_evaluate`, and set "TF_CONFIG" environment variables for each binary running in your cluster. What's supported now?In TF 2.0 alpha release, we support training with Estimator using all strategies. Examples and TutorialsHere are some examples that show end to end usage of various strategies with Estimator:1. [Tutorial](../tutorials/distribute/multi_worker.ipynb) to train MNIST with multiple workers using `MultiWorkerMirroredStrategy`.2. [End to end example](https://github.com/tensorflow/ecosystem/tree/master/distribution_strategy) for multi worker training in tensorflow/ecosystem using Kuberentes templates. This example starts with a Keras model and converts it to an Estimator using the `tf.keras.estimator.model_to_estimator` API.3. Official [ResNet50](https://github.com/tensorflow/models/blob/master/official/resnet/imagenet_main.py) model, which can be trained using either `MirroredStrategy` or `MultiWorkerMirroredStrategy`.4. [ResNet50](https://github.com/tensorflow/tpu/blob/master/models/experimental/distribution_strategy/resnet_estimator.py) example with TPUStrategy. Using `tf.distribute.Strategy` with custom training loopsAs you've seen, using `tf.distribute.Strategy` with high level APIs is only a couple lines of code change. With a little more effort, `tf.distribute.Strategy` can also be used by other users who are not using these frameworks.TensorFlow is used for a wide variety of use cases and some users (such as researchers) require more flexibility and control over their training loops. This makes it hard for them to use the high level frameworks such as Estimator or Keras. For instance, someone using a GAN may want to take a different number of generator or discriminator steps each round. Similarly, the high level frameworks are not very suitable for Reinforcement Learning training. So these users will usually write their own training loops.For these users, we provide a core set of methods through the `tf.distribute.Strategy` classes. Using these may require minor restructuring of the code initially, but once that is done, the user should be able to switch between GPUs / TPUs / multiple machines by just changing the strategy instance.Here we will show a brief snippet illustrating this use case for a simple training example using the same Keras model as before.Note: These APIs are still experimental and we are improving them to make them more user friendly in TensorFlow 2.0. First, we create the model and optimizer inside the strategy's scope. This ensures that any variables created with the model and optimizer are mirrored variables.
###Code
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
optimizer = tf.keras.optimizers.SGD()
###Output
_____no_output_____
###Markdown
Next, we create the input dataset and call `tf.distribute.Strategy.experimental_distribute_dataset` to distribute the dataset based on the strategy.
###Code
with mirrored_strategy.scope():
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(1000).batch(
global_batch_size)
dist_dataset = mirrored_strategy.experimental_distribute_dataset(dataset)
###Output
_____no_output_____
###Markdown
Then, we define one step of the training. We will use `tf.GradientTape` to compute gradients and optimizer to apply those gradients to update our model's variables. To distribute this training step, we put in in a function `step_fn` and pass it to `tf.distrbute.Strategy.experimental_run_v2` along with the dataset inputs that we get from `dist_dataset` created before:
###Code
@tf.function
def train_step(dist_inputs):
def step_fn(inputs):
features, labels = inputs
with tf.GradientTape() as tape:
logits = model(features)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(
logits=logits, labels=labels)
loss = tf.reduce_sum(cross_entropy) * (1.0 / global_batch_size)
grads = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(list(zip(grads, model.trainable_variables)))
return loss
per_replica_losses = mirrored_strategy.experimental_run_v2(
step_fn, args=(dist_inputs,))
mean_loss = mirrored_strategy.reduce(
tf.distribute.ReduceOp.SUM, per_replica_losses, axis=None)
return mean_loss
###Output
_____no_output_____
###Markdown
A few other things to note in the code above:1. We used `tf.nn.softmax_cross_entropy_with_logits` to compute the loss. And then we scaled the total loss by the global batch size. This is important because all the replicas are training in sync and number of examples in each step of training is the global batch. So the loss needs to be divided by the global batch size and not by the replica (local) batch size.2. We used the `tf.distribute.Strategy.reduce` API to aggregate the results returned by `tf.distribute.Strategy.experimental_run_v2`. `tf.distribute.Strategy.experimental_run_v2` returns results from each local replica in the strategy, and there are multiple ways to consume this result. You can `reduce` them to get an aggregated value. You can also do `tf.distribute.Strategy.experimental_local_results` to get the list of values contained in the result, one per local replica.3. When `apply_gradients` is called within a distribution strategy scope, its behavior is modified. Specifically, before applying gradients on each parallel instance during synchronous training, it performs a sum-over-all-replicas of the gradients. Finally, once we have defined the training step, we can iterate over `dist_dataset` and run the training in a loop:
###Code
with mirrored_strategy.scope():
for inputs in dist_dataset:
print(train_step(inputs))
###Output
_____no_output_____
###Markdown
In the example above, we iterated over the `dist_dataset` to provide input to your training. We also provide the `tf.distribute.Strategy.make_experimental_numpy_dataset` to support numpy inputs. You can use this API to create a dataset before calling `tf.distribute.Strategy.experimental_distribute_dataset`.Another way of iterating over your data is to explicitly use iterators. You may want to do this when you want to run for a given number of steps as opposed to iterating over the entire dataset.The above iteration would now be modified to first create an iterator and then explicity call `next` on it to get the input data.
###Code
with mirrored_strategy.scope():
iterator = iter(dist_dataset)
for _ in range(10):
print(train_step(next(iterator)))
###Output
_____no_output_____
###Markdown
Copyright 2018 The TensorFlow Authors.
###Code
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###Output
_____no_output_____
###Markdown
Distributed Training in TensorFlow View on TensorFlow.org Run in Google Colab View source on GitHub Overview`tf.distribute.Strategy` is a TensorFlow API to distribute trainingacross multiple GPUs, multiple machines or TPUs. Using this API, users can distribute their existing models and training code with minimal code changes.`tf.distribute.Strategy` has been designed with these key goals in mind:* Easy to use and support multiple user segments, including researchers, ML engineers, etc.* Provide good performance out of the box.* Easy switching between strategies.`tf.distribute.Strategy` can be used with TensorFlow's high level APIs, [tf.keras](https://www.tensorflow.org/guide/keras) and [tf.estimator](https://www.tensorflow.org/guide/estimators), with just a couple of lines of code change. It also provides an API that can be used to distribute custom training loops (and in general any computation using TensorFlow).In TensorFlow 2.0, users can execute their programs eagerly, or in a graph using [`tf.function`](../tutorials/eager/tf_function.ipynb). `tf.distribute.Strategy` intends to support both these modes of execution. Note that we may talk about training most of the time in this guide, but this API can also be used for distributing evaluation and prediction on different platforms.As you will see in a bit, very few changes are needed to use `tf.distribute.Strategy` with your code. This is because we have changed the underlying components of TensorFlow to become strategy-aware. This includes variables, layers, models, optimizers, metrics, summaries, and checkpoints. In this guide, we will talk about various types of strategies and how one can use them in a different situations.
###Code
# Import TensorFlow
from __future__ import absolute_import, division, print_function, unicode_literals
!pip install tensorflow-gpu==2.0.0-alpha0
import tensorflow as tf
###Output
_____no_output_____
###Markdown
Types of strategies`tf.distribute.Strategy` intends to cover a number of use cases along different axes. Some of these combinations are currently supported and others will be added in the future. Some of these axes are:* Syncronous vs asynchronous training: These are two common ways of distributing training with data parallelism. In sync training, all workers train over different slices of input data in sync, and aggregating gradients at each step. In async training, all workers are independently training over the input data and updating variables asynchronously. Typically sync training is supported via all-reduce and async through parameter server architecture.* Hardware platform: Users may want to scale their training onto multiple GPUs on one machine, or multiple machines in a network (with 0 or more GPUs each), or on Cloud TPUs.In order to support these use cases, we have 4 strategies available. In the next section we will talk about which of these are supported in which scenarios in TF 2.0-alpha at this time. MirroredStrategy`tf.distribute.MirroredStrategy` support synchronous distributed training on multiple GPUs on one machine. It creates one replica per GPU device. Each variable in the model is mirrored across all the replicas. Together, these variables form a single conceptual variable called `MirroredVariable`. These variables are kept in sync with each other by applying identical updates.Efficient all-reduce algorithms are used to communicate the variable updates across the devices.All-reduce aggregates tensors across all the devices by adding them up, and makes them available on each device.It’s a fused algorithm that is very efficient and can reduce the overhead of synchronization significantly. There are many all-reduce algorithms and implementations available, depending on the type of communication available between devices. By default, it uses NVIDIA NCCL as the all-reduce implementation. The user can also choose between a few other options we provide, or write their own.Here is the simplest way of creating `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
###Output
_____no_output_____
###Markdown
This will create a `MirroredStrategy` instance which will use all the GPUs that are visible to TensorFlow, and use NCCL as the cross device communication.If you wish to use only some of the GPUs on your machine, you can do so like this:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(devices=["/gpu:0", "/gpu:1"])
###Output
_____no_output_____
###Markdown
If you wish to override the cross device communication, you can do so using the `cross_device_ops` argument by supplying an instance of `tf.distribute.CrossDeviceOps`. Currently we provide `tf.distribute.HierarchicalCopyAllReduce` and `tf.distribute.ReductionToOneDevice` as 2 other options other than `tf.distribute.NcclAllReduce` which is the default.
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(
cross_device_ops=tf.distribute.HierarchicalCopyAllReduce())
###Output
_____no_output_____
###Markdown
MultiWorkerMirroredStrategy`tf.distribute.experimental.MultiWorkerMirroredStrategy` is very similar to `MirroredStrategy`. It implements synchronous distributed training across multiple workers, each with potentially multiple GPUs. Similar to `MirroredStrategy`, it creates copies of all variables in the model on each device across all workers. It uses [CollectiveOps](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/collective_ops.py) as the multi-worker all-reduce communication method used to keep variables in sync. A collective op is a single op in the TensorFlow graph which can automatically choose an all-reduce algorithm in the TensorFlow runtime according to hardware, network topology and tensor sizes. It also implements additional performance optimizations. For example, it includes a static optimization that converts multiple all-reductions on small tensors into fewer all-reductions on larger tensors. In addition, we are designing it to have a plugin architecture - so that in the future, users will be able to plugin algorithms that are better tuned for their hardware. Note that collective ops also implement other collective operations such as broadcast and all-gather. Here is the simplest way of creating `MultiWorkerMirroredStrategy`:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()
###Output
_____no_output_____
###Markdown
`MultiWorkerMirroredStrategy` currently allows you to choose between two different implementations of collective ops. `CollectiveCommunication.RING` implements ring-based collectives using gRPC as the communication layer. `CollectiveCommunication.NCCL` uses [Nvidia's NCCL](https://developer.nvidia.com/nccl) to implement collectives. `CollectiveCommunication.AUTO` defers the choice to the runtime. The best choice of collective implementation depends upon the number and kind of GPUs, and the network interconnect in the cluster. You can specify them like so:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy(
tf.distribute.experimental.CollectiveCommunication.NCCL)
###Output
_____no_output_____
###Markdown
One of the key differences to get multi worker training going, as compared to multi-GPU training, is the multi-worker setup. "TF_CONFIG" environment variable is the standard way in TensorFlow to specify the cluster configuration to each worker that is part of the cluster. See section on ["TF_CONFIG" below](TF_CONFIG) for more details on how this can be done. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. TPUStrategy`tf.distribute.experimental.TPUStrategy` lets users run their TensorFlow training on Tensor Processing Units (TPUs). TPUs are Google's specialized ASICs designed to dramatically accelerate machine learning workloads. They are available on Google Colab, the [TensorFlow Research Cloud](https://www.tensorflow.org/tfrc) and [Google Compute Engine](https://cloud.google.com/tpu).In terms of distributed training architecture, TPUStrategy is the same `MirroredStrategy` - it implements synchronous distributed training. TPUs provide their own implementation of efficient all-reduce and other collective operations across multiple TPU cores, which are used in `TPUStrategy`. Here is how you would instantiate `TPUStrategy`.Note: To run this code in Colab, you should select TPU as the Colab runtime. See [Using TPUs]( tpu.ipynb) guide for a runnable version.```resolver = tf.distribute.cluster_resolver.TPUClusterResolver()tf.tpu.experimental.initialize_tpu_system(resolver)tpu_strategy = tf.distribute.experimental.TPUStrategy(resolver)``` `TPUClusterResolver` instance helps locate the TPUs. In Colab, you don't need to specify any arguments to it. If you want to use this for Cloud TPUs, you will need to specify the name of your TPU resource in `tpu` argument. We also need to initialize the tpu system explicitly at the start of the program. This is required before TPUs can be used for computation and should ideally be done at the beginning because it also wipes out the TPU memory so all state will be lost. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. ParameterServerStrategy`tf.distribute.experimental.ParameterServerStrategy` supports parameter servers training. It can be used either for multi-GPU synchronous local training or asynchronous multi-machine training. When used to train locally on one machine, variables are not mirrored, instead they are placed on the CPU and operations are replicated across all local GPUs. In a multi-machine setting, some machines are designated as workers and some as parameter servers. Each variable of the model is placed on one parameter server. Computation is replicated across all GPUs of the all the workers.In terms of code, it looks similar to other strategies:
###Code
ps_strategy = tf.distribute.experimental.ParameterServerStrategy()
###Output
_____no_output_____
###Markdown
For multi worker training, "TF_CONFIG" needs to specify the configuration of parameter servers and workers in your cluster, which you can read more about in ["TF_CONFIG" below](TF_CONFIG) below. So far we've talked about what are the different stategies available and how you can instantiate them. In the next few sections, we will talk about the different ways in which you can use them to distribute your training. We will show short code snippets in this guide and link off to full tutorials which you can run end to end. Using `tf.distribute.Strategy` with KerasWe've integrated `tf.distribute.Strategy` into `tf.keras` which is TensorFlow's implementation of the[Keras API specification](https://keras.io). `tf.keras` is a high-level API to build and train models. By integrating into `tf.keras` backend, we've made it seamless for Keras users to distribute their training written in the Keras training framework. The only things that need to change in a user's program are: (1) Create an instance of the appropriate `tf.distribute.Strategy` and (2) Move the creation and compiling of Keras model inside `strategy.scope`. Here is a snippet of code to do this for a very simple Keras model with one dense layer:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
model.compile(loss='mse', optimizer='sgd')
###Output
_____no_output_____
###Markdown
In this example we used `MirroredStrategy` so we can run this on a machine with multiple GPUs. `strategy.scope()` indicated which parts of the code to run distributed. Creating a model inside this scope allows us to create mirrored variables instead of regular variables. Compiling under the scope allows us to know that the user intends to train this model using this strategy. Once this is setup, you can fit your model like you would normally. `MirroredStrategy` takes care of replicating the model's training on the available GPUs, aggregating gradients etc.
###Code
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100).batch(10)
model.fit(dataset, epochs=2)
model.evaluate(dataset)
###Output
_____no_output_____
###Markdown
Here we used a `tf.data.Dataset` to provide the training and eval input. You can also use numpy arrays:
###Code
import numpy as np
inputs, targets = np.ones((100, 1)), np.ones((100, 1))
model.fit(inputs, targets, epochs=2, batch_size=10)
###Output
_____no_output_____
###Markdown
In both cases (dataset or numpy), each batch of the given input is divided equally among the multiple replicas. For instance, if using `MirroredStrategy` with 2 GPUs, each batch of size 10 will get divided among the 2 GPUs, with each receiving 5 input examples in each step. Each epoch will then train faster as you add more GPUs. Typically, you would want to increase your batch size as you add more accelerators so as to make effective use of the extra computing power. You will also need to re-tune your learning rate, depending on the model. You can use `strategy.num_replicas_in_sync` to get the number of replicas.
###Code
# Compute global batch size using number of replicas.
BATCH_SIZE_PER_REPLICA = 5
global_batch_size = (BATCH_SIZE_PER_REPLICA *
mirrored_strategy.num_replicas_in_sync)
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100)
dataset = dataset.batch(global_batch_size)
LEARNING_RATES_BY_BATCH_SIZE = {5: 0.1, 10: 0.15}
learning_rate = LEARNING_RATES_BY_BATCH_SIZE[global_batch_size]
###Output
_____no_output_____
###Markdown
What's supported now?In TF 2.0 alpha release, we support training with Keras using `MirroredStrategy`, as well as one machine parameter server using `ParameterServerStrategy`. Support for other strategies will be coming soon. The API and how to use will be exactly the same as above. If you wish to use the other strategies like `TPUStrategy` or `MultiWorkerMirorredStrategy` in Keras in TF 2.0, you can currently do so by disabling eager execution (`tf.compat.v1.disable_eager_execution()`). Another thing to note is that when using `MultiWorkerMirorredStrategy` for multiple workers with Keras, currently the user will have to explicitly shard or shuffle the data for different workers, but we will change this in the future to automatically shard the input data intelligently. Examples and TutorialsHere is a list of tutorials and examples that illustrate the above integration end to end with Keras:1. [Tutorial](../tutorials/distribute/keras.ipynb) to train MNIST with `MirroredStrategy`.2. [Tutorial](tpu.ipynb) to train Fashion MNIST with `TPUStrategy` (currently uses `disable_eager_execution`)3. Official [ResNet50](https://github.com/tensorflow/models/blob/master/official/resnet/keras/keras_imagenet_main.py) training with ImageNet data using `MirroredStrategy`.4. [ResNet50](https://github.com/tensorflow/tpu/blob/master/models/experimental/resnet50_keras/resnet50.py) trained with Imagenet data on Cloud TPus with `TPUStrategy`. Note that this example only works with TensorFlow 1.x currently. Using `tf.distribute.Strategy` with Estimator`tf.estimator` is a distributed training TensorFlow API that originally supported the async parameter server approach. Like with Keras, we've integrated `tf.distribute.Strategy` into `tf.Estimator` so that a user who is using Estimator for their training can easily change their training is distributed with very few changes to your their code. With this, estimator users can now do synchronous distributed training on multiple GPUs and multiple workers, as well as use TPUs. The usage of `tf.distribute.Strategy` with Estimator is slightly different than the Keras case. Instead of using `strategy.scope`, now we pass the strategy object into the [`RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig) for the Estimator. Here is a snippet of code that shows this with a premade estimator `LinearRegressor` and `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
config = tf.estimator.RunConfig(
train_distribute=mirrored_strategy, eval_distribute=mirrored_strategy)
regressor = tf.estimator.LinearRegressor(
feature_columns=[tf.feature_column.numeric_column('feats')],
optimizer='SGD',
config=config)
###Output
_____no_output_____
###Markdown
We use a premade Estimator here, but the same code works with a custom Estimator as well. `train_distribute` determines how training will be distributed, and `eval_distribute` determines how evaluation will be distributed. This is another difference from Keras where we use the same strategy for both training and eval. Now we can train and evaluate this Estimator with an input function:
###Code
def input_fn():
dataset = tf.data.Dataset.from_tensors(({"feats":[1.]}, [1.]))
return dataset.repeat(1000).batch(10)
regressor.train(input_fn=input_fn, steps=10)
regressor.evaluate(input_fn=input_fn, steps=10)
###Output
_____no_output_____
###Markdown
Another difference to highlight here between Estimator and Keras is the input handling. In Keras, we mentioned that each batch of the dataset is split across the multiple replicas. In Estimator, however, the user provides an `input_fn` and have full control over how they want their data to be distributed across workers and devices. We do not do automatic splitting of batch, nor automatically shard the data across different workers. The provided `input_fn` is called once per worker, thus giving one dataset per worker. Then one batch from that dataset is fed to one replica on that worker, thereby consuming N batches for N replicas on 1 worker. In other words, the dataset returned by the `input_fn` should provide batches of size `PER_REPLICA_BATCH_SIZE`. And the global batch size for a step can be obtained as `PER_REPLICA_BATCH_SIZE * strategy.num_replicas_in_sync`. When doing multi worker training, users will also want to either split their data across the workers, or shuffle with a random seed on each. You can see an example of how to do this in the [multi-worker tutorial](../tutorials/distribute/multi_worker.ipynb). We showed an example of using `MirroredStrategy` with Estimator. You can also use `TPUStrategy` with Estimator as well, in the exact same way:```config = tf.estimator.RunConfig( train_distribute=tpu_strategy, eval_distribute=tpu_strategy)``` And similarly, you can use multi worker and parameter server strategies as well. The code remains the same, but you need to use `tf.estimator.train_and_evaluate`, and set "TF_CONFIG" environment variables for each binary running in your cluster. What's supported now?In TF 2.0 alpha release, we support training with Estimator using all strategies. Examples and TutorialsHere are some examples that show end to end usage of various strategies with Estimator:1. [Tutorial]((../tutorials/distribute/multi_worker.ipynb) to train MNIST with multiple workers using `MultiWorkerMirroredStrategy`.2. [End to end example](https://github.com/tensorflow/ecosystem/tree/master/distribution_strategy) for multi worker training in tensorflow/ecosystem using Kuberentes templates. This example starts with a Keras model and converts it to an Estimator using the `tf.keras.estimator.model_to_estimator` API. 3. Official [ResNet50](https://github.com/tensorflow/models/blob/master/official/resnet/imagenet_main.py) model, which can be trained using either `MirroredStrategy` or `MultiWorkerMirroredStrategy`.4. [ResNet50](https://github.com/tensorflow/tpu/blob/master/models/experimental/distribution_strategy/resnet_estimator.py) example with TPUStrategy. Using `tf.distribute.Strategy` with custom training loopsAs you've seen, using `tf.distrbute.Strategy` with high level APIs is only a couple lines of code change. With a little more effort, `tf.distrbute.Strategy` can also be used by other users who are not using these frameworks.TensorFlow is used for a wide variety of use cases and some users (such as researchers) require more flexibility and control over their training loops. This makes it hard for them to use the high level frameworks such as Estimator or Keras. For instance, someone using a GAN may want to take a different number of generator or discriminator steps each round. Similarly, the high level frameworks are not very suitable for Reinforcement Learning training. So these users will usually write their own training loops. For these users, we provide a core set of methods through the `tf.distrbute.Strategy` classes. Using these may require minor restructuring of the code initially, but once that is done, the user should be able to switch between GPUs / TPUs / multiple machines by just changing the strategy instance.Here we will show a brief snippet illustrating this use case for a simple training example using the same Keras model as before. Note: These APIs are still experimental and we are improving them to make them more user friendly in TensorFlow 2.0. First, we create the model and optimizer inside the strategy's scope. This ensures that any variables created with the model and optimizer are mirrored variables.
###Code
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
optimizer = tf.keras.optimizers.SGD()
###Output
_____no_output_____
###Markdown
Next, we create the input dataset and call `make_dataset_iterator` to distribute the dataset based on the strategy. This API is expected to change in the near future.
###Code
with mirrored_strategy.scope():
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(1000).batch(
global_batch_size)
input_iterator = mirrored_strategy.make_dataset_iterator(dataset)
###Output
_____no_output_____
###Markdown
Then, we define one step of the training. We will use `tf.GradientTape` to compute gradients and optimizer to apply those gradients to update our model's variables. To distribute this training step, we put in in a function `step_fn` and pass it to `strategy.experimental_run` along with the iterator created before:
###Code
@tf.function
def train_step():
def step_fn(inputs):
features, labels = inputs
with tf.GradientTape() as tape:
logits = model(features)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(
logits=logits, labels=labels)
loss = tf.reduce_sum(cross_entropy) * (1.0 / global_batch_size)
grads = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(list(zip(grads, model.trainable_variables)))
return loss
per_replica_losses = mirrored_strategy.experimental_run(
step_fn, input_iterator)
mean_loss = mirrored_strategy.reduce(
tf.distribute.ReduceOp.MEAN, per_replica_losses)
return mean_loss
###Output
_____no_output_____
###Markdown
A few other things to note in the code above: 1. We used `tf.nn.softmax_cross_entropy_with_logits` to compute the loss. And then we scaled the total loss by the global batch size. This is important because all the replicas are training in sync and number of examples in each step of training is the global batch. If you're using TensorFlow's standard losses from `tf.losses` or `tf.keras.losses`, they are distribution aware and will take care of the scaling by number of replicas whenever a strategy is in scope. 2. We used the `strategy.reduce` API to aggregate the results returned by `experimental_run`. `experimental_run` returns results from each local replica in the strategy, and there are multiple ways to consume this result. You can `reduce` them to get an aggregated value. You can also do `strategy.unwrap(results)`* to get the list of values contained in the result, one per local replica.*expected to change Finally, once we have defined the training step, we can initialize the iterator and run the training in a loop:
###Code
with mirrored_strategy.scope():
input_iterator.initialize()
for _ in range(10):
print(train_step())
###Output
_____no_output_____
###Markdown
Copyright 2018 The TensorFlow Authors.
###Code
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###Output
_____no_output_____
###Markdown
Distributed Training in TensorFlow View on TensorFlow.org Run in Google Colab View source on GitHub Overview`tf.distribute.Strategy` is a TensorFlow API to distribute trainingacross multiple GPUs, multiple machines or TPUs. Using this API, users can distribute their existing models and training code with minimal code changes.`tf.distribute.Strategy` has been designed with these key goals in mind:* Easy to use and support multiple user segments, including researchers, ML engineers, etc.* Provide good performance out of the box.* Easy switching between strategies.`tf.distribute.Strategy` can be used with TensorFlow's high level APIs, [tf.keras](https://www.tensorflow.org/guide/keras) and [tf.estimator](https://www.tensorflow.org/guide/estimators), with just a couple of lines of code change. It also provides an API that can be used to distribute custom training loops (and in general any computation using TensorFlow).In TensorFlow 2.0, users can execute their programs eagerly, or in a graph using [`tf.function`](../tutorials/eager/tf_function.ipynb). `tf.distribute.Strategy` intends to support both these modes of execution. Note that we may talk about training most of the time in this guide, but this API can also be used for distributing evaluation and prediction on different platforms.As you will see in a bit, very few changes are needed to use `tf.distribute.Strategy` with your code. This is because we have changed the underlying components of TensorFlow to become strategy-aware. This includes variables, layers, models, optimizers, metrics, summaries, and checkpoints.In this guide, we will talk about various types of strategies and how one can use them in a different situations.
###Code
# Import TensorFlow
from __future__ import absolute_import, division, print_function, unicode_literals
!pip install tensorflow-gpu==2.0.0-alpha0
import tensorflow as tf
###Output
_____no_output_____
###Markdown
Types of strategies`tf.distribute.Strategy` intends to cover a number of use cases along different axes. Some of these combinations are currently supported and others will be added in the future. Some of these axes are:* Syncronous vs asynchronous training: These are two common ways of distributing training with data parallelism. In sync training, all workers train over different slices of input data in sync, and aggregating gradients at each step. In async training, all workers are independently training over the input data and updating variables asynchronously. Typically sync training is supported via all-reduce and async through parameter server architecture.* Hardware platform: Users may want to scale their training onto multiple GPUs on one machine, or multiple machines in a network (with 0 or more GPUs each), or on Cloud TPUs.In order to support these use cases, we have 4 strategies available. In the next section we will talk about which of these are supported in which scenarios in TF 2.0-alpha at this time. MirroredStrategy`tf.distribute.MirroredStrategy` support synchronous distributed training on multiple GPUs on one machine. It creates one replica per GPU device. Each variable in the model is mirrored across all the replicas. Together, these variables form a single conceptual variable called `MirroredVariable`. These variables are kept in sync with each other by applying identical updates.Efficient all-reduce algorithms are used to communicate the variable updates across the devices.All-reduce aggregates tensors across all the devices by adding them up, and makes them available on each device.It’s a fused algorithm that is very efficient and can reduce the overhead of synchronization significantly. There are many all-reduce algorithms and implementations available, depending on the type of communication available between devices. By default, it uses NVIDIA NCCL as the all-reduce implementation. The user can also choose between a few other options we provide, or write their own.Here is the simplest way of creating `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
###Output
_____no_output_____
###Markdown
This will create a `MirroredStrategy` instance which will use all the GPUs that are visible to TensorFlow, and use NCCL as the cross device communication.If you wish to use only some of the GPUs on your machine, you can do so like this:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(devices=["/gpu:0", "/gpu:1"])
###Output
_____no_output_____
###Markdown
If you wish to override the cross device communication, you can do so using the `cross_device_ops` argument by supplying an instance of `tf.distribute.CrossDeviceOps`. Currently we provide `tf.distribute.HierarchicalCopyAllReduce` and `tf.distribute.ReductionToOneDevice` as 2 other options other than `tf.distribute.NcclAllReduce` which is the default.
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(
cross_device_ops=tf.distribute.HierarchicalCopyAllReduce())
###Output
_____no_output_____
###Markdown
MultiWorkerMirroredStrategy`tf.distribute.experimental.MultiWorkerMirroredStrategy` is very similar to `MirroredStrategy`. It implements synchronous distributed training across multiple workers, each with potentially multiple GPUs. Similar to `MirroredStrategy`, it creates copies of all variables in the model on each device across all workers.It uses [CollectiveOps](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/collective_ops.py) as the multi-worker all-reduce communication method used to keep variables in sync. A collective op is a single op in the TensorFlow graph which can automatically choose an all-reduce algorithm in the TensorFlow runtime according to hardware, network topology and tensor sizes.It also implements additional performance optimizations. For example, it includes a static optimization that converts multiple all-reductions on small tensors into fewer all-reductions on larger tensors. In addition, we are designing it to have a plugin architecture - so that in the future, users will be able to plugin algorithms that are better tuned for their hardware. Note that collective ops also implement other collective operations such as broadcast and all-gather.Here is the simplest way of creating `MultiWorkerMirroredStrategy`:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()
###Output
_____no_output_____
###Markdown
`MultiWorkerMirroredStrategy` currently allows you to choose between two different implementations of collective ops. `CollectiveCommunication.RING` implements ring-based collectives using gRPC as the communication layer. `CollectiveCommunication.NCCL` uses [Nvidia's NCCL](https://developer.nvidia.com/nccl) to implement collectives. `CollectiveCommunication.AUTO` defers the choice to the runtime. The best choice of collective implementation depends upon the number and kind of GPUs, and the network interconnect in the cluster. You can specify them like so:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy(
tf.distribute.experimental.CollectiveCommunication.NCCL)
###Output
_____no_output_____
###Markdown
One of the key differences to get multi worker training going, as compared to multi-GPU training, is the multi-worker setup. "TF_CONFIG" environment variable is the standard way in TensorFlow to specify the cluster configuration to each worker that is part of the cluster. See section on ["TF_CONFIG" below](TF_CONFIG) for more details on how this can be done. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. TPUStrategy`tf.distribute.experimental.TPUStrategy` lets users run their TensorFlow training on Tensor Processing Units (TPUs). TPUs are Google's specialized ASICs designed to dramatically accelerate machine learning workloads. They are available on Google Colab, the [TensorFlow Research Cloud](https://www.tensorflow.org/tfrc) and [Google Compute Engine](https://cloud.google.com/tpu).In terms of distributed training architecture, TPUStrategy is the same `MirroredStrategy` - it implements synchronous distributed training. TPUs provide their own implementation of efficient all-reduce and other collective operations across multiple TPU cores, which are used in `TPUStrategy`.Here is how you would instantiate `TPUStrategy`.Note: To run this code in Colab, you should select TPU as the Colab runtime. See [Using TPUs]( tpu.ipynb) guide for a runnable version.```resolver = tf.distribute.cluster_resolver.TPUClusterResolver()tf.tpu.experimental.initialize_tpu_system(resolver)tpu_strategy = tf.distribute.experimental.TPUStrategy(resolver)``` `TPUClusterResolver` instance helps locate the TPUs. In Colab, you don't need to specify any arguments to it. If you want to use this for Cloud TPUs, you will need to specify the name of your TPU resource in `tpu` argument. We also need to initialize the tpu system explicitly at the start of the program. This is required before TPUs can be used for computation and should ideally be done at the beginning because it also wipes out the TPU memory so all state will be lost. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. ParameterServerStrategy`tf.distribute.experimental.ParameterServerStrategy` supports parameter servers training. It can be used either for multi-GPU synchronous local training or asynchronous multi-machine training. When used to train locally on one machine, variables are not mirrored, instead they are placed on the CPU and operations are replicated across all local GPUs. In a multi-machine setting, some machines are designated as workers and some as parameter servers. Each variable of the model is placed on one parameter server. Computation is replicated across all GPUs of the all the workers.In terms of code, it looks similar to other strategies:
###Code
ps_strategy = tf.distribute.experimental.ParameterServerStrategy()
###Output
_____no_output_____
###Markdown
For multi worker training, "TF_CONFIG" needs to specify the configuration of parameter servers and workers in your cluster, which you can read more about in ["TF_CONFIG" below](TF_CONFIG) below. So far we've talked about what are the different stategies available and how you can instantiate them. In the next few sections, we will talk about the different ways in which you can use them to distribute your training. We will show short code snippets in this guide and link off to full tutorials which you can run end to end. Using `tf.distribute.Strategy` with KerasWe've integrated `tf.distribute.Strategy` into `tf.keras` which is TensorFlow's implementation of the[Keras API specification](https://keras.io). `tf.keras` is a high-level API to build and train models. By integrating into `tf.keras` backend, we've made it seamless for Keras users to distribute their training written in the Keras training framework. The only things that need to change in a user's program are: (1) Create an instance of the appropriate `tf.distribute.Strategy` and (2) Move the creation and compiling of Keras model inside `strategy.scope`.Here is a snippet of code to do this for a very simple Keras model with one dense layer:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
model.compile(loss='mse', optimizer='sgd')
###Output
_____no_output_____
###Markdown
In this example we used `MirroredStrategy` so we can run this on a machine with multiple GPUs. `strategy.scope()` indicated which parts of the code to run distributed. Creating a model inside this scope allows us to create mirrored variables instead of regular variables. Compiling under the scope allows us to know that the user intends to train this model using this strategy. Once this is setup, you can fit your model like you would normally. `MirroredStrategy` takes care of replicating the model's training on the available GPUs, aggregating gradients etc.
###Code
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100).batch(10)
model.fit(dataset, epochs=2)
model.evaluate(dataset)
###Output
_____no_output_____
###Markdown
Here we used a `tf.data.Dataset` to provide the training and eval input. You can also use numpy arrays:
###Code
import numpy as np
inputs, targets = np.ones((100, 1)), np.ones((100, 1))
model.fit(inputs, targets, epochs=2, batch_size=10)
###Output
_____no_output_____
###Markdown
In both cases (dataset or numpy), each batch of the given input is divided equally among the multiple replicas. For instance, if using `MirroredStrategy` with 2 GPUs, each batch of size 10 will get divided among the 2 GPUs, with each receiving 5 input examples in each step. Each epoch will then train faster as you add more GPUs. Typically, you would want to increase your batch size as you add more accelerators so as to make effective use of the extra computing power. You will also need to re-tune your learning rate, depending on the model. You can use `strategy.num_replicas_in_sync` to get the number of replicas.
###Code
# Compute global batch size using number of replicas.
BATCH_SIZE_PER_REPLICA = 5
global_batch_size = (BATCH_SIZE_PER_REPLICA *
mirrored_strategy.num_replicas_in_sync)
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100)
dataset = dataset.batch(global_batch_size)
LEARNING_RATES_BY_BATCH_SIZE = {5: 0.1, 10: 0.15}
learning_rate = LEARNING_RATES_BY_BATCH_SIZE[global_batch_size]
###Output
_____no_output_____
###Markdown
What's supported now?In TF 2.0 alpha release, we support training with Keras using `MirroredStrategy`, as well as one machine parameter server using `ParameterServerStrategy`.Support for other strategies will be coming soon. The API and how to use will be exactly the same as above. If you wish to use the other strategies like `TPUStrategy` or `MultiWorkerMirorredStrategy` in Keras in TF 2.0, you can currently do so by disabling eager execution (`tf.compat.v1.disable_eager_execution()`). Another thing to note is that when using `MultiWorkerMirorredStrategy` for multiple workers with Keras, currently the user will have to explicitly shard or shuffle the data for different workers, but we will change this in the future to automatically shard the input data intelligently. Examples and TutorialsHere is a list of tutorials and examples that illustrate the above integration end to end with Keras:1. [Tutorial](../tutorials/distribute/keras.ipynb) to train MNIST with `MirroredStrategy`.2. [Tutorial](tpu.ipynb) to train Fashion MNIST with `TPUStrategy` (currently uses `disable_eager_execution`)3. Official [ResNet50](https://github.com/tensorflow/models/blob/master/official/resnet/keras/keras_imagenet_main.py) training with ImageNet data using `MirroredStrategy`.4. [ResNet50](https://github.com/tensorflow/tpu/blob/master/models/experimental/resnet50_keras/resnet50.py) trained with Imagenet data on Cloud TPus with `TPUStrategy`. Note that this example only works with TensorFlow 1.x currently. Using `tf.distribute.Strategy` with Estimator`tf.estimator` is a distributed training TensorFlow API that originally supported the async parameter server approach. Like with Keras, we've integrated `tf.distribute.Strategy` into `tf.Estimator` so that a user who is using Estimator for their training can easily change their training is distributed with very few changes to your their code. With this, estimator users can now do synchronous distributed training on multiple GPUs and multiple workers, as well as use TPUs.The usage of `tf.distribute.Strategy` with Estimator is slightly different than the Keras case. Instead of using `strategy.scope`, now we pass the strategy object into the [`RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig) for the Estimator.Here is a snippet of code that shows this with a premade estimator `LinearRegressor` and `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
config = tf.estimator.RunConfig(
train_distribute=mirrored_strategy, eval_distribute=mirrored_strategy)
regressor = tf.estimator.LinearRegressor(
feature_columns=[tf.feature_column.numeric_column('feats')],
optimizer='SGD',
config=config)
###Output
_____no_output_____
###Markdown
We use a premade Estimator here, but the same code works with a custom Estimator as well. `train_distribute` determines how training will be distributed, and `eval_distribute` determines how evaluation will be distributed. This is another difference from Keras where we use the same strategy for both training and eval.Now we can train and evaluate this Estimator with an input function:
###Code
def input_fn():
dataset = tf.data.Dataset.from_tensors(({"feats":[1.]}, [1.]))
return dataset.repeat(1000).batch(10)
regressor.train(input_fn=input_fn, steps=10)
regressor.evaluate(input_fn=input_fn, steps=10)
###Output
_____no_output_____
###Markdown
Another difference to highlight here between Estimator and Keras is the input handling. In Keras, we mentioned that each batch of the dataset is split across the multiple replicas. In Estimator, however, the user provides an `input_fn` and have full control over how they want their data to be distributed across workers and devices. We do not do automatic splitting of batch, nor automatically shard the data across different workers. The provided `input_fn` is called once per worker, thus giving one dataset per worker. Then one batch from that dataset is fed to one replica on that worker, thereby consuming N batches for N replicas on 1 worker. In other words, the dataset returned by the `input_fn` should provide batches of size `PER_REPLICA_BATCH_SIZE`. And the global batch size for a step can be obtained as `PER_REPLICA_BATCH_SIZE * strategy.num_replicas_in_sync`. When doing multi worker training, users will also want to either split their data across the workers, or shuffle with a random seed on each. You can see an example of how to do this in the [multi-worker tutorial](../tutorials/distribute/multi_worker.ipynb). We showed an example of using `MirroredStrategy` with Estimator. You can also use `TPUStrategy` with Estimator as well, in the exact same way:```config = tf.estimator.RunConfig( train_distribute=tpu_strategy, eval_distribute=tpu_strategy)``` And similarly, you can use multi worker and parameter server strategies as well. The code remains the same, but you need to use `tf.estimator.train_and_evaluate`, and set "TF_CONFIG" environment variables for each binary running in your cluster. What's supported now?In TF 2.0 alpha release, we support training with Estimator using all strategies. Examples and TutorialsHere are some examples that show end to end usage of various strategies with Estimator:1. [Tutorial]((../tutorials/distribute/multi_worker.ipynb) to train MNIST with multiple workers using `MultiWorkerMirroredStrategy`.2. [End to end example](https://github.com/tensorflow/ecosystem/tree/master/distribution_strategy) for multi worker training in tensorflow/ecosystem using Kuberentes templates. This example starts with a Keras model and converts it to an Estimator using the `tf.keras.estimator.model_to_estimator` API.3. Official [ResNet50](https://github.com/tensorflow/models/blob/master/official/resnet/imagenet_main.py) model, which can be trained using either `MirroredStrategy` or `MultiWorkerMirroredStrategy`.4. [ResNet50](https://github.com/tensorflow/tpu/blob/master/models/experimental/distribution_strategy/resnet_estimator.py) example with TPUStrategy. Using `tf.distribute.Strategy` with custom training loopsAs you've seen, using `tf.distrbute.Strategy` with high level APIs is only a couple lines of code change. With a little more effort, `tf.distrbute.Strategy` can also be used by other users who are not using these frameworks.TensorFlow is used for a wide variety of use cases and some users (such as researchers) require more flexibility and control over their training loops. This makes it hard for them to use the high level frameworks such as Estimator or Keras. For instance, someone using a GAN may want to take a different number of generator or discriminator steps each round. Similarly, the high level frameworks are not very suitable for Reinforcement Learning training. So these users will usually write their own training loops.For these users, we provide a core set of methods through the `tf.distrbute.Strategy` classes. Using these may require minor restructuring of the code initially, but once that is done, the user should be able to switch between GPUs / TPUs / multiple machines by just changing the strategy instance.Here we will show a brief snippet illustrating this use case for a simple training example using the same Keras model as before.Note: These APIs are still experimental and we are improving them to make them more user friendly in TensorFlow 2.0. First, we create the model and optimizer inside the strategy's scope. This ensures that any variables created with the model and optimizer are mirrored variables.
###Code
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
optimizer = tf.keras.optimizers.SGD()
###Output
_____no_output_____
###Markdown
Next, we create the input dataset and call `make_dataset_iterator` to distribute the dataset based on the strategy. This API is expected to change in the near future.
###Code
with mirrored_strategy.scope():
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(1000).batch(
global_batch_size)
input_iterator = mirrored_strategy.make_dataset_iterator(dataset)
###Output
_____no_output_____
###Markdown
Then, we define one step of the training. We will use `tf.GradientTape` to compute gradients and optimizer to apply those gradients to update our model's variables. To distribute this training step, we put in in a function `step_fn` and pass it to `strategy.experimental_run` along with the iterator created before:
###Code
@tf.function
def train_step():
def step_fn(inputs):
features, labels = inputs
with tf.GradientTape() as tape:
logits = model(features)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(
logits=logits, labels=labels)
loss = tf.reduce_sum(cross_entropy) * (1.0 / global_batch_size)
grads = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(list(zip(grads, model.trainable_variables)))
return loss
per_replica_losses = mirrored_strategy.experimental_run(
step_fn, input_iterator)
mean_loss = mirrored_strategy.reduce(
tf.distribute.ReduceOp.SUM, per_replica_losses, axis=None)
return mean_loss
###Output
_____no_output_____
###Markdown
A few other things to note in the code above:1. We used `tf.nn.softmax_cross_entropy_with_logits` to compute the loss. And then we scaled the total loss by the global batch size. This is important because all the replicas are training in sync and number of examples in each step of training is the global batch. If you're using TensorFlow's standard losses from `tf.losses` or `tf.keras.losses`, they are distribution aware and will take care of the scaling by number of replicas whenever a strategy is in scope.2. We used the `strategy.reduce` API to aggregate the results returned by `experimental_run`. `experimental_run` returns results from each local replica in the strategy, and there are multiple ways to consume this result. You can `reduce` them to get an aggregated value. You can also do `strategy.unwrap(results)`* to get the list of values contained in the result, one per local replica.*expected to change Finally, once we have defined the training step, we can initialize the iterator and run the training in a loop:
###Code
with mirrored_strategy.scope():
input_iterator.initialize()
for _ in range(10):
print(train_step())
###Output
_____no_output_____
###Markdown
Copyright 2018 The TensorFlow Authors.
###Code
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###Output
_____no_output_____
###Markdown
Distributed Training in TensorFlow View on TensorFlow.org Run in Google Colab View source on GitHub Overview`tf.distribute.Strategy` is a TensorFlow API to distribute trainingacross multiple GPUs, multiple machines or TPUs. Using this API, users can distribute their existing models and training code with minimal code changes.`tf.distribute.Strategy` has been designed with these key goals in mind:* Easy to use and support multiple user segments, including researchers, ML engineers, etc.* Provide good performance out of the box.* Easy switching between strategies.`tf.distribute.Strategy` can be used with TensorFlow's high level APIs, [tf.keras](https://www.tensorflow.org/guide/keras) and [tf.estimator](https://www.tensorflow.org/guide/estimators), with just a couple of lines of code change. It also provides an API that can be used to distribute custom training loops (and in general any computation using TensorFlow).In TensorFlow 2.0, users can execute their programs eagerly, or in a graph using [`tf.function`](../tutorials/eager/tf_function.ipynb). `tf.distribute.Strategy` intends to support both these modes of execution. Note that we may talk about training most of the time in this guide, but this API can also be used for distributing evaluation and prediction on different platforms.As you will see in a bit, very few changes are needed to use `tf.distribute.Strategy` with your code. This is because we have changed the underlying components of TensorFlow to become strategy-aware. This includes variables, layers, models, optimizers, metrics, summaries, and checkpoints.In this guide, we will talk about various types of strategies and how one can use them in a different situations.
###Code
# Import TensorFlow
from __future__ import absolute_import, division, print_function, unicode_literals
!pip install tensorflow-gpu==2.0.0-alpha0
import tensorflow as tf
###Output
_____no_output_____
###Markdown
Types of strategies`tf.distribute.Strategy` intends to cover a number of use cases along different axes. Some of these combinations are currently supported and others will be added in the future. Some of these axes are:* Syncronous vs asynchronous training: These are two common ways of distributing training with data parallelism. In sync training, all workers train over different slices of input data in sync, and aggregating gradients at each step. In async training, all workers are independently training over the input data and updating variables asynchronously. Typically sync training is supported via all-reduce and async through parameter server architecture.* Hardware platform: Users may want to scale their training onto multiple GPUs on one machine, or multiple machines in a network (with 0 or more GPUs each), or on Cloud TPUs.In order to support these use cases, we have 4 strategies available. In the next section we will talk about which of these are supported in which scenarios in TF 2.0-alpha at this time. MirroredStrategy`tf.distribute.MirroredStrategy` support synchronous distributed training on multiple GPUs on one machine. It creates one replica per GPU device. Each variable in the model is mirrored across all the replicas. Together, these variables form a single conceptual variable called `MirroredVariable`. These variables are kept in sync with each other by applying identical updates.Efficient all-reduce algorithms are used to communicate the variable updates across the devices.All-reduce aggregates tensors across all the devices by adding them up, and makes them available on each device.It’s a fused algorithm that is very efficient and can reduce the overhead of synchronization significantly. There are many all-reduce algorithms and implementations available, depending on the type of communication available between devices. By default, it uses NVIDIA NCCL as the all-reduce implementation. The user can also choose between a few other options we provide, or write their own.Here is the simplest way of creating `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
###Output
_____no_output_____
###Markdown
This will create a `MirroredStrategy` instance which will use all the GPUs that are visible to TensorFlow, and use NCCL as the cross device communication.If you wish to use only some of the GPUs on your machine, you can do so like this:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(devices=["/gpu:0", "/gpu:1"])
###Output
_____no_output_____
###Markdown
If you wish to override the cross device communication, you can do so using the `cross_device_ops` argument by supplying an instance of `tf.distribute.CrossDeviceOps`. Currently we provide `tf.distribute.HierarchicalCopyAllReduce` and `tf.distribute.ReductionToOneDevice` as 2 other options other than `tf.distribute.NcclAllReduce` which is the default.
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(
cross_device_ops=tf.distribute.HierarchicalCopyAllReduce())
###Output
_____no_output_____
###Markdown
CentralStorageStrategy`tf.distribute.experimental.CentralStorageStrategy` does synchronous training as well. Variables are not mirrored, instead they are placed on the CPU and operations are replicated across all local GPUs. If there is only one GPU, all variables and operations will be placed on that GPU.Create a `CentralStorageStrategy` by:
###Code
central_storage_strategy = tf.distribute.experimental.CentralStorageStrategy()
###Output
_____no_output_____
###Markdown
This will create a `CentralStorageStrategy` instance which will use all visible GPUs and CPU. Update to variables on replicas will be aggragated before being applied to variables. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. MultiWorkerMirroredStrategy`tf.distribute.experimental.MultiWorkerMirroredStrategy` is very similar to `MirroredStrategy`. It implements synchronous distributed training across multiple workers, each with potentially multiple GPUs. Similar to `MirroredStrategy`, it creates copies of all variables in the model on each device across all workers.It uses [CollectiveOps](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/collective_ops.py) as the multi-worker all-reduce communication method used to keep variables in sync. A collective op is a single op in the TensorFlow graph which can automatically choose an all-reduce algorithm in the TensorFlow runtime according to hardware, network topology and tensor sizes.It also implements additional performance optimizations. For example, it includes a static optimization that converts multiple all-reductions on small tensors into fewer all-reductions on larger tensors. In addition, we are designing it to have a plugin architecture - so that in the future, users will be able to plugin algorithms that are better tuned for their hardware. Note that collective ops also implement other collective operations such as broadcast and all-gather.Here is the simplest way of creating `MultiWorkerMirroredStrategy`:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()
###Output
_____no_output_____
###Markdown
`MultiWorkerMirroredStrategy` currently allows you to choose between two different implementations of collective ops. `CollectiveCommunication.RING` implements ring-based collectives using gRPC as the communication layer. `CollectiveCommunication.NCCL` uses [Nvidia's NCCL](https://developer.nvidia.com/nccl) to implement collectives. `CollectiveCommunication.AUTO` defers the choice to the runtime. The best choice of collective implementation depends upon the number and kind of GPUs, and the network interconnect in the cluster. You can specify them like so:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy(
tf.distribute.experimental.CollectiveCommunication.NCCL)
###Output
_____no_output_____
###Markdown
One of the key differences to get multi worker training going, as compared to multi-GPU training, is the multi-worker setup. "TF_CONFIG" environment variable is the standard way in TensorFlow to specify the cluster configuration to each worker that is part of the cluster. See section on ["TF_CONFIG" below](TF_CONFIG) for more details on how this can be done. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. TPUStrategy`tf.distribute.experimental.TPUStrategy` lets users run their TensorFlow training on Tensor Processing Units (TPUs). TPUs are Google's specialized ASICs designed to dramatically accelerate machine learning workloads. They are available on Google Colab, the [TensorFlow Research Cloud](https://www.tensorflow.org/tfrc) and [Google Compute Engine](https://cloud.google.com/tpu).In terms of distributed training architecture, TPUStrategy is the same `MirroredStrategy` - it implements synchronous distributed training. TPUs provide their own implementation of efficient all-reduce and other collective operations across multiple TPU cores, which are used in `TPUStrategy`.Here is how you would instantiate `TPUStrategy`.Note: To run this code in Colab, you should select TPU as the Colab runtime. See [Using TPUs]( tpu.ipynb) guide for a runnable version.```resolver = tf.distribute.cluster_resolver.TPUClusterResolver()tf.tpu.experimental.initialize_tpu_system(resolver)tpu_strategy = tf.distribute.experimental.TPUStrategy(resolver)``` `TPUClusterResolver` instance helps locate the TPUs. In Colab, you don't need to specify any arguments to it. If you want to use this for Cloud TPUs, you will need to specify the name of your TPU resource in `tpu` argument. We also need to initialize the tpu system explicitly at the start of the program. This is required before TPUs can be used for computation and should ideally be done at the beginning because it also wipes out the TPU memory so all state will be lost. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. ParameterServerStrategy`tf.distribute.experimental.ParameterServerStrategy` supports parameter servers training on multiple machines. In this setup, some machines are designated as workers and some as parameter servers. Each variable of the model is placed on one parameter server. Computation is replicated across all GPUs of the all the workers.In terms of code, it looks similar to other strategies:```ps_strategy = tf.distribute.experimental.ParameterServerStrategy()``` For multi worker training, "TF_CONFIG" needs to specify the configuration of parameter servers and workers in your cluster, which you can read more about in ["TF_CONFIG" below](TF_CONFIG) below. So far we've talked about what are the different stategies available and how you can instantiate them. In the next few sections, we will talk about the different ways in which you can use them to distribute your training. We will show short code snippets in this guide and link off to full tutorials which you can run end to end. Using `tf.distribute.Strategy` with KerasWe've integrated `tf.distribute.Strategy` into `tf.keras` which is TensorFlow's implementation of the[Keras API specification](https://keras.io). `tf.keras` is a high-level API to build and train models. By integrating into `tf.keras` backend, we've made it seamless for Keras users to distribute their training written in the Keras training framework. The only things that need to change in a user's program are: (1) Create an instance of the appropriate `tf.distribute.Strategy` and (2) Move the creation and compiling of Keras model inside `strategy.scope`.Here is a snippet of code to do this for a very simple Keras model with one dense layer:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
model.compile(loss='mse', optimizer='sgd')
###Output
_____no_output_____
###Markdown
In this example we used `MirroredStrategy` so we can run this on a machine with multiple GPUs. `strategy.scope()` indicated which parts of the code to run distributed. Creating a model inside this scope allows us to create mirrored variables instead of regular variables. Compiling under the scope allows us to know that the user intends to train this model using this strategy. Once this is setup, you can fit your model like you would normally. `MirroredStrategy` takes care of replicating the model's training on the available GPUs, aggregating gradients etc.
###Code
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100).batch(10)
model.fit(dataset, epochs=2)
model.evaluate(dataset)
###Output
_____no_output_____
###Markdown
Here we used a `tf.data.Dataset` to provide the training and eval input. You can also use numpy arrays:
###Code
import numpy as np
inputs, targets = np.ones((100, 1)), np.ones((100, 1))
model.fit(inputs, targets, epochs=2, batch_size=10)
###Output
_____no_output_____
###Markdown
In both cases (dataset or numpy), each batch of the given input is divided equally among the multiple replicas. For instance, if using `MirroredStrategy` with 2 GPUs, each batch of size 10 will get divided among the 2 GPUs, with each receiving 5 input examples in each step. Each epoch will then train faster as you add more GPUs. Typically, you would want to increase your batch size as you add more accelerators so as to make effective use of the extra computing power. You will also need to re-tune your learning rate, depending on the model. You can use `strategy.num_replicas_in_sync` to get the number of replicas.
###Code
# Compute global batch size using number of replicas.
BATCH_SIZE_PER_REPLICA = 5
global_batch_size = (BATCH_SIZE_PER_REPLICA *
mirrored_strategy.num_replicas_in_sync)
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100)
dataset = dataset.batch(global_batch_size)
LEARNING_RATES_BY_BATCH_SIZE = {5: 0.1, 10: 0.15}
learning_rate = LEARNING_RATES_BY_BATCH_SIZE[global_batch_size]
###Output
_____no_output_____
###Markdown
What's supported now?In TF 2.0 alpha release, we support training with Keras using `MirroredStrategy`, as well as one machine parameter server using `ParameterServerStrategy`.Support for other strategies will be coming soon. The API and how to use will be exactly the same as above. If you wish to use the other strategies like `TPUStrategy` or `MultiWorkerMirorredStrategy` in Keras in TF 2.0, you can currently do so by disabling eager execution (`tf.compat.v1.disable_eager_execution()`). Another thing to note is that when using `MultiWorkerMirorredStrategy` for multiple workers with Keras, currently the user will have to explicitly shard or shuffle the data for different workers, but we will change this in the future to automatically shard the input data intelligently. Examples and TutorialsHere is a list of tutorials and examples that illustrate the above integration end to end with Keras:1. [Tutorial](../tutorials/distribute/keras.ipynb) to train MNIST with `MirroredStrategy`.2. Official [ResNet50](https://github.com/tensorflow/models/blob/master/official/resnet/keras/keras_imagenet_main.py) training with ImageNet data using `MirroredStrategy`.3. [ResNet50](https://github.com/tensorflow/tpu/blob/master/models/experimental/resnet50_keras/resnet50.py) trained with Imagenet data on Cloud TPus with `TPUStrategy`. Note that this example only works with TensorFlow 1.x currently. Using `tf.distribute.Strategy` with Estimator`tf.estimator` is a distributed training TensorFlow API that originally supported the async parameter server approach. Like with Keras, we've integrated `tf.distribute.Strategy` into `tf.Estimator` so that a user who is using Estimator for their training can easily change their training is distributed with very few changes to your their code. With this, estimator users can now do synchronous distributed training on multiple GPUs and multiple workers, as well as use TPUs.The usage of `tf.distribute.Strategy` with Estimator is slightly different than the Keras case. Instead of using `strategy.scope`, now we pass the strategy object into the [`RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig) for the Estimator.Here is a snippet of code that shows this with a premade estimator `LinearRegressor` and `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
config = tf.estimator.RunConfig(
train_distribute=mirrored_strategy, eval_distribute=mirrored_strategy)
regressor = tf.estimator.LinearRegressor(
feature_columns=[tf.feature_column.numeric_column('feats')],
optimizer='SGD',
config=config)
###Output
_____no_output_____
###Markdown
We use a premade Estimator here, but the same code works with a custom Estimator as well. `train_distribute` determines how training will be distributed, and `eval_distribute` determines how evaluation will be distributed. This is another difference from Keras where we use the same strategy for both training and eval.Now we can train and evaluate this Estimator with an input function:
###Code
def input_fn():
dataset = tf.data.Dataset.from_tensors(({"feats":[1.]}, [1.]))
return dataset.repeat(1000).batch(10)
regressor.train(input_fn=input_fn, steps=10)
regressor.evaluate(input_fn=input_fn, steps=10)
###Output
_____no_output_____
###Markdown
Another difference to highlight here between Estimator and Keras is the input handling. In Keras, we mentioned that each batch of the dataset is split across the multiple replicas. In Estimator, however, the user provides an `input_fn` and have full control over how they want their data to be distributed across workers and devices. We do not do automatic splitting of batch, nor automatically shard the data across different workers. The provided `input_fn` is called once per worker, thus giving one dataset per worker. Then one batch from that dataset is fed to one replica on that worker, thereby consuming N batches for N replicas on 1 worker. In other words, the dataset returned by the `input_fn` should provide batches of size `PER_REPLICA_BATCH_SIZE`. And the global batch size for a step can be obtained as `PER_REPLICA_BATCH_SIZE * strategy.num_replicas_in_sync`. When doing multi worker training, users will also want to either split their data across the workers, or shuffle with a random seed on each. You can see an example of how to do this in the [multi-worker tutorial](../tutorials/distribute/multi_worker.ipynb). We showed an example of using `MirroredStrategy` with Estimator. You can also use `TPUStrategy` with Estimator as well, in the exact same way:```config = tf.estimator.RunConfig( train_distribute=tpu_strategy, eval_distribute=tpu_strategy)``` And similarly, you can use multi worker and parameter server strategies as well. The code remains the same, but you need to use `tf.estimator.train_and_evaluate`, and set "TF_CONFIG" environment variables for each binary running in your cluster. What's supported now?In TF 2.0 alpha release, we support training with Estimator using all strategies. Examples and TutorialsHere are some examples that show end to end usage of various strategies with Estimator:1. [Tutorial](../tutorials/distribute/multi_worker.ipynb) to train MNIST with multiple workers using `MultiWorkerMirroredStrategy`.2. [End to end example](https://github.com/tensorflow/ecosystem/tree/master/distribution_strategy) for multi worker training in tensorflow/ecosystem using Kuberentes templates. This example starts with a Keras model and converts it to an Estimator using the `tf.keras.estimator.model_to_estimator` API.3. Official [ResNet50](https://github.com/tensorflow/models/blob/master/official/resnet/imagenet_main.py) model, which can be trained using either `MirroredStrategy` or `MultiWorkerMirroredStrategy`.4. [ResNet50](https://github.com/tensorflow/tpu/blob/master/models/experimental/distribution_strategy/resnet_estimator.py) example with TPUStrategy. Using `tf.distribute.Strategy` with custom training loopsAs you've seen, using `tf.distrbute.Strategy` with high level APIs is only a couple lines of code change. With a little more effort, `tf.distrbute.Strategy` can also be used by other users who are not using these frameworks.TensorFlow is used for a wide variety of use cases and some users (such as researchers) require more flexibility and control over their training loops. This makes it hard for them to use the high level frameworks such as Estimator or Keras. For instance, someone using a GAN may want to take a different number of generator or discriminator steps each round. Similarly, the high level frameworks are not very suitable for Reinforcement Learning training. So these users will usually write their own training loops.For these users, we provide a core set of methods through the `tf.distrbute.Strategy` classes. Using these may require minor restructuring of the code initially, but once that is done, the user should be able to switch between GPUs / TPUs / multiple machines by just changing the strategy instance.Here we will show a brief snippet illustrating this use case for a simple training example using the same Keras model as before.Note: These APIs are still experimental and we are improving them to make them more user friendly in TensorFlow 2.0. First, we create the model and optimizer inside the strategy's scope. This ensures that any variables created with the model and optimizer are mirrored variables.
###Code
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
optimizer = tf.keras.optimizers.SGD()
###Output
_____no_output_____
###Markdown
Next, we create the input dataset and call `make_dataset_iterator` to distribute the dataset based on the strategy. This API is expected to change in the near future.
###Code
with mirrored_strategy.scope():
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(1000).batch(
global_batch_size)
input_iterator = mirrored_strategy.make_dataset_iterator(dataset)
###Output
_____no_output_____
###Markdown
Then, we define one step of the training. We will use `tf.GradientTape` to compute gradients and optimizer to apply those gradients to update our model's variables. To distribute this training step, we put in in a function `step_fn` and pass it to `strategy.experimental_run` along with the iterator created before:
###Code
@tf.function
def train_step():
def step_fn(inputs):
features, labels = inputs
with tf.GradientTape() as tape:
logits = model(features)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(
logits=logits, labels=labels)
loss = tf.reduce_sum(cross_entropy) * (1.0 / global_batch_size)
grads = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(list(zip(grads, model.trainable_variables)))
return loss
per_replica_losses = mirrored_strategy.experimental_run(
step_fn, input_iterator)
mean_loss = mirrored_strategy.reduce(
tf.distribute.ReduceOp.SUM, per_replica_losses, axis=None)
return mean_loss
###Output
_____no_output_____
###Markdown
A few other things to note in the code above:1. We used `tf.nn.softmax_cross_entropy_with_logits` to compute the loss. And then we scaled the total loss by the global batch size. This is important because all the replicas are training in sync and number of examples in each step of training is the global batch. So the loss needs to be divided by the global batch size and not by the replica (local) batch size.2. We used the `strategy.reduce` API to aggregate the results returned by `experimental_run`. `experimental_run` returns results from each local replica in the strategy, and there are multiple ways to consume this result. You can `reduce` them to get an aggregated value. You can also do `strategy.unwrap(results)`* to get the list of values contained in the result, one per local replica.3. When `apply_gradients` is called within a distribution strategy scope, its behavior is modified. Specifically, before applying gradients on each parallel instance during synchronous training, it performs a sum-over-all-replicas of the gradients.*expected to change Finally, once we have defined the training step, we can initialize the iterator and run the training in a loop:
###Code
with mirrored_strategy.scope():
input_iterator.initialize()
for _ in range(10):
print(train_step())
###Output
_____no_output_____
###Markdown
Copyright 2018 The TensorFlow Authors.
###Code
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###Output
_____no_output_____
###Markdown
Distributed Training in TensorFlow View on TensorFlow.org Run in Google Colab View source on GitHub OverviewThe `tf.distribute.Strategy` API is an easy way to distribute your trainingacross multiple devices/machines. Our goal is to allow users to use existingmodels and training code with minimal changes to enable distributed training.Currently, in core TensorFlow, we support `tf.distribute.MirroredStrategy`. Thisdoes in-graph replication with synchronous training on many GPUs on one machine.Essentially, we create copies of all variables in the model's layers on eachdevice. We then use all-reduce to combine gradients across the devices beforeapplying them to the variables to keep them in sync.Many other strategies will soon beavailable in core TensorFlow. You can find more information about them in the[README](https://github.com/tensorflow/tensorflow/tree/master/tensorflow/contrib/distribute).You can also read the[public design review](https://github.com/tensorflow/community/blob/master/rfcs/20181016-replicator.md)for updating the `tf.distribute.Strategy` API as part of the move toto core TF. Example with Keras APILet's see how to scale to multiple GPUs on one machine using `MirroredStrategy`with [tf.keras](https://www.tensorflow.org/guide/keras).We will take a very simple model consisting of a single layer. First, we will import Tensorflow.
###Code
from __future__ import absolute_import, division, print_function
!pip install tf-nightly-2.0-preview
import tensorflow as tf
###Output
_____no_output_____
###Markdown
To distribute a Keras model on multiple GPUs using `MirroredStrategy`, we first instantiate a `MirroredStrategy` object.
###Code
strategy = tf.distribute.MirroredStrategy()
###Output
_____no_output_____
###Markdown
We then create and compile the Keras model in `strategy.scope`.
###Code
with strategy.scope():
inputs = tf.keras.layers.Input(shape=(1,))
predictions = tf.keras.layers.Dense(1)(inputs)
model = tf.keras.models.Model(inputs=inputs, outputs=predictions)
model.compile(loss='mse',
optimizer=tf.keras.optimizers.SGD(learning_rate=0.2))
###Output
_____no_output_____
###Markdown
Let's also define a simple input dataset for training this model.
###Code
train_dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(10000).batch(10)
###Output
_____no_output_____
###Markdown
To train the model we call Keras `fit` API using the input dataset that wecreated earlier, same as how we would in a non-distributed case.
###Code
model.fit(train_dataset, epochs=5, steps_per_epoch=10)
###Output
_____no_output_____
###Markdown
Similarly, we can also call `evaluate` and `predict` as before using appropriatedatasets.
###Code
eval_dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100).batch(10)
model.evaluate(eval_dataset, steps=10)
predict_dataset = tf.data.Dataset.from_tensors(([1.])).repeat(10).batch(2)
model.predict(predict_dataset, steps=5)
###Output
_____no_output_____
###Markdown
That's all you need to train your model with Keras on multiple GPUs with`MirroredStrategy`. It will take care of splitting upthe input dataset, replicating layers and variables on each device, andcombining and applying gradients.The model and input code does not have to change because we have changed theunderlying components of TensorFlow (such as optimizer, batch norm andsummaries) to become strategy-aware. That means those components know how tocombine their state across devices. Further, saving and checkpointing worksseamlessly, so you can save with one or no distribute strategy and resume withanother. Example with Estimator APIYou can also use `tf.distribute.Strategy` API with[`Estimator`](https://www.tensorflow.org/api_docs/python/tf/estimator/Estimator).Let's see a simple example of its usage with `MirroredStrategy`.We will use the `LinearRegressor` premade estimator as an example. To use `MirroredStrategy` with Estimator, all we need to do is:* Create an instance of the `MirroredStrategy` class.* Pass it to the[`RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig)parameter of the custom or premade `Estimator`.
###Code
strategy = tf.distribute.MirroredStrategy()
config = tf.estimator.RunConfig(
train_distribute=strategy, eval_distribute=strategy)
regressor = tf.estimator.LinearRegressor(
feature_columns=[tf.feature_column.numeric_column('feats')],
optimizer='SGD',
config=config)
###Output
_____no_output_____
###Markdown
We will define a simple input function to feed data for training this model.
###Code
def input_fn():
return tf.data.Dataset.from_tensors(({"feats":[1.]}, [1.])).repeat(10000).batch(10)
###Output
_____no_output_____
###Markdown
Then we can call `train` on the regressor instance to train the model.
###Code
regressor.train(input_fn=input_fn, steps=10)
###Output
_____no_output_____
###Markdown
And we can `evaluate` to evaluate the trained model.
###Code
regressor.evaluate(input_fn=input_fn, steps=10)
###Output
_____no_output_____
###Markdown
Copyright 2018 The TensorFlow Authors.
###Code
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###Output
_____no_output_____
###Markdown
Distributed Training in TensorFlow View on TensorFlow.org Run in Google Colab View source on GitHub Overview`tf.distribute.Strategy` is a TensorFlow API to distribute trainingacross multiple GPUs, multiple machines or TPUs. Using this API, users can distribute their existing models and training code with minimal code changes.`tf.distribute.Strategy` has been designed with these key goals in mind:* Easy to use and support multiple user segments, including researchers, ML engineers, etc.* Provide good performance out of the box.* Easy switching between strategies.`tf.distribute.Strategy` can be used with TensorFlow's high level APIs, [tf.keras](https://www.tensorflow.org/guide/keras) and [tf.estimator](https://www.tensorflow.org/guide/estimators), with just a couple of lines of code change. It also provides an API that can be used to distribute custom training loops (and in general any computation using TensorFlow).In TensorFlow 2.0, users can execute their programs eagerly, or in a graph using [`tf.function`](../tutorials/eager/tf_function.ipynb). `tf.distribute.Strategy` intends to support both these modes of execution. Note that we may talk about training most of the time in this guide, but this API can also be used for distributing evaluation and prediction on different platforms.As you will see in a bit, very few changes are needed to use `tf.distribute.Strategy` with your code. This is because we have changed the underlying components of TensorFlow to become strategy-aware. This includes variables, layers, models, optimizers, metrics, summaries, and checkpoints. In this guide, we will talk about various types of strategies and how one can use them in a different situations.
###Code
# Import TensorFlow
from __future__ import absolute_import, division, print_function
!pip install tensorflow-gpu==2.0.0-alpha0
import tensorflow as tf
###Output
_____no_output_____
###Markdown
Types of strategies`tf.distribute.Strategy` intends to cover a number of use cases along different axes. Some of these combinations are currently supported and others will be added in the future. Some of these axes are:* Syncronous vs asynchronous training: These are two common ways of distributing training with data parallelism. In sync training, all workers train over different slices of input data in sync, and aggregating gradients at each step. In async training, all workers are independently training over the input data and updating variables asynchronously. Typically sync training is supported via all-reduce and async through parameter server architecture.* Hardware platform: Users may want to scale their training onto multiple GPUs on one machine, or multiple machines in a network (with 0 or more GPUs each), or on Cloud TPUs.In order to support these use cases, we have 4 strategies available. In the next section we will talk about which of these are supported in which scenarios in TF 2.0-alpha at this time. MirroredStrategy`tf.distribute.MirroredStrategy` support synchronous distributed training on multiple GPUs on one machine. It creates one replica per GPU device. Each variable in the model is mirrored across all the replicas. Together, these variables form a single conceptual variable called `MirroredVariable`. These variables are kept in sync with each other by applying identical updates.Efficient all-reduce algorithms are used to communicate the variable updates across the devices.All-reduce aggregates tensors across all the devices by adding them up, and makes them available on each device.It’s a fused algorithm that is very efficient and can reduce the overhead of synchronization significantly. There are many all-reduce algorithms and implementations available, depending on the type of communication available between devices. By default, it uses NVIDIA NCCL as the all-reduce implementation. The user can also choose between a few other options we provide, or write their own.Here is the simplest way of creating `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
###Output
_____no_output_____
###Markdown
This will create a `MirroredStrategy` instance which will use all the GPUs that are visible to TensorFlow, and use NCCL as the cross device communication.If you wish to use only some of the GPUs on your machine, you can do so like this:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(devices=["/gpu:0", "/gpu:1"])
###Output
_____no_output_____
###Markdown
If you wish to override the cross device communication, you can do so using the `cross_device_ops` argument by supplying an instance of `tf.distribute.CrossDeviceOps`. Currently we provide `tf.distribute.HierarchicalCopyAllReduce` and `tf.distribute.ReductionToOneDevice` as 2 other options other than `tf.distribute.NcclAllReduce` which is the default.
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(
cross_device_ops=tf.distribute.HierarchicalCopyAllReduce())
###Output
_____no_output_____
###Markdown
MultiWorkerMirroredStrategy`tf.distribute.experimental.MultiWorkerMirroredStrategy` is very similar to `MirroredStrategy`. It implements synchronous distributed training across multiple workers, each with potentially multiple GPUs. Similar to `MirroredStrategy`, it creates copies of all variables in the model on each device across all workers. It uses [CollectiveOps](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/collective_ops.py) as the multi-worker all-reduce communication method used to keep variables in sync. A collective op is a single op in the TensorFlow graph which can automatically choose an all-reduce algorithm in the TensorFlow runtime according to hardware, network topology and tensor sizes. It also implements additional performance optimizations. For example, it includes a static optimization that converts multiple all-reductions on small tensors into fewer all-reductions on larger tensors. In addition, we are designing it to have a plugin architecture - so that in the future, users will be able to plugin algorithms that are better tuned for their hardware. Note that collective ops also implement other collective operations such as broadcast and all-gather. Here is the simplest way of creating `MultiWorkerMirroredStrategy`:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()
###Output
_____no_output_____
###Markdown
`MultiWorkerMirroredStrategy` currently allows you to choose between two different implementations of collective ops. `CollectiveCommunication.RING` implements ring-based collectives using gRPC as the communication layer. `CollectiveCommunication.NCCL` uses [Nvidia's NCCL](https://developer.nvidia.com/nccl) to implement collectives. `CollectiveCommunication.AUTO` defers the choice to the runtime. The best choice of collective implementation depends upon the number and kind of GPUs, and the network interconnect in the cluster. You can specify them like so:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy(
tf.distribute.experimental.CollectiveCommunication.NCCL)
###Output
_____no_output_____
###Markdown
One of the key differences to get multi worker training going, as compared to multi-GPU training, is the multi-worker setup. "TF_CONFIG" environment variable is the standard way in TensorFlow to specify the cluster configuration to each worker that is part of the cluster. See section on ["TF_CONFIG" below](TF_CONFIG) for more details on how this can be done. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. TPUStrategy`tf.distribute.experimental.TPUStrategy` lets users run their TensorFlow training on Tensor Processing Units (TPUs). TPUs are Google's specialized ASICs designed to dramatically accelerate machine learning workloads. They are available on Google Colab, the [TensorFlow Research Cloud](https://www.tensorflow.org/tfrc) and [Google Compute Engine](https://cloud.google.com/tpu).In terms of distributed training architecture, TPUStrategy is the same `MirroredStrategy` - it implements synchronous distributed training. TPUs provide their own implementation of efficient all-reduce and other collective operations across multiple TPU cores, which are used in `TPUStrategy`. Here is how you would instantiate `TPUStrategy`.Note: To run this code in Colab, you should select TPU as the Colab runtime. See [Using TPUs]( tpu.ipynb) guide for a runnable version.```resolver = tf.distribute.cluster_resolver.TPUClusterResolver()tf.tpu.experimental.initialize_tpu_system(resolver)tpu_strategy = tf.distribute.experimental.TPUStrategy(resolver)``` `TPUClusterResolver` instance helps locate the TPUs. In Colab, you don't need to specify any arguments to it. If you want to use this for Cloud TPUs, you will need to specify the name of your TPU resource in `tpu` argument. We also need to initialize the tpu system explicitly at the start of the program. This is required before TPUs can be used for computation and should ideally be done at the beginning because it also wipes out the TPU memory so all state will be lost. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. ParameterServerStrategy`tf.distribute.experimental.ParameterServerStrategy` supports parameter servers training. It can be used either for multi-GPU synchronous local training or asynchronous multi-machine training. When used to train locally on one machine, variables are not mirrored, instead they are placed on the CPU and operations are replicated across all local GPUs. In a multi-machine setting, some machines are designated as workers and some as parameter servers. Each variable of the model is placed on one parameter server. Computation is replicated across all GPUs of the all the workers.In terms of code, it looks similar to other strategies:
###Code
ps_strategy = tf.distribute.experimental.ParameterServerStrategy()
###Output
_____no_output_____
###Markdown
For multi worker training, "TF_CONFIG" needs to specify the configuration of parameter servers and workers in your cluster, which you can read more about in ["TF_CONFIG" below](TF_CONFIG) below. So far we've talked about what are the different stategies available and how you can instantiate them. In the next few sections, we will talk about the different ways in which you can use them to distribute your training. We will show short code snippets in this guide and link off to full tutorials which you can run end to end. Using `tf.distribute.Strategy` with KerasWe've integrated `tf.distribute.Strategy` into `tf.keras` which is TensorFlow's implementation of the[Keras API specification](https://keras.io). `tf.keras` is a high-level API to build and train models. By integrating into `tf.keras` backend, we've made it seamless for Keras users to distribute their training written in the Keras training framework. The only things that need to change in a user's program are: (1) Create an instance of the appropriate `tf.distribute.Strategy` and (2) Move the creation and compiling of Keras model inside `strategy.scope`. Here is a snippet of code to do this for a very simple Keras model with one dense layer:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
model.compile(loss='mse', optimizer='sgd')
###Output
_____no_output_____
###Markdown
In this example we used `MirroredStrategy` so we can run this on a machine with multiple GPUs. `strategy.scope()` indicated which parts of the code to run distributed. Creating a model inside this scope allows us to create mirrored variables instead of regular variables. Compiling under the scope allows us to know that the user intends to train this model using this strategy. Once this is setup, you can fit your model like you would normally. `MirroredStrategy` takes care of replicating the model's training on the available GPUs, aggregating gradients etc.
###Code
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100).batch(10)
model.fit(dataset, epochs=2)
model.evaluate(dataset)
###Output
_____no_output_____
###Markdown
Here we used a `tf.data.Dataset` to provide the training and eval input. You can also use numpy arrays:
###Code
import numpy as np
inputs, targets = np.ones((100, 1)), np.ones((100, 1))
model.fit(inputs, targets, epochs=2, batch_size=10)
###Output
_____no_output_____
###Markdown
In both cases (dataset or numpy), each batch of the given input is divided equally among the multiple replicas. For instance, if using `MirroredStrategy` with 2 GPUs, each batch of size 10 will get divided among the 2 GPUs, with each receiving 5 input examples in each step. Each epoch will then train faster as you add more GPUs. Typically, you would want to increase your batch size as you add more accelerators so as to make effective use of the extra computing power. You will also need to re-tune your learning rate, depending on the model. You can use `strategy.num_replicas_in_sync` to get the number of replicas.
###Code
# Compute global batch size using number of replicas.
BATCH_SIZE_PER_REPLICA = 5
global_batch_size = (BATCH_SIZE_PER_REPLICA *
mirrored_strategy.num_replicas_in_sync)
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100)
dataset = dataset.batch(global_batch_size)
LEARNING_RATES_BY_BATCH_SIZE = {5: 0.1, 10: 0.15}
learning_rate = LEARNING_RATES_BY_BATCH_SIZE[global_batch_size]
###Output
_____no_output_____
###Markdown
What's supported now?In TF 2.0 alpha release, we support training with Keras using `MirroredStrategy`, as well as one machine parameter server using `ParameterServerStrategy`. Support for other strategies will be coming soon. The API and how to use will be exactly the same as above. If you wish to use the other strategies like `TPUStrategy` or `MultiWorkerMirorredStrategy` in Keras in TF 2.0, you can currently do so by disabling eager execution (`tf.compat.v1.disable_eager_execution()`). Another thing to note is that when using `MultiWorkerMirorredStrategy` for multiple workers with Keras, currently the user will have to explicitly shard or shuffle the data for different workers, but we will change this in the future to automatically shard the input data intelligently. Examples and TutorialsHere is a list of tutorials and examples that illustrate the above integration end to end with Keras:1. [Tutorial](../tutorials/distribute/keras.ipynb) to train MNIST with `MirroredStrategy`.2. [Tutorial](tpu.ipynb) to train Fashion MNIST with `TPUStrategy` (currently uses `disable_eager_execution`)3. Official [ResNet50](https://github.com/tensorflow/models/blob/master/official/resnet/keras/keras_imagenet_main.py) training with ImageNet data using `MirroredStrategy`.4. [ResNet50](https://github.com/tensorflow/tpu/blob/master/models/experimental/resnet50_keras/resnet50.py) trained with Imagenet data on Cloud TPus with `TPUStrategy`. Note that this example only works with TensorFlow 1.x currently. Using `tf.distribute.Strategy` with Estimator`tf.estimator` is a distributed training TensorFlow API that originally supported the async parameter server approach. Like with Keras, we've integrated `tf.distribute.Strategy` into `tf.Estimator` so that a user who is using Estimator for their training can easily change their training is distributed with very few changes to your their code. With this, estimator users can now do synchronous distributed training on multiple GPUs and multiple workers, as well as use TPUs. The usage of `tf.distribute.Strategy` with Estimator is slightly different than the Keras case. Instead of using `strategy.scope`, now we pass the strategy object into the [`RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig) for the Estimator. Here is a snippet of code that shows this with a premade estimator `LinearRegressor` and `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
config = tf.estimator.RunConfig(
train_distribute=mirrored_strategy, eval_distribute=mirrored_strategy)
regressor = tf.estimator.LinearRegressor(
feature_columns=[tf.feature_column.numeric_column('feats')],
optimizer='SGD',
config=config)
###Output
_____no_output_____
###Markdown
We use a premade Estimator here, but the same code works with a custom Estimator as well. `train_distribute` determines how training will be distributed, and `eval_distribute` determines how evaluation will be distributed. This is another difference from Keras where we use the same strategy for both training and eval. Now we can train and evaluate this Estimator with an input function:
###Code
def input_fn():
dataset = tf.data.Dataset.from_tensors(({"feats":[1.]}, [1.]))
return dataset.repeat(1000).batch(10)
regressor.train(input_fn=input_fn, steps=10)
regressor.evaluate(input_fn=input_fn, steps=10)
###Output
_____no_output_____
###Markdown
Another difference to highlight here between Estimator and Keras is the input handling. In Keras, we mentioned that each batch of the dataset is split across the multiple replicas. In Estimator, however, the user provides an `input_fn` and have full control over how they want their data to be distributed across workers and devices. We do not do automatic splitting of batch, nor automatically shard the data across different workers. The provided `input_fn` is called once per worker, thus giving one dataset per worker. Then one batch from that dataset is fed to one replica on that worker, thereby consuming N batches for N replicas on 1 worker. In other words, the dataset returned by the `input_fn` should provide batches of size `PER_REPLICA_BATCH_SIZE`. And the global batch size for a step can be obtained as `PER_REPLICA_BATCH_SIZE * strategy.num_replicas_in_sync`. When doing multi worker training, users will also want to either split their data across the workers, or shuffle with a random seed on each. You can see an example of how to do this in the [multi-worker tutorial](../tutorials/distribute/multi_worker.ipynb). We showed an example of using `MirroredStrategy` with Estimator. You can also use `TPUStrategy` with Estimator as well, in the exact same way:```config = tf.estimator.RunConfig( train_distribute=tpu_strategy, eval_distribute=tpu_strategy)``` And similarly, you can use multi worker and parameter server strategies as well. The code remains the same, but you need to use `tf.estimator.train_and_evaluate`, and set "TF_CONFIG" environment variables for each binary running in your cluster. What's supported now?In TF 2.0 alpha release, we support training with Estimator using all strategies. Examples and TutorialsHere are some examples that show end to end usage of various strategies with Estimator:1. [Tutorial]((../tutorials/distribute/multi_worker.ipynb) to train MNIST with multiple workers using `MultiWorkerMirroredStrategy`.2. [End to end example](https://github.com/tensorflow/ecosystem/tree/master/distribution_strategy) for multi worker training in tensorflow/ecosystem using Kuberentes templates. This example starts with a Keras model and converts it to an Estimator using the `tf.keras.estimator.model_to_estimator` API. 3. Official [ResNet50](https://github.com/tensorflow/models/blob/master/official/resnet/imagenet_main.py) model, which can be trained using either `MirroredStrategy` or `MultiWorkerMirroredStrategy`.4. [ResNet50](https://github.com/tensorflow/tpu/blob/master/models/experimental/distribution_strategy/resnet_estimator.py) example with TPUStrategy. Using `tf.distribute.Strategy` with custom training loopsAs you've seen, using `tf.distrbute.Strategy` with high level APIs is only a couple lines of code change. With a little more effort, `tf.distrbute.Strategy` can also be used by other users who are not using these frameworks.TensorFlow is used for a wide variety of use cases and some users (such as researchers) require more flexibility and control over their training loops. This makes it hard for them to use the high level frameworks such as Estimator or Keras. For instance, someone using a GAN may want to take a different number of generator or discriminator steps each round. Similarly, the high level frameworks are not very suitable for Reinforcement Learning training. So these users will usually write their own training loops. For these users, we provide a core set of methods through the `tf.distrbute.Strategy` classes. Using these may require minor restructuring of the code initially, but once that is done, the user should be able to switch between GPUs / TPUs / multiple machines by just changing the strategy instance.Here we will show a brief snippet illustrating this use case for a simple training example using the same Keras model as before. Note: These APIs are still experimental and we are improving them to make them more user friendly in TensorFlow 2.0. First, we create the model and optimizer inside the strategy's scope. This ensures that any variables created with the model and optimizer are mirrored variables.
###Code
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
optimizer = tf.keras.optimizers.SGD()
###Output
_____no_output_____
###Markdown
Next, we create the input dataset and call `make_dataset_iterator` to distribute the dataset based on the strategy. This API is expected to change in the near future.
###Code
with mirrored_strategy.scope():
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(1000).batch(
global_batch_size)
input_iterator = mirrored_strategy.make_dataset_iterator(dataset)
###Output
_____no_output_____
###Markdown
Then, we define one step of the training. We will use `tf.GradientTape` to compute gradients and optimizer to apply those gradients to update our model's variables. To distribute this training step, we put in in a function `step_fn` and pass it to `strategy.experimental_run` along with the iterator created before:
###Code
@tf.function
def train_step():
def step_fn(inputs):
features, labels = inputs
with tf.GradientTape() as tape:
logits = model(features)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(
logits=logits, labels=labels)
loss = tf.reduce_sum(cross_entropy) * (1.0 / global_batch_size)
grads = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(list(zip(grads, model.trainable_variables)))
return loss
per_replica_losses = mirrored_strategy.experimental_run(
step_fn, input_iterator)
mean_loss = mirrored_strategy.reduce(
tf.distribute.ReduceOp.MEAN, per_replica_losses)
return mean_loss
###Output
_____no_output_____
###Markdown
A few other things to note in the code above: 1. We used `tf.nn.softmax_cross_entropy_with_logits` to compute the loss. And then we scaled the total loss by the global batch size. This is important because all the replicas are training in sync and number of examples in each step of training is the global batch. If you're using TensorFlow's standard losses from `tf.losses` or `tf.keras.losses`, they are distribution aware and will take care of the scaling by number of replicas whenever a strategy is in scope. 2. We used the `strategy.reduce` API to aggregate the results returned by `experimental_run`. `experimental_run` returns results from each local replica in the strategy, and there are multiple ways to consume this result. You can `reduce` them to get an aggregated value. You can also do `strategy.unwrap(results)`* to get the list of values contained in the result, one per local replica.*expected to change Finally, once we have defined the training step, we can initialize the iterator and run the training in a loop:
###Code
with mirrored_strategy.scope():
input_iterator.initialize()
for _ in range(10):
print(train_step())
###Output
_____no_output_____
###Markdown
Copyright 2018 The TensorFlow Authors.
###Code
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###Output
_____no_output_____
###Markdown
Distributed Training in TensorFlow View on TensorFlow.org Run in Google Colab View source on GitHub Overview`tf.distribute.Strategy` is a TensorFlow API to distribute trainingacross multiple GPUs, multiple machines or TPUs. Using this API, users can distribute their existing models and training code with minimal code changes.`tf.distribute.Strategy` has been designed with these key goals in mind:* Easy to use and support multiple user segments, including researchers, ML engineers, etc.* Provide good performance out of the box.* Easy switching between strategies.`tf.distribute.Strategy` can be used with TensorFlow's high level APIs, [tf.keras](https://www.tensorflow.org/guide/keras) and [tf.estimator](https://www.tensorflow.org/guide/estimators), with just a couple of lines of code change. It also provides an API that can be used to distribute custom training loops (and in general any computation using TensorFlow).In TensorFlow 2.0, users can execute their programs eagerly, or in a graph using [`tf.function`](../tutorials/eager/tf_function.ipynb). `tf.distribute.Strategy` intends to support both these modes of execution. Note that we may talk about training most of the time in this guide, but this API can also be used for distributing evaluation and prediction on different platforms.As you will see in a bit, very few changes are needed to use `tf.distribute.Strategy` with your code. This is because we have changed the underlying components of TensorFlow to become strategy-aware. This includes variables, layers, models, optimizers, metrics, summaries, and checkpoints.In this guide, we will talk about various types of strategies and how one can use them in a different situations.
###Code
# Import TensorFlow
from __future__ import absolute_import, division, print_function, unicode_literals
!pip install tf-nightly-gpu-2.0-preview
import tensorflow as tf
###Output
_____no_output_____
###Markdown
Types of strategies`tf.distribute.Strategy` intends to cover a number of use cases along different axes. Some of these combinations are currently supported and others will be added in the future. Some of these axes are:* Syncronous vs asynchronous training: These are two common ways of distributing training with data parallelism. In sync training, all workers train over different slices of input data in sync, and aggregating gradients at each step. In async training, all workers are independently training over the input data and updating variables asynchronously. Typically sync training is supported via all-reduce and async through parameter server architecture.* Hardware platform: Users may want to scale their training onto multiple GPUs on one machine, or multiple machines in a network (with 0 or more GPUs each), or on Cloud TPUs.In order to support these use cases, we have 4 strategies available. In the next section we will talk about which of these are supported in which scenarios in TF 2.0-alpha at this time. MirroredStrategy`tf.distribute.MirroredStrategy` support synchronous distributed training on multiple GPUs on one machine. It creates one replica per GPU device. Each variable in the model is mirrored across all the replicas. Together, these variables form a single conceptual variable called `MirroredVariable`. These variables are kept in sync with each other by applying identical updates.Efficient all-reduce algorithms are used to communicate the variable updates across the devices.All-reduce aggregates tensors across all the devices by adding them up, and makes them available on each device.It’s a fused algorithm that is very efficient and can reduce the overhead of synchronization significantly. There are many all-reduce algorithms and implementations available, depending on the type of communication available between devices. By default, it uses NVIDIA NCCL as the all-reduce implementation. The user can also choose between a few other options we provide, or write their own.Here is the simplest way of creating `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
###Output
_____no_output_____
###Markdown
This will create a `MirroredStrategy` instance which will use all the GPUs that are visible to TensorFlow, and use NCCL as the cross device communication.If you wish to use only some of the GPUs on your machine, you can do so like this:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(devices=["/gpu:0", "/gpu:1"])
###Output
_____no_output_____
###Markdown
If you wish to override the cross device communication, you can do so using the `cross_device_ops` argument by supplying an instance of `tf.distribute.CrossDeviceOps`. Currently we provide `tf.distribute.HierarchicalCopyAllReduce` and `tf.distribute.ReductionToOneDevice` as 2 other options other than `tf.distribute.NcclAllReduce` which is the default.
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(
cross_device_ops=tf.distribute.HierarchicalCopyAllReduce())
###Output
_____no_output_____
###Markdown
CentralStorageStrategy`tf.distribute.experimental.CentralStorageStrategy` does synchronous training as well. Variables are not mirrored, instead they are placed on the CPU and operations are replicated across all local GPUs. If there is only one GPU, all variables and operations will be placed on that GPU.Create a `CentralStorageStrategy` by:
###Code
central_storage_strategy = tf.distribute.experimental.CentralStorageStrategy()
###Output
_____no_output_____
###Markdown
This will create a `CentralStorageStrategy` instance which will use all visible GPUs and CPU. Update to variables on replicas will be aggragated before being applied to variables. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. MultiWorkerMirroredStrategy`tf.distribute.experimental.MultiWorkerMirroredStrategy` is very similar to `MirroredStrategy`. It implements synchronous distributed training across multiple workers, each with potentially multiple GPUs. Similar to `MirroredStrategy`, it creates copies of all variables in the model on each device across all workers.It uses [CollectiveOps](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/collective_ops.py) as the multi-worker all-reduce communication method used to keep variables in sync. A collective op is a single op in the TensorFlow graph which can automatically choose an all-reduce algorithm in the TensorFlow runtime according to hardware, network topology and tensor sizes.It also implements additional performance optimizations. For example, it includes a static optimization that converts multiple all-reductions on small tensors into fewer all-reductions on larger tensors. In addition, we are designing it to have a plugin architecture - so that in the future, users will be able to plugin algorithms that are better tuned for their hardware. Note that collective ops also implement other collective operations such as broadcast and all-gather.Here is the simplest way of creating `MultiWorkerMirroredStrategy`:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()
###Output
_____no_output_____
###Markdown
`MultiWorkerMirroredStrategy` currently allows you to choose between two different implementations of collective ops. `CollectiveCommunication.RING` implements ring-based collectives using gRPC as the communication layer. `CollectiveCommunication.NCCL` uses [Nvidia's NCCL](https://developer.nvidia.com/nccl) to implement collectives. `CollectiveCommunication.AUTO` defers the choice to the runtime. The best choice of collective implementation depends upon the number and kind of GPUs, and the network interconnect in the cluster. You can specify them like so:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy(
tf.distribute.experimental.CollectiveCommunication.NCCL)
###Output
_____no_output_____
###Markdown
One of the key differences to get multi worker training going, as compared to multi-GPU training, is the multi-worker setup. "TF_CONFIG" environment variable is the standard way in TensorFlow to specify the cluster configuration to each worker that is part of the cluster. See section on ["TF_CONFIG" below](TF_CONFIG) for more details on how this can be done. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. TPUStrategy`tf.distribute.experimental.TPUStrategy` lets users run their TensorFlow training on Tensor Processing Units (TPUs). TPUs are Google's specialized ASICs designed to dramatically accelerate machine learning workloads. They are available on Google Colab, the [TensorFlow Research Cloud](https://www.tensorflow.org/tfrc) and [Google Compute Engine](https://cloud.google.com/tpu).In terms of distributed training architecture, TPUStrategy is the same `MirroredStrategy` - it implements synchronous distributed training. TPUs provide their own implementation of efficient all-reduce and other collective operations across multiple TPU cores, which are used in `TPUStrategy`.Here is how you would instantiate `TPUStrategy`.Note: To run this code in Colab, you should select TPU as the Colab runtime. See [Using TPUs]( tpu.ipynb) guide for a runnable version.```resolver = tf.distribute.cluster_resolver.TPUClusterResolver()tf.tpu.experimental.initialize_tpu_system(resolver)tpu_strategy = tf.distribute.experimental.TPUStrategy(resolver)``` `TPUClusterResolver` instance helps locate the TPUs. In Colab, you don't need to specify any arguments to it. If you want to use this for Cloud TPUs, you will need to specify the name of your TPU resource in `tpu` argument. We also need to initialize the tpu system explicitly at the start of the program. This is required before TPUs can be used for computation and should ideally be done at the beginning because it also wipes out the TPU memory so all state will be lost. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. ParameterServerStrategy`tf.distribute.experimental.ParameterServerStrategy` supports parameter servers training on multiple machines. In this setup, some machines are designated as workers and some as parameter servers. Each variable of the model is placed on one parameter server. Computation is replicated across all GPUs of the all the workers.In terms of code, it looks similar to other strategies:```ps_strategy = tf.distribute.experimental.ParameterServerStrategy()``` For multi worker training, "TF_CONFIG" needs to specify the configuration of parameter servers and workers in your cluster, which you can read more about in ["TF_CONFIG" below](TF_CONFIG) below. So far we've talked about what are the different stategies available and how you can instantiate them. In the next few sections, we will talk about the different ways in which you can use them to distribute your training. We will show short code snippets in this guide and link off to full tutorials which you can run end to end. Using `tf.distribute.Strategy` with KerasWe've integrated `tf.distribute.Strategy` into `tf.keras` which is TensorFlow's implementation of the[Keras API specification](https://keras.io). `tf.keras` is a high-level API to build and train models. By integrating into `tf.keras` backend, we've made it seamless for Keras users to distribute their training written in the Keras training framework. The only things that need to change in a user's program are: (1) Create an instance of the appropriate `tf.distribute.Strategy` and (2) Move the creation and compiling of Keras model inside `strategy.scope`.Here is a snippet of code to do this for a very simple Keras model with one dense layer:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
model.compile(loss='mse', optimizer='sgd')
###Output
_____no_output_____
###Markdown
In this example we used `MirroredStrategy` so we can run this on a machine with multiple GPUs. `strategy.scope()` indicated which parts of the code to run distributed. Creating a model inside this scope allows us to create mirrored variables instead of regular variables. Compiling under the scope allows us to know that the user intends to train this model using this strategy. Once this is setup, you can fit your model like you would normally. `MirroredStrategy` takes care of replicating the model's training on the available GPUs, aggregating gradients etc.
###Code
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100).batch(10)
model.fit(dataset, epochs=2)
model.evaluate(dataset)
###Output
_____no_output_____
###Markdown
Here we used a `tf.data.Dataset` to provide the training and eval input. You can also use numpy arrays:
###Code
import numpy as np
inputs, targets = np.ones((100, 1)), np.ones((100, 1))
model.fit(inputs, targets, epochs=2, batch_size=10)
###Output
_____no_output_____
###Markdown
In both cases (dataset or numpy), each batch of the given input is divided equally among the multiple replicas. For instance, if using `MirroredStrategy` with 2 GPUs, each batch of size 10 will get divided among the 2 GPUs, with each receiving 5 input examples in each step. Each epoch will then train faster as you add more GPUs. Typically, you would want to increase your batch size as you add more accelerators so as to make effective use of the extra computing power. You will also need to re-tune your learning rate, depending on the model. You can use `strategy.num_replicas_in_sync` to get the number of replicas.
###Code
# Compute global batch size using number of replicas.
BATCH_SIZE_PER_REPLICA = 5
global_batch_size = (BATCH_SIZE_PER_REPLICA *
mirrored_strategy.num_replicas_in_sync)
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100)
dataset = dataset.batch(global_batch_size)
LEARNING_RATES_BY_BATCH_SIZE = {5: 0.1, 10: 0.15}
learning_rate = LEARNING_RATES_BY_BATCH_SIZE[global_batch_size]
###Output
_____no_output_____
###Markdown
What's supported now?In TF 2.0 alpha release, we support training with Keras using `MirroredStrategy`, as well as one machine parameter server using `ParameterServerStrategy`.Support for other strategies will be coming soon. The API and how to use will be exactly the same as above. If you wish to use the other strategies like `TPUStrategy` or `MultiWorkerMirorredStrategy` in Keras in TF 2.0, you can currently do so by disabling eager execution (`tf.compat.v1.disable_eager_execution()`). Another thing to note is that when using `MultiWorkerMirorredStrategy` for multiple workers with Keras, currently the user will have to explicitly shard or shuffle the data for different workers, but we will change this in the future to automatically shard the input data intelligently. Examples and TutorialsHere is a list of tutorials and examples that illustrate the above integration end to end with Keras:1. [Tutorial](../tutorials/distribute/keras.ipynb) to train MNIST with `MirroredStrategy`.2. Official [ResNet50](https://github.com/tensorflow/models/blob/master/official/resnet/keras/keras_imagenet_main.py) training with ImageNet data using `MirroredStrategy`.3. [ResNet50](https://github.com/tensorflow/tpu/blob/master/models/experimental/resnet50_keras/resnet50.py) trained with Imagenet data on Cloud TPus with `TPUStrategy`. Note that this example only works with TensorFlow 1.x currently. Using `tf.distribute.Strategy` with Estimator`tf.estimator` is a distributed training TensorFlow API that originally supported the async parameter server approach. Like with Keras, we've integrated `tf.distribute.Strategy` into `tf.Estimator` so that a user who is using Estimator for their training can easily change their training is distributed with very few changes to your their code. With this, estimator users can now do synchronous distributed training on multiple GPUs and multiple workers, as well as use TPUs.The usage of `tf.distribute.Strategy` with Estimator is slightly different than the Keras case. Instead of using `strategy.scope`, now we pass the strategy object into the [`RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig) for the Estimator.Here is a snippet of code that shows this with a premade estimator `LinearRegressor` and `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
config = tf.estimator.RunConfig(
train_distribute=mirrored_strategy, eval_distribute=mirrored_strategy)
regressor = tf.estimator.LinearRegressor(
feature_columns=[tf.feature_column.numeric_column('feats')],
optimizer='SGD',
config=config)
###Output
_____no_output_____
###Markdown
We use a premade Estimator here, but the same code works with a custom Estimator as well. `train_distribute` determines how training will be distributed, and `eval_distribute` determines how evaluation will be distributed. This is another difference from Keras where we use the same strategy for both training and eval.Now we can train and evaluate this Estimator with an input function:
###Code
def input_fn():
dataset = tf.data.Dataset.from_tensors(({"feats":[1.]}, [1.]))
return dataset.repeat(1000).batch(10)
regressor.train(input_fn=input_fn, steps=10)
regressor.evaluate(input_fn=input_fn, steps=10)
###Output
_____no_output_____
###Markdown
Another difference to highlight here between Estimator and Keras is the input handling. In Keras, we mentioned that each batch of the dataset is split across the multiple replicas. In Estimator, however, the user provides an `input_fn` and have full control over how they want their data to be distributed across workers and devices. We do not do automatic splitting of batch, nor automatically shard the data across different workers. The provided `input_fn` is called once per worker, thus giving one dataset per worker. Then one batch from that dataset is fed to one replica on that worker, thereby consuming N batches for N replicas on 1 worker. In other words, the dataset returned by the `input_fn` should provide batches of size `PER_REPLICA_BATCH_SIZE`. And the global batch size for a step can be obtained as `PER_REPLICA_BATCH_SIZE * strategy.num_replicas_in_sync`. When doing multi worker training, users will also want to either split their data across the workers, or shuffle with a random seed on each. You can see an example of how to do this in the [multi-worker tutorial](../tutorials/distribute/multi_worker.ipynb). We showed an example of using `MirroredStrategy` with Estimator. You can also use `TPUStrategy` with Estimator as well, in the exact same way:```config = tf.estimator.RunConfig( train_distribute=tpu_strategy, eval_distribute=tpu_strategy)``` And similarly, you can use multi worker and parameter server strategies as well. The code remains the same, but you need to use `tf.estimator.train_and_evaluate`, and set "TF_CONFIG" environment variables for each binary running in your cluster. What's supported now?In TF 2.0 alpha release, we support training with Estimator using all strategies. Examples and TutorialsHere are some examples that show end to end usage of various strategies with Estimator:1. [Tutorial](../tutorials/distribute/multi_worker.ipynb) to train MNIST with multiple workers using `MultiWorkerMirroredStrategy`.2. [End to end example](https://github.com/tensorflow/ecosystem/tree/master/distribution_strategy) for multi worker training in tensorflow/ecosystem using Kuberentes templates. This example starts with a Keras model and converts it to an Estimator using the `tf.keras.estimator.model_to_estimator` API.3. Official [ResNet50](https://github.com/tensorflow/models/blob/master/official/resnet/imagenet_main.py) model, which can be trained using either `MirroredStrategy` or `MultiWorkerMirroredStrategy`.4. [ResNet50](https://github.com/tensorflow/tpu/blob/master/models/experimental/distribution_strategy/resnet_estimator.py) example with TPUStrategy. Using `tf.distribute.Strategy` with custom training loopsAs you've seen, using `tf.distrbute.Strategy` with high level APIs is only a couple lines of code change. With a little more effort, `tf.distrbute.Strategy` can also be used by other users who are not using these frameworks.TensorFlow is used for a wide variety of use cases and some users (such as researchers) require more flexibility and control over their training loops. This makes it hard for them to use the high level frameworks such as Estimator or Keras. For instance, someone using a GAN may want to take a different number of generator or discriminator steps each round. Similarly, the high level frameworks are not very suitable for Reinforcement Learning training. So these users will usually write their own training loops.For these users, we provide a core set of methods through the `tf.distrbute.Strategy` classes. Using these may require minor restructuring of the code initially, but once that is done, the user should be able to switch between GPUs / TPUs / multiple machines by just changing the strategy instance.Here we will show a brief snippet illustrating this use case for a simple training example using the same Keras model as before.Note: These APIs are still experimental and we are improving them to make them more user friendly in TensorFlow 2.0. First, we create the model and optimizer inside the strategy's scope. This ensures that any variables created with the model and optimizer are mirrored variables.
###Code
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
optimizer = tf.keras.optimizers.SGD()
###Output
_____no_output_____
###Markdown
Next, we create the input dataset and call `make_dataset_iterator` to distribute the dataset based on the strategy. This API is expected to change in the near future.
###Code
with mirrored_strategy.scope():
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(1000).batch(
global_batch_size)
input_iterator = mirrored_strategy.make_dataset_iterator(dataset)
###Output
_____no_output_____
###Markdown
Then, we define one step of the training. We will use `tf.GradientTape` to compute gradients and optimizer to apply those gradients to update our model's variables. To distribute this training step, we put in in a function `step_fn` and pass it to `strategy.experimental_run` along with the iterator created before:
###Code
@tf.function
def train_step():
def step_fn(inputs):
features, labels = inputs
with tf.GradientTape() as tape:
logits = model(features)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(
logits=logits, labels=labels)
loss = tf.reduce_sum(cross_entropy) * (1.0 / global_batch_size)
grads = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(list(zip(grads, model.trainable_variables)))
return loss
per_replica_losses = mirrored_strategy.experimental_run(
step_fn, input_iterator)
mean_loss = mirrored_strategy.reduce(
tf.distribute.ReduceOp.SUM, per_replica_losses, axis=None)
return mean_loss
###Output
_____no_output_____
###Markdown
A few other things to note in the code above:1. We used `tf.nn.softmax_cross_entropy_with_logits` to compute the loss. And then we scaled the total loss by the global batch size. This is important because all the replicas are training in sync and number of examples in each step of training is the global batch. So the loss needs to be divided by the global batch size and not by the replica (local) batch size.2. We used the `strategy.reduce` API to aggregate the results returned by `experimental_run`. `experimental_run` returns results from each local replica in the strategy, and there are multiple ways to consume this result. You can `reduce` them to get an aggregated value. You can also do `strategy.unwrap(results)`* to get the list of values contained in the result, one per local replica.3. When `apply_gradients` is called within a distribution strategy scope, its behavior is modified. Specifically, before applying gradients on each parallel instance during synchronous training, it performs a sum-over-all-replicas of the gradients.*expected to change Finally, once we have defined the training step, we can initialize the iterator and run the training in a loop:
###Code
with mirrored_strategy.scope():
input_iterator.initialize()
for _ in range(10):
print(train_step())
###Output
_____no_output_____
###Markdown
Copyright 2018 The TensorFlow Authors.
###Code
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###Output
_____no_output_____
###Markdown
Distributed Training in TensorFlow View on TensorFlow.org Run in Google Colab View source on GitHub Overview`tf.distribute.Strategy` is a TensorFlow API to distribute trainingacross multiple GPUs, multiple machines or TPUs. Using this API, users can distribute their existing models and training code with minimal code changes.`tf.distribute.Strategy` has been designed with these key goals in mind:* Easy to use and support multiple user segments, including researchers, ML engineers, etc.* Provide good performance out of the box.* Easy switching between strategies.`tf.distribute.Strategy` can be used with TensorFlow's high level APIs, [tf.keras](https://www.tensorflow.org/guide/keras) and [tf.estimator](https://www.tensorflow.org/guide/estimators), with just a couple of lines of code change. It also provides an API that can be used to distribute custom training loops (and in general any computation using TensorFlow).In TensorFlow 2.0, users can execute their programs eagerly, or in a graph using [`tf.function`](../tutorials/eager/tf_function.ipynb). `tf.distribute.Strategy` intends to support both these modes of execution. Note that we may talk about training most of the time in this guide, but this API can also be used for distributing evaluation and prediction on different platforms.As you will see in a bit, very few changes are needed to use `tf.distribute.Strategy` with your code. This is because we have changed the underlying components of TensorFlow to become strategy-aware. This includes variables, layers, models, optimizers, metrics, summaries, and checkpoints. In this guide, we will talk about various types of strategies and how one can use them in a different situations.
###Code
# Import TensorFlow
from __future__ import absolute_import, division, print_function
!pip install tensorflow-gpu==2.0.0-alpha0
import tensorflow as tf
###Output
_____no_output_____
###Markdown
Types of strategies`tf.distribute.Strategy` intends to cover a number of use cases along different axes. Some of these combinations are currently supported and others will be added in the future. Some of these axes are:* Syncronous vs asynchronous training: These are two common ways of distributing training with data parallelism. In sync training, all workers train over different slices of input data in sync, and aggregating gradients at each step. In async training, all workers are independently training over the input data and updating variables asynchronously. Typically sync training is supported via all-reduce and async through parameter server architecture.* Hardware platform: Users may want to scale their training onto multiple GPUs on one machine, or multiple machines in a network (with 0 or more GPUs each), or on Cloud TPUs.In order to support these use cases, we have 4 strategies available. In the next section we will talk about which of these are supported in which scenarios in TF 2.0-alpha at this time. MirroredStrategy`tf.distribute.MirroredStrategy` support synchronous distributed training on multiple GPUs on one machine. It creates one replica per GPU device. Each variable in the model is mirrored across all the replicas. Together, these variables form a single conceptual variable called `MirroredVariable`. These variables are kept in sync with each other by applying identical updates.Efficient all-reduce algorithms are used to communicate the variable updates across the devices.All-reduce aggregates tensors across all the devices by adding them up, and makes them available on each device.It’s a fused algorithm that is very efficient and can reduce the overhead of synchronization significantly. There are many all-reduce algorithms and implementations available, depending on the type of communication available between devices. By default, it uses NVIDIA NCCL as the all-reduce implementation. The user can also choose between a few other options we provide, or write their own.Here is the simplest way of creating `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
###Output
_____no_output_____
###Markdown
This will create a `MirroredStrategy` instance which will use all the GPUs that are visible to TensorFlow, and use NCCL as the cross device communication.If you wish to use only some of the GPUs on your machine, you can do so like this:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(devices=["/gpu:0", "/gpu:1"])
###Output
_____no_output_____
###Markdown
If you wish to override the cross device communication, you can do so using the `cross_device_ops` argument by supplying an instance of `tf.distribute.CrossDeviceOps`. Currently we provide `tf.distribute.HierarchicalCopyAllReduce` and `tf.distribute.ReductionToOneDevice` as 2 other options other than `tf.distribute.NcclAllReduce` which is the default.
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(
cross_device_ops=tf.distribute.HierarchicalCopyAllReduce())
###Output
_____no_output_____
###Markdown
MultiWorkerMirroredStrategy`tf.distribute.experimental.MultiWorkerMirroredStrategy` is very similar to `MirroredStrategy`. It implements synchronous distributed training across multiple workers, each with potentially multiple GPUs. Similar to `MirroredStrategy`, it creates copies of all variables in the model on each device across all workers. It uses [CollectiveOps](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/collective_ops.py) as the multi-worker all-reduce communication method used to keep variables in sync. A collective op is a single op in the TensorFlow graph which can automatically choose an all-reduce algorithm in the TensorFlow runtime according to hardware, network topology and tensor sizes. It also implements additional performance optimizations. For example, it includes a static optimization that converts multiple all-reductions on small tensors into fewer all-reductions on larger tensors. In addition, we are designing it to have a plugin architecture - so that in the future, users will be able to plugin algorithms that are better tuned for their hardware. Note that collective ops also implement other collective operations such as broadcast and all-gather. Here is the simplest way of creating `MultiWorkerMirroredStrategy`:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()
###Output
_____no_output_____
###Markdown
`MultiWorkerMirroredStrategy` currently allows you to choose between two different implementations of collective ops. `CollectiveCommunication.RING` implements ring-based collectives using gRPC as the communication layer. `CollectiveCommunication.NCCL` uses [Nvidia's NCCL](https://developer.nvidia.com/nccl) to implement collectives. `CollectiveCommunication.AUTO` defers the choice to the runtime. The best choice of collective implementation depends upon the number and kind of GPUs, and the network interconnect in the cluster. You can specify them like so:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy(
tf.distribute.experimental.CollectiveCommunication.NCCL)
###Output
_____no_output_____
###Markdown
One of the key differences to get multi worker training going, as compared to multi-GPU training, is the multi-worker setup. "TF_CONFIG" environment variable is the standard way in TensorFlow to specify the cluster configuration to each worker that is part of the cluster. See section on ["TF_CONFIG" below](TF_CONFIG) for more details on how this can be done. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. TPUStrategy`tf.distribute.experimental.TPUStrategy` lets users run their TensorFlow training on Tensor Processing Units (TPUs). TPUs are Google's specialized ASICs designed to dramatically accelerate machine learning workloads. They are available on Google Colab, the [TensorFlow Research Cloud](https://www.tensorflow.org/tfrc) and [Google Compute Engine](https://cloud.google.com/tpu).In terms of distributed training architecture, TPUStrategy is the same `MirroredStrategy` - it implements synchronous distributed training. TPUs provide their own implementation of efficient all-reduce and other collective operations across multiple TPU cores, which are used in `TPUStrategy`. Here is how you would instantiate `TPUStrategy`.Note: To run this code in Colab, you should select TPU as the Colab runtime. See [Using TPUs]( tpu.ipynb) guide for a runnable version.```resolver = tf.distribute.cluster_resolver.TPUClusterResolver()tf.tpu.experimental.initialize_tpu_system(resolver)tpu_strategy = tf.distribute.experimental.TPUStrategy(resolver)``` `TPUClusterResolver` instance helps locate the TPUs. In Colab, you don't need to specify any arguments to it. If you want to use this for Cloud TPUs, you will need to specify the name of your TPU resource in `tpu` argument. We also need to initialize the tpu system explicitly at the start of the program. This is required before TPUs can be used for computation and should ideally be done at the beginning because it also wipes out the TPU memory so all state will be lost. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. ParameterServerStrategy`tf.distribute.experimental.ParameterServerStrategy` supports parameter servers training. It can be used either for multi-GPU synchronous local training or asynchronous multi-machine training. When used to train locally on one machine, variables are not mirrored, instead they are placed on the CPU and operations are replicated across all local GPUs. In a multi-machine setting, some machines are designated as workers and some as parameter servers. Each variable of the model is placed on one parameter server. Computation is replicated across all GPUs of the all the workers.In terms of code, it looks similar to other strategies:
###Code
ps_strategy = tf.distribute.experimental.ParameterServerStrategy()
###Output
_____no_output_____
###Markdown
For multi worker training, "TF_CONFIG" needs to specify the configuration of parameter servers and workers in your cluster, which you can read more about in ["TF_CONFIG" below](TF_CONFIG) below. So far we've talked about what are the different stategies available and how you can instantiate them. In the next few sections, we will talk about the different ways in which you can use them to distribute your training. We will show short code snippets in this guide and link off to full tutorials which you can run end to end. Using `tf.distribute.Strategy` with KerasWe've integrated `tf.distribute.Strategy` into `tf.keras` which is TensorFlow's implementation of the[Keras API specification](https://keras.io). `tf.keras` is a high-level API to build and train models. By integrating into `tf.keras` backend, we've made it seamless for Keras users to distribute their training written in the Keras training framework. The only things that need to change in a user's program are: (1) Create an instance of the appropriate `tf.distribute.Strategy` and (2) Move the creation and compiling of Keras model inside `strategy.scope`. Here is a snippet of code to do this for a very simple Keras model with one dense layer:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
model.compile(loss='mse', optimizer='sgd')
###Output
_____no_output_____
###Markdown
In this example we used `MirroredStrategy` so we can run this on a machine with multiple GPUs. `strategy.scope()` indicated which parts of the code to run distributed. Creating a model inside this scope allows us to create mirrored variables instead of regular variables. Compiling under the scope allows us to know that the user intends to train this model using this strategy. Once this is setup, you can fit your model like you would normally. `MirroredStrategy` takes care of replicating the model's training on the available GPUs, aggregating gradients etc.
###Code
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100).batch(10)
model.fit(dataset, epochs=2)
model.evaluate(dataset)
###Output
_____no_output_____
###Markdown
Here we used a `tf.data.Dataset` to provide the training and eval input. You can also use numpy arrays:
###Code
import numpy as np
inputs, targets = np.ones((100, 1)), np.ones((100, 1))
model.fit(inputs, targets, epochs=2, batch_size=10)
###Output
_____no_output_____
###Markdown
In both cases (dataset or numpy), each batch of the given input is divided equally among the multiple replicas. For instance, if using `MirroredStrategy` with 2 GPUs, each batch of size 10 will get divided among the 2 GPUs, with each receiving 5 input examples in each step. Each epoch will then train faster as you add more GPUs. Typically, you would want to increase your batch size as you add more accelerators so as to make effective use of the extra computing power. You will also need to re-tune your learning rate, depending on the model. You can use `strategy.num_replicas_in_sync` to get the number of replicas.
###Code
# Compute global batch size using number of replicas.
BATCH_SIZE_PER_REPLICA = 5
global_batch_size = (BATCH_SIZE_PER_REPLICA *
mirrored_strategy.num_replicas_in_sync)
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100)
dataset = dataset.batch(global_batch_size)
LEARNING_RATES_BY_BATCH_SIZE = {5: 0.1, 10: 0.15}
learning_rate = LEARNING_RATES_BY_BATCH_SIZE[global_batch_size]
###Output
_____no_output_____
###Markdown
What's supported now?In TF 2.0 alpha release, we support training with Keras using `MirroredStrategy`, as well as one machine parameter server using `ParameterServerStrategy`. Support for other strategies will be coming soon. The API and how to use will be exactly the same as above. If you wish to use the other strategies like `TPUStrategy` or `MultiWorkerMirorredStrategy` in Keras in TF 2.0, you can currently do so by disabling eager execution (`tf.compat.v1.disable_eager_execution()`). Another thing to note is that when using `MultiWorkerMirorredStrategy` for multiple workers with Keras, currently the user will have to explicitly shard or shuffle the data for different workers, but we will change this in the future to automatically shard the input data intelligently. Examples and TutorialsHere is a list of tutorials and examples that illustrate the above integration end to end with Keras:1. [Tutorial](../tutorials/distribute/keras.ipynb) to train MNIST with `MirroredStrategy`.2. [Tutorial](tpu.ipynb) to train Fashion MNIST with `TPUStrategy` (currently uses `disable_eager_execution`)3. Official [ResNet50](https://github.com/tensorflow/models/blob/master/official/resnet/keras/keras_imagenet_main.py) training with ImageNet data using `MirroredStrategy`.4. [ResNet50](https://github.com/tensorflow/tpu/blob/master/models/experimental/resnet50_keras/resnet50.py) trained with Imagenet data on Cloud TPus with `TPUStrategy`. Note that this example only works with TensorFlow 1.x currently. Using `tf.distribute.Strategy` with Estimator`tf.estimator` is a distributed training TensorFlow API that originally supported the async parameter server approach. Like with Keras, we've integrated `tf.distribute.Strategy` into `tf.Estimator` so that a user who is using Estimator for their training can easily change their training is distributed with very few changes to your their code. With this, estimator users can now do synchronous distributed training on multiple GPUs and multiple workers, as well as use TPUs. The usage of `tf.distribute.Strategy` with Estimator is slightly different than the Keras case. Instead of using `strategy.scope`, now we pass the strategy object into the [`RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig) for the Estimator. Here is a snippet of code that shows this with a premade estimator `LinearRegressor` and `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
config = tf.estimator.RunConfig(
train_distribute=mirrored_strategy, eval_distribute=mirrored_strategy)
regressor = tf.estimator.LinearRegressor(
feature_columns=[tf.feature_column.numeric_column('feats')],
optimizer='SGD',
config=config)
###Output
_____no_output_____
###Markdown
We use a premade Estimator here, but the same code works with a custom Estimator as well. `train_distribute` determines how training will be distributed, and `eval_distribute` determines how evaluation will be distributed. This is another difference from Keras where we use the same strategy for both training and eval. Now we can train and evaluate this Estimator with an input function:
###Code
def input_fn():
dataset = tf.data.Dataset.from_tensors(({"feats":[1.]}, [1.]))
return dataset.repeat(1000).batch(10)
regressor.train(input_fn=input_fn, steps=10)
regressor.evaluate(input_fn=input_fn, steps=10)
###Output
_____no_output_____
###Markdown
Another difference to highlight here between Estimator and Keras is the input handling. In Keras, we mentioned that each batch of the dataset is split across the multiple replicas. In Estimator, however, the user provides an `input_fn` and have full control over how they want their data to be distributed across workers and devices. We do not do automatic splitting of batch, nor automatically shard the data across different workers. The provided `input_fn` is called once per worker, thus giving one dataset per worker. Then one batch from that dataset is fed to one replica on that worker, thereby consuming N batches for N replicas on 1 worker. In other words, the dataset returned by the `input_fn` should provide batches of size `PER_REPLICA_BATCH_SIZE`. And the global batch size for a step can be obtained as `PER_REPLICA_BATCH_SIZE * strategy.num_replicas_in_sync`. When doing multi worker training, users will also want to either split their data across the workers, or shuffle with a random seed on each. You can see an example of how to do this in the [multi-worker tutorial](../tutorials/distribute/multi_worker.ipynb). We showed an example of using `MirroredStrategy` with Estimator. You can also use `TPUStrategy` with Estimator as well, in the exact same way:```config = tf.estimator.RunConfig( train_distribute=tpu_strategy, eval_distribute=tpu_strategy)``` And similarly, you can use multi worker and parameter server strategies as well. The code remains the same, but you need to use `tf.estimator.train_and_evaluate`, and set "TF_CONFIG" environment variables for each binary running in your cluster. What's supported now?In TF 2.0 alpha release, we support training with Estimator using all strategies. Examples and TutorialsHere are some examples that show end to end usage of various strategies with Estimator:1. [Tutorial]((../tutorials/distribute/multi_worker.ipynb) to train MNIST with multiple workers using `MultiWorkerMirroredStrategy`.2. [End to end example](https://github.com/tensorflow/ecosystem/tree/master/distribution_strategy) for multi worker training in tensorflow/ecosystem using Kuberentes templates. This example starts with a Keras model and converts it to an Estimator using the `tf.keras.estimator.model_to_estimator` API. 3. Official [ResNet50](https://github.com/tensorflow/models/blob/master/official/resnet/imagenet_main.py) model, which can be trained using either `MirroredStrategy` or `MultiWorkerMirroredStrategy`.4. [ResNet50](https://github.com/tensorflow/tpu/blob/master/models/experimental/distribution_strategy/resnet_estimator.py) example with TPUStrategy. Using `tf.distribute.Strategy` with custom training loopsAs you've seen, using `tf.distrbute.Strategy` with high level APIs is only a couple lines of code change. With a little more effort, `tf.distrbute.Strategy` can also be used by other users who are not using these frameworks.TensorFlow is used for a wide variety of use cases and some users (such as researchers) require more flexibility and control over their training loops. This makes it hard for them to use the high level frameworks such as Estimator or Keras. For instance, someone using a GAN may want to take a different number of generator or discriminator steps each round. Similarly, the high level frameworks are not very suitable for Reinforcement Learning training. So these users will usually write their own training loops. For these users, we provide a core set of methods through the `tf.distrbute.Strategy` classes. Using these may require minor restructuring of the code initially, but once that is done, the user should be able to switch between GPUs / TPUs / multiple machines by just changing the strategy instance.Here we will show a brief snippet illustrating this use case for a simple training example using the same Keras model as before. Note: These APIs are still experimental and we are improving them to make them more user friendly in TensorFlow 2.0. First, we create the model and optimizer inside the strategy's scope. This ensures that any variables created with the model and optimizer are mirrored variables.
###Code
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
optimizer = tf.keras.optimizers.SGD()
###Output
_____no_output_____
###Markdown
Next, we create the input dataset and call `make_dataset_iterator` to distribute the dataset based on the strategy. This API is expected to change in the near future.
###Code
with mirrored_strategy.scope():
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(1000).batch(
global_batch_size)
input_iterator = mirrored_strategy.make_dataset_iterator(dataset)
###Output
_____no_output_____
###Markdown
Then, we define one step of the training. We will use `tf.GradientTape` to compute gradients and optimizer to apply those gradients to update our model's variables. To distribute this training step, we put in in a function `step_fn` and pass it to `strategy.experimental_run` along with the iterator created before:
###Code
@tf.function
def train_step():
def step_fn(inputs):
features, labels = inputs
with tf.GradientTape() as tape:
logits = model(features)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(
logits=logits, labels=labels)
loss = tf.reduce_sum(cross_entropy) * (1.0 / global_batch_size)
grads = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(list(zip(grads, model.trainable_variables)))
return loss
per_replica_losses = mirrored_strategy.experimental_run(
step_fn, input_iterator)
mean_loss = mirrored_strategy.reduce(
tf.distribute.ReduceOp.MEAN, per_replica_losses)
return mean_loss
###Output
_____no_output_____
###Markdown
A few other things to note in the code above: 1. We used `tf.nn.softmax_cross_entropy_with_logits` to compute the loss. And then we scaled the total loss by the global batch size. This is important because all the replicas are training in sync and number of examples in each step of training is the global batch. If you're using TensorFlow's standard losses from `tf.losses` or `tf.keras.losses`, they are distribution aware and will take care of the scaling by number of replicas whenever a strategy is in scope. 2. We used the `strategy.reduce` API to aggregate the results returned by `experimental_run`. `experimental_run` returns results from each local replica in the strategy, and there are multiple ways to consume this result. You can `reduce` them to get an aggregated value. You can also do `strategy.unwrap(results)`* to get the list of values contained in the result, one per local replica.*expected to change Finally, once we have defined the training step, we can initialize the iterator and run the training in a loop:
###Code
with mirrored_strategy.scope():
input_iterator.initialize()
for _ in range(10):
print(train_step())
###Output
_____no_output_____
###Markdown
Copyright 2018 The TensorFlow Authors.
###Code
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###Output
_____no_output_____
###Markdown
Distributed Training in TensorFlow View on TensorFlow.org Run in Google Colab View source on GitHub Overview`tf.distribute.Strategy` is a TensorFlow API to distribute trainingacross multiple GPUs, multiple machines or TPUs. Using this API, users can distribute their existing models and training code with minimal code changes.`tf.distribute.Strategy` has been designed with these key goals in mind:* Easy to use and support multiple user segments, including researchers, ML engineers, etc.* Provide good performance out of the box.* Easy switching between strategies.`tf.distribute.Strategy` can be used with TensorFlow's high level APIs, [tf.keras](https://www.tensorflow.org/guide/keras) and [tf.estimator](https://www.tensorflow.org/guide/estimators), with just a couple of lines of code change. It also provides an API that can be used to distribute custom training loops (and in general any computation using TensorFlow).In TensorFlow 2.0, users can execute their programs eagerly, or in a graph using [`tf.function`](../tutorials/eager/tf_function.ipynb). `tf.distribute.Strategy` intends to support both these modes of execution. Note that we may talk about training most of the time in this guide, but this API can also be used for distributing evaluation and prediction on different platforms.As you will see in a bit, very few changes are needed to use `tf.distribute.Strategy` with your code. This is because we have changed the underlying components of TensorFlow to become strategy-aware. This includes variables, layers, models, optimizers, metrics, summaries, and checkpoints. In this guide, we will talk about various types of strategies and how one can use them in a different situations.
###Code
# Import TensorFlow
from __future__ import absolute_import, division, print_function
!pip install tensorflow-gpu==2.0.0-alpha0
import tensorflow as tf
###Output
_____no_output_____
###Markdown
Types of strategies`tf.distribute.Strategy` intends to cover a number of use cases along different axes. Some of these combinations are currently supported and others will be added in the future. Some of these axes are:* Syncronous vs asynchronous training: These are two common ways of distributing training with data parallelism. In sync training, all workers train over different slices of input data in sync, and aggregating gradients at each step. In async training, all workers are independently training over the input data and updating variables asynchronously. Typically sync training is supported via all-reduce and async through parameter server architecture.* Hardware platform: Users may want to scale their training onto multiple GPUs on one machine, or multiple machines in a network (with 0 or more GPUs each), or on Cloud TPUs.In order to support these use cases, we have 4 strategies available. In the next section we will talk about which of these are supported in which scenarios in TF 2.0-alpha at this time. MirroredStrategy`tf.distribute.MirroredStrategy` support synchronous distributed training on multiple GPUs on one machine. It creates one replica per GPU device. Each variable in the model is mirrored across all the replicas. Together, these variables form a single conceptual variable called `MirroredVariable`. These variables are kept in sync with each other by applying identical updates.Efficient all-reduce algorithms are used to communicate the variable updates across the devices.All-reduce aggregates tensors across all the devices by adding them up, and makes them available on each device.It’s a fused algorithm that is very efficient and can reduce the overhead of synchronization significantly. There are many all-reduce algorithms and implementations available, depending on the type of communication available between devices. By default, it uses NVIDIA NCCL as the all-reduce implementation. The user can also choose between a few other options we provide, or write their own.Here is the simplest way of creating `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
###Output
_____no_output_____
###Markdown
This will create a `MirroredStrategy` instance which will use all the GPUs that are visible to TensorFlow, and use NCCL as the cross device communication.If you wish to use only some of the GPUs on your machine, you can do so like this:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(devices=["/gpu:0", "/gpu:1"])
###Output
_____no_output_____
###Markdown
If you wish to override the cross device communication, you can do so using the `cross_device_ops` argument by supplying an instance of `tf.distribute.CrossDeviceOps`. Currently we provide `tf.distribute.HierarchicalCopyAllReduce` and `tf.distribute.ReductionToOneDevice` as 2 other options other than `tf.distribute.NcclAllReduce` which is the default.
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(
cross_device_ops=tf.distribute.HierarchicalCopyAllReduce())
###Output
_____no_output_____
###Markdown
MultiWorkerMirroredStrategy`tf.distribute.experimental.MultiWorkerMirroredStrategy` is very similar to `MirroredStrategy`. It implements synchronous distributed training across multiple workers, each with potentially multiple GPUs. Similar to `MirroredStrategy`, it creates copies of all variables in the model on each device across all workers. It uses [CollectiveOps](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/collective_ops.py) as the multi-worker all-reduce communication method used to keep variables in sync. A collective op is a single op in the TensorFlow graph which can automatically choose an all-reduce algorithm in the TensorFlow runtime according to hardware, network topology and tensor sizes. It also implements additional performance optimizations. For example, it includes a static optimization that converts multiple all-reductions on small tensors into fewer all-reductions on larger tensors. In addition, we are designing it to have a plugin architecture - so that in the future, users will be able to plugin algorithms that are better tuned for their hardware. Note that collective ops also implement other collective operations such as broadcast and all-gather. Here is the simplest way of creating `MultiWorkerMirroredStrategy`:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()
###Output
_____no_output_____
###Markdown
`MultiWorkerMirroredStrategy` currently allows you to choose between two different implementations of collective ops. `CollectiveCommunication.RING` implements ring-based collectives using gRPC as the communication layer. `CollectiveCommunication.NCCL` uses [Nvidia's NCCL](https://developer.nvidia.com/nccl) to implement collectives. `CollectiveCommunication.AUTO` defers the choice to the runtime. The best choice of collective implementation depends upon the number and kind of GPUs, and the network interconnect in the cluster. You can specify them like so:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy(
tf.distribute.experimental.CollectiveCommunication.NCCL)
###Output
_____no_output_____
###Markdown
One of the key differences to get multi worker training going, as compared to multi-GPU training, is the multi-worker setup. "TF_CONFIG" environment variable is the standard way in TensorFlow to specify the cluster configuration to each worker that is part of the cluster. See section on ["TF_CONFIG" below](TF_CONFIG) for more details on how this can be done. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. TPUStrategy`tf.distribute.experimental.TPUStrategy` lets users run their TensorFlow training on Tensor Processing Units (TPUs). TPUs are Google's specialized ASICs designed to dramatically accelerate machine learning workloads. They are available on Google Colab, the [TensorFlow Research Cloud](https://www.tensorflow.org/tfrc) and [Google Compute Engine](https://cloud.google.com/tpu).In terms of distributed training architecture, TPUStrategy is the same `MirroredStrategy` - it implements synchronous distributed training. TPUs provide their own implementation of efficient all-reduce and other collective operations across multiple TPU cores, which are used in `TPUStrategy`. Here is how you would instantiate `TPUStrategy`.Note: To run this code in Colab, you should select TPU as the Colab runtime. See [Using TPUs]( tpu.ipynb) guide for a runnable version.```resolver = tf.distribute.cluster_resolver.TPUClusterResolver()tf.tpu.experimental.initialize_tpu_system(resolver)tpu_strategy = tf.distribute.experimental.TPUStrategy(resolver)``` `TPUClusterResolver` instance helps locate the TPUs. In Colab, you don't need to specify any arguments to it. If you want to use this for Cloud TPUs, you will need to specify the name of your TPU resource in `tpu` argument. We also need to initialize the tpu system explicitly at the start of the program. This is required before TPUs can be used for computation and should ideally be done at the beginning because it also wipes out the TPU memory so all state will be lost. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. ParameterServerStrategy`tf.distribute.experimental.ParameterServerStrategy` supports parameter servers training. It can be used either for multi-GPU synchronous local training or asynchronous multi-machine training. When used to train locally on one machine, variables are not mirrored, instead they are placed on the CPU and operations are replicated across all local GPUs. In a multi-machine setting, some machines are designated as workers and some as parameter servers. Each variable of the model is placed on one parameter server. Computation is replicated across all GPUs of the all the workers.In terms of code, it looks similar to other strategies:
###Code
ps_strategy = tf.distribute.experimental.ParameterServerStrategy()
###Output
_____no_output_____
###Markdown
For multi worker training, "TF_CONFIG" needs to specify the configuration of parameter servers and workers in your cluster, which you can read more about in ["TF_CONFIG" below](TF_CONFIG) below. So far we've talked about what are the different stategies available and how you can instantiate them. In the next few sections, we will talk about the different ways in which you can use them to distribute your training. We will show short code snippets in this guide and link off to full tutorials which you can run end to end. Using `tf.distribute.Strategy` with KerasWe've integrated `tf.distribute.Strategy` into `tf.keras` which is TensorFlow's implementation of the[Keras API specification](https://keras.io). `tf.keras` is a high-level API to build and train models. By integrating into `tf.keras` backend, we've made it seamless for Keras users to distribute their training written in the Keras training framework. The only things that need to change in a user's program are: (1) Create an instance of the appropriate `tf.distribute.Strategy` and (2) Move the creation and compiling of Keras model inside `strategy.scope`. Here is a snippet of code to do this for a very simple Keras model with one dense layer:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
model.compile(loss='mse', optimizer='sgd')
###Output
_____no_output_____
###Markdown
In this example we used `MirroredStrategy` so we can run this on a machine with multiple GPUs. `strategy.scope()` indicated which parts of the code to run distributed. Creating a model inside this scope allows us to create mirrored variables instead of regular variables. Compiling under the scope allows us to know that the user intends to train this model using this strategy. Once this is setup, you can fit your model like you would normally. `MirroredStrategy` takes care of replicating the model's training on the available GPUs, aggregating gradients etc.
###Code
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100).batch(10)
model.fit(dataset, epochs=2)
model.evaluate(dataset)
###Output
_____no_output_____
###Markdown
Here we used a `tf.data.Dataset` to provide the training and eval input. You can also use numpy arrays:
###Code
import numpy as np
inputs, targets = np.ones((100, 1)), np.ones((100, 1))
model.fit(inputs, targets, epochs=2, batch_size=10)
###Output
_____no_output_____
###Markdown
In both cases (dataset or numpy), each batch of the given input is divided equally among the multiple replicas. For instance, if using `MirroredStrategy` with 2 GPUs, each batch of size 10 will get divided among the 2 GPUs, with each receiving 5 input examples in each step. Each epoch will then train faster as you add more GPUs. Typically, you would want to increase your batch size as you add more accelerators so as to make effective use of the extra computing power. You will also need to re-tune your learning rate, depending on the model. You can use `strategy.num_replicas_in_sync` to get the number of replicas.
###Code
# Compute global batch size using number of replicas.
BATCH_SIZE_PER_REPLICA = 5
global_batch_size = (BATCH_SIZE_PER_REPLICA *
mirrored_strategy.num_replicas_in_sync)
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100)
dataset = dataset.batch(global_batch_size)
LEARNING_RATES_BY_BATCH_SIZE = {5: 0.1, 10: 0.15}
learning_rate = LEARNING_RATES_BY_BATCH_SIZE[global_batch_size]
###Output
_____no_output_____
###Markdown
What's supported now?In TF 2.0 alpha release, we support training with Keras using `MirroredStrategy`, as well as one machine parameter server using `ParameterServerStrategy`. Support for other strategies will be coming soon. The API and how to use will be exactly the same as above. If you wish to use the other strategies like `TPUStrategy` or `MultiWorkerMirorredStrategy` in Keras in TF 2.0, you can currently do so by disabling eager execution (`tf.compat.v1.disable_eager_execution()`). Another thing to note is that when using `MultiWorkerMirorredStrategy` for multiple workers with Keras, currently the user will have to explicitly shard or shuffle the data for different workers, but we will change this in the future to automatically shard the input data intelligently. Examples and TutorialsHere is a list of tutorials and examples that illustrate the above integration end to end with Keras:1. [Tutorial](../tutorials/distribute/keras.ipynb) to train MNIST with `MirroredStrategy`.2. [Tutorial](tpu.ipynb) to train Fashion MNIST with `TPUStrategy` (currently uses `disable_eager_execution`)3. Official [ResNet50](https://github.com/tensorflow/models/blob/master/official/resnet/keras/keras_imagenet_main.py) training with ImageNet data using `MirroredStrategy`.4. [ResNet50](https://github.com/tensorflow/tpu/blob/master/models/experimental/resnet50_keras/resnet50.py) trained with Imagenet data on Cloud TPus with `TPUStrategy`. Note that this example only works with TensorFlow 1.x currently. Using `tf.distribute.Strategy` with Estimator`tf.estimator` is a distributed training TensorFlow API that originally supported the async parameter server approach. Like with Keras, we've integrated `tf.distribute.Strategy` into `tf.Estimator` so that a user who is using Estimator for their training can easily change their training is distributed with very few changes to your their code. With this, estimator users can now do synchronous distributed training on multiple GPUs and multiple workers, as well as use TPUs. The usage of `tf.distribute.Strategy` with Estimator is slightly different than the Keras case. Instead of using `strategy.scope`, now we pass the strategy object into the [`RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig) for the Estimator. Here is a snippet of code that shows this with a premade estimator `LinearRegressor` and `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
config = tf.estimator.RunConfig(
train_distribute=mirrored_strategy, eval_distribute=mirrored_strategy)
regressor = tf.estimator.LinearRegressor(
feature_columns=[tf.feature_column.numeric_column('feats')],
optimizer='SGD',
config=config)
###Output
_____no_output_____
###Markdown
We use a premade Estimator here, but the same code works with a custom Estimator as well. `train_distribute` determines how training will be distributed, and `eval_distribute` determines how evaluation will be distributed. This is another difference from Keras where we use the same strategy for both training and eval. Now we can train and evaluate this Estimator with an input function:
###Code
def input_fn():
dataset = tf.data.Dataset.from_tensors(({"feats":[1.]}, [1.]))
return dataset.repeat(1000).batch(10)
regressor.train(input_fn=input_fn, steps=10)
regressor.evaluate(input_fn=input_fn, steps=10)
###Output
_____no_output_____
###Markdown
Another difference to highlight here between Estimator and Keras is the input handling. In Keras, we mentioned that each batch of the dataset is split across the multiple replicas. In Estimator, however, the user provides an `input_fn` and have full control over how they want their data to be distributed across workers and devices. We do not do automatic splitting of batch, nor automatically shard the data across different workers. The provided `input_fn` is called once per worker, thus giving one dataset per worker. Then one batch from that dataset is fed to one replica on that worker, thereby consuming N batches for N replicas on 1 worker. In other words, the dataset returned by the `input_fn` should provide batches of size `PER_REPLICA_BATCH_SIZE`. And the global batch size for a step can be obtained as `PER_REPLICA_BATCH_SIZE * strategy.num_replicas_in_sync`. When doing multi worker training, users will also want to either split their data across the workers, or shuffle with a random seed on each. You can see an example of how to do this in the [multi-worker tutorial](../tutorials/distribute/multi_worker.ipynb). We showed an example of using `MirroredStrategy` with Estimator. You can also use `TPUStrategy` with Estimator as well, in the exact same way:```config = tf.estimator.RunConfig( train_distribute=tpu_strategy, eval_distribute=tpu_strategy)``` And similarly, you can use multi worker and parameter server strategies as well. The code remains the same, but you need to use `tf.estimator.train_and_evaluate`, and set "TF_CONFIG" environment variables for each binary running in your cluster. What's supported now?In TF 2.0 alpha release, we support training with Estimator using all strategies. Examples and TutorialsHere are some examples that show end to end usage of various strategies with Estimator:1. [Tutorial]((../tutorials/distribute/multi_worker.ipynb) to train MNIST with multiple workers using `MultiWorkerMirroredStrategy`.2. [End to end example](https://github.com/tensorflow/ecosystem/tree/master/distribution_strategy) for multi worker training in tensorflow/ecosystem using Kuberentes templates. This example starts with a Keras model and converts it to an Estimator using the `tf.keras.estimator.model_to_estimator` API. 3. Official [ResNet50](https://github.com/tensorflow/models/blob/master/official/resnet/imagenet_main.py) model, which can be trained using either `MirroredStrategy` or `MultiWorkerMirroredStrategy`.4. [ResNet50](https://github.com/tensorflow/tpu/blob/master/models/experimental/distribution_strategy/resnet_estimator.py) example with TPUStrategy. Using `tf.distribute.Strategy` with custom training loopsAs you've seen, using `tf.distrbute.Strategy` with high level APIs is only a couple lines of code change. With a little more effort, `tf.distrbute.Strategy` can also be used by other users who are not using these frameworks.TensorFlow is used for a wide variety of use cases and some users (such as researchers) require more flexibility and control over their training loops. This makes it hard for them to use the high level frameworks such as Estimator or Keras. For instance, someone using a GAN may want to take a different number of generator or discriminator steps each round. Similarly, the high level frameworks are not very suitable for Reinforcement Learning training. So these users will usually write their own training loops. For these users, we provide a core set of methods through the `tf.distrbute.Strategy` classes. Using these may require minor restructuring of the code initially, but once that is done, the user should be able to switch between GPUs / TPUs / multiple machines by just changing the strategy instance.Here we will show a brief snippet illustrating this use case for a simple training example using the same Keras model as before. Note: These APIs are still experimental and we are improving them to make them more user friendly in TensorFlow 2.0. First, we create the model and optimizer inside the strategy's scope. This ensures that any variables created with the model and optimizer are mirrored variables.
###Code
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
optimizer = tf.keras.optimizers.SGD()
###Output
_____no_output_____
###Markdown
Next, we create the input dataset and call `make_dataset_iterator` to distribute the dataset based on the strategy. This API is expected to change in the near future.
###Code
with mirrored_strategy.scope():
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(1000).batch(
global_batch_size)
input_iterator = mirrored_strategy.make_dataset_iterator(dataset)
###Output
_____no_output_____
###Markdown
Then, we define one step of the training. We will use `tf.GradientTape` to compute gradients and optimizer to apply those gradients to update our model's variables. To distribute this training step, we put in in a function `step_fn` and pass it to `strategy.experimental_run` along with the iterator created before:
###Code
@tf.function
def train_step():
def step_fn(inputs):
features, labels = inputs
with tf.GradientTape() as tape:
logits = model(features)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(
logits=logits, labels=labels)
loss = tf.reduce_sum(cross_entropy) * (1.0 / global_batch_size)
grads = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(list(zip(grads, model.trainable_variables)))
return loss
per_replica_losses = mirrored_strategy.experimental_run(
step_fn, input_iterator)
mean_loss = mirrored_strategy.reduce(
tf.distribute.ReduceOp.MEAN, per_replica_losses)
return mean_loss
###Output
_____no_output_____
###Markdown
A few other things to note in the code above: 1. We used `tf.nn.softmax_cross_entropy_with_logits` to compute the loss. And then we scaled the total loss by the global batch size. This is important because all the replicas are training in sync and number of examples in each step of training is the global batch. If you're using TensorFlow's standard losses from `tf.losses` or `tf.keras.losses`, they are distribution aware and will take care of the scaling by number of replicas whenever a strategy is in scope. 2. We used the `strategy.reduce` API to aggregate the results returned by `experimental_run`. `experimental_run` returns results from each local replica in the strategy, and there are multiple ways to consume this result. You can `reduce` them to get an aggregated value. You can also do `strategy.unwrap(results)`* to get the list of values contained in the result, one per local replica.*expected to change Finally, once we have defined the training step, we can initialize the iterator and run the training in a loop:
###Code
with mirrored_strategy.scope():
input_iterator.initialize()
for _ in range(10):
print(train_step())
###Output
_____no_output_____
###Markdown
Copyright 2018 The TensorFlow Authors.
###Code
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###Output
_____no_output_____
###Markdown
Distributed Training in TensorFlow View on TensorFlow.org Run in Google Colab View source on GitHub Overview`tf.distribute.Strategy` is a TensorFlow API to distribute trainingacross multiple GPUs, multiple machines or TPUs. Using this API, users can distribute their existing models and training code with minimal code changes.`tf.distribute.Strategy` has been designed with these key goals in mind:* Easy to use and support multiple user segments, including researchers, ML engineers, etc.* Provide good performance out of the box.* Easy switching between strategies.`tf.distribute.Strategy` can be used with TensorFlow's high level APIs, [tf.keras](https://www.tensorflow.org/guide/keras) and [tf.estimator](https://www.tensorflow.org/guide/estimators), with just a couple of lines of code change. It also provides an API that can be used to distribute custom training loops (and in general any computation using TensorFlow).In TensorFlow 2.0, users can execute their programs eagerly, or in a graph using [`tf.function`](../tutorials/eager/tf_function.ipynb). `tf.distribute.Strategy` intends to support both these modes of execution. Note that we may talk about training most of the time in this guide, but this API can also be used for distributing evaluation and prediction on different platforms.As you will see in a bit, very few changes are needed to use `tf.distribute.Strategy` with your code. This is because we have changed the underlying components of TensorFlow to become strategy-aware. This includes variables, layers, models, optimizers, metrics, summaries, and checkpoints.In this guide, we will talk about various types of strategies and how one can use them in a different situations.
###Code
# Import TensorFlow
from __future__ import absolute_import, division, print_function, unicode_literals
!pip install tf-nightly-gpu-2.0-preview
import tensorflow as tf
###Output
_____no_output_____
###Markdown
Types of strategies`tf.distribute.Strategy` intends to cover a number of use cases along different axes. Some of these combinations are currently supported and others will be added in the future. Some of these axes are:* Syncronous vs asynchronous training: These are two common ways of distributing training with data parallelism. In sync training, all workers train over different slices of input data in sync, and aggregating gradients at each step. In async training, all workers are independently training over the input data and updating variables asynchronously. Typically sync training is supported via all-reduce and async through parameter server architecture.* Hardware platform: Users may want to scale their training onto multiple GPUs on one machine, or multiple machines in a network (with 0 or more GPUs each), or on Cloud TPUs.In order to support these use cases, we have 4 strategies available. In the next section we will talk about which of these are supported in which scenarios in TF 2.0-alpha at this time. MirroredStrategy`tf.distribute.MirroredStrategy` support synchronous distributed training on multiple GPUs on one machine. It creates one replica per GPU device. Each variable in the model is mirrored across all the replicas. Together, these variables form a single conceptual variable called `MirroredVariable`. These variables are kept in sync with each other by applying identical updates.Efficient all-reduce algorithms are used to communicate the variable updates across the devices.All-reduce aggregates tensors across all the devices by adding them up, and makes them available on each device.It’s a fused algorithm that is very efficient and can reduce the overhead of synchronization significantly. There are many all-reduce algorithms and implementations available, depending on the type of communication available between devices. By default, it uses NVIDIA NCCL as the all-reduce implementation. The user can also choose between a few other options we provide, or write their own.Here is the simplest way of creating `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
###Output
_____no_output_____
###Markdown
This will create a `MirroredStrategy` instance which will use all the GPUs that are visible to TensorFlow, and use NCCL as the cross device communication.If you wish to use only some of the GPUs on your machine, you can do so like this:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(devices=["/gpu:0", "/gpu:1"])
###Output
_____no_output_____
###Markdown
If you wish to override the cross device communication, you can do so using the `cross_device_ops` argument by supplying an instance of `tf.distribute.CrossDeviceOps`. Currently we provide `tf.distribute.HierarchicalCopyAllReduce` and `tf.distribute.ReductionToOneDevice` as 2 other options other than `tf.distribute.NcclAllReduce` which is the default.
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(
cross_device_ops=tf.distribute.HierarchicalCopyAllReduce())
###Output
_____no_output_____
###Markdown
CentralStorageStrategy`tf.distribute.experimental.CentralStorageStrategy` does synchronous training as well. Variables are not mirrored, instead they are placed on the CPU and operations are replicated across all local GPUs. If there is only one GPU, all variables and operations will be placed on that GPU.Create a `CentralStorageStrategy` by:
###Code
central_storage_strategy = tf.distribute.experimental.CentralStorageStrategy()
###Output
_____no_output_____
###Markdown
This will create a `CentralStorageStrategy` instance which will use all visible GPUs and CPU. Update to variables on replicas will be aggragated before being applied to variables. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. MultiWorkerMirroredStrategy`tf.distribute.experimental.MultiWorkerMirroredStrategy` is very similar to `MirroredStrategy`. It implements synchronous distributed training across multiple workers, each with potentially multiple GPUs. Similar to `MirroredStrategy`, it creates copies of all variables in the model on each device across all workers.It uses [CollectiveOps](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/collective_ops.py) as the multi-worker all-reduce communication method used to keep variables in sync. A collective op is a single op in the TensorFlow graph which can automatically choose an all-reduce algorithm in the TensorFlow runtime according to hardware, network topology and tensor sizes.It also implements additional performance optimizations. For example, it includes a static optimization that converts multiple all-reductions on small tensors into fewer all-reductions on larger tensors. In addition, we are designing it to have a plugin architecture - so that in the future, users will be able to plugin algorithms that are better tuned for their hardware. Note that collective ops also implement other collective operations such as broadcast and all-gather.Here is the simplest way of creating `MultiWorkerMirroredStrategy`:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()
###Output
_____no_output_____
###Markdown
`MultiWorkerMirroredStrategy` currently allows you to choose between two different implementations of collective ops. `CollectiveCommunication.RING` implements ring-based collectives using gRPC as the communication layer. `CollectiveCommunication.NCCL` uses [Nvidia's NCCL](https://developer.nvidia.com/nccl) to implement collectives. `CollectiveCommunication.AUTO` defers the choice to the runtime. The best choice of collective implementation depends upon the number and kind of GPUs, and the network interconnect in the cluster. You can specify them like so:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy(
tf.distribute.experimental.CollectiveCommunication.NCCL)
###Output
_____no_output_____
###Markdown
One of the key differences to get multi worker training going, as compared to multi-GPU training, is the multi-worker setup. "TF_CONFIG" environment variable is the standard way in TensorFlow to specify the cluster configuration to each worker that is part of the cluster. See section on ["TF_CONFIG" below](TF_CONFIG) for more details on how this can be done. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. TPUStrategy`tf.distribute.experimental.TPUStrategy` lets users run their TensorFlow training on Tensor Processing Units (TPUs). TPUs are Google's specialized ASICs designed to dramatically accelerate machine learning workloads. They are available on Google Colab, the [TensorFlow Research Cloud](https://www.tensorflow.org/tfrc) and [Google Compute Engine](https://cloud.google.com/tpu).In terms of distributed training architecture, TPUStrategy is the same `MirroredStrategy` - it implements synchronous distributed training. TPUs provide their own implementation of efficient all-reduce and other collective operations across multiple TPU cores, which are used in `TPUStrategy`.Here is how you would instantiate `TPUStrategy`.Note: To run this code in Colab, you should select TPU as the Colab runtime. See [Using TPUs]( tpu.ipynb) guide for a runnable version.```resolver = tf.distribute.cluster_resolver.TPUClusterResolver()tf.tpu.experimental.initialize_tpu_system(resolver)tpu_strategy = tf.distribute.experimental.TPUStrategy(resolver)``` `TPUClusterResolver` instance helps locate the TPUs. In Colab, you don't need to specify any arguments to it. If you want to use this for Cloud TPUs, you will need to specify the name of your TPU resource in `tpu` argument. We also need to initialize the tpu system explicitly at the start of the program. This is required before TPUs can be used for computation and should ideally be done at the beginning because it also wipes out the TPU memory so all state will be lost. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. ParameterServerStrategy`tf.distribute.experimental.ParameterServerStrategy` supports parameter servers training on multiple machines. In this setup, some machines are designated as workers and some as parameter servers. Each variable of the model is placed on one parameter server. Computation is replicated across all GPUs of the all the workers.In terms of code, it looks similar to other strategies:```ps_strategy = tf.distribute.experimental.ParameterServerStrategy()``` For multi worker training, "TF_CONFIG" needs to specify the configuration of parameter servers and workers in your cluster, which you can read more about in ["TF_CONFIG" below](TF_CONFIG) below. So far we've talked about what are the different stategies available and how you can instantiate them. In the next few sections, we will talk about the different ways in which you can use them to distribute your training. We will show short code snippets in this guide and link off to full tutorials which you can run end to end. Using `tf.distribute.Strategy` with KerasWe've integrated `tf.distribute.Strategy` into `tf.keras` which is TensorFlow's implementation of the[Keras API specification](https://keras.io). `tf.keras` is a high-level API to build and train models. By integrating into `tf.keras` backend, we've made it seamless for Keras users to distribute their training written in the Keras training framework. The only things that need to change in a user's program are: (1) Create an instance of the appropriate `tf.distribute.Strategy` and (2) Move the creation and compiling of Keras model inside `strategy.scope`.Here is a snippet of code to do this for a very simple Keras model with one dense layer:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
model.compile(loss='mse', optimizer='sgd')
###Output
_____no_output_____
###Markdown
In this example we used `MirroredStrategy` so we can run this on a machine with multiple GPUs. `strategy.scope()` indicated which parts of the code to run distributed. Creating a model inside this scope allows us to create mirrored variables instead of regular variables. Compiling under the scope allows us to know that the user intends to train this model using this strategy. Once this is setup, you can fit your model like you would normally. `MirroredStrategy` takes care of replicating the model's training on the available GPUs, aggregating gradients etc.
###Code
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100).batch(10)
model.fit(dataset, epochs=2)
model.evaluate(dataset)
###Output
_____no_output_____
###Markdown
Here we used a `tf.data.Dataset` to provide the training and eval input. You can also use numpy arrays:
###Code
import numpy as np
inputs, targets = np.ones((100, 1)), np.ones((100, 1))
model.fit(inputs, targets, epochs=2, batch_size=10)
###Output
_____no_output_____
###Markdown
In both cases (dataset or numpy), each batch of the given input is divided equally among the multiple replicas. For instance, if using `MirroredStrategy` with 2 GPUs, each batch of size 10 will get divided among the 2 GPUs, with each receiving 5 input examples in each step. Each epoch will then train faster as you add more GPUs. Typically, you would want to increase your batch size as you add more accelerators so as to make effective use of the extra computing power. You will also need to re-tune your learning rate, depending on the model. You can use `strategy.num_replicas_in_sync` to get the number of replicas.
###Code
# Compute global batch size using number of replicas.
BATCH_SIZE_PER_REPLICA = 5
global_batch_size = (BATCH_SIZE_PER_REPLICA *
mirrored_strategy.num_replicas_in_sync)
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100)
dataset = dataset.batch(global_batch_size)
LEARNING_RATES_BY_BATCH_SIZE = {5: 0.1, 10: 0.15}
learning_rate = LEARNING_RATES_BY_BATCH_SIZE[global_batch_size]
###Output
_____no_output_____
###Markdown
What's supported now?In TF 2.0 alpha release, we support training with Keras using `MirroredStrategy`, as well as one machine parameter server using `ParameterServerStrategy`.Support for other strategies will be coming soon. The API and how to use will be exactly the same as above. If you wish to use the other strategies like `TPUStrategy` or `MultiWorkerMirorredStrategy` in Keras in TF 2.0, you can currently do so by disabling eager execution (`tf.compat.v1.disable_eager_execution()`). Another thing to note is that when using `MultiWorkerMirorredStrategy` for multiple workers with Keras, currently the user will have to explicitly shard or shuffle the data for different workers, but we will change this in the future to automatically shard the input data intelligently. Examples and TutorialsHere is a list of tutorials and examples that illustrate the above integration end to end with Keras:1. [Tutorial](../tutorials/distribute/keras.ipynb) to train MNIST with `MirroredStrategy`.2. Official [ResNet50](https://github.com/tensorflow/models/blob/master/official/resnet/keras/keras_imagenet_main.py) training with ImageNet data using `MirroredStrategy`.3. [ResNet50](https://github.com/tensorflow/tpu/blob/master/models/experimental/resnet50_keras/resnet50.py) trained with Imagenet data on Cloud TPus with `TPUStrategy`. Note that this example only works with TensorFlow 1.x currently. Using `tf.distribute.Strategy` with Estimator`tf.estimator` is a distributed training TensorFlow API that originally supported the async parameter server approach. Like with Keras, we've integrated `tf.distribute.Strategy` into `tf.Estimator` so that a user who is using Estimator for their training can easily change their training is distributed with very few changes to your their code. With this, estimator users can now do synchronous distributed training on multiple GPUs and multiple workers, as well as use TPUs.The usage of `tf.distribute.Strategy` with Estimator is slightly different than the Keras case. Instead of using `strategy.scope`, now we pass the strategy object into the [`RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig) for the Estimator.Here is a snippet of code that shows this with a premade estimator `LinearRegressor` and `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
config = tf.estimator.RunConfig(
train_distribute=mirrored_strategy, eval_distribute=mirrored_strategy)
regressor = tf.estimator.LinearRegressor(
feature_columns=[tf.feature_column.numeric_column('feats')],
optimizer='SGD',
config=config)
###Output
_____no_output_____
###Markdown
We use a premade Estimator here, but the same code works with a custom Estimator as well. `train_distribute` determines how training will be distributed, and `eval_distribute` determines how evaluation will be distributed. This is another difference from Keras where we use the same strategy for both training and eval.Now we can train and evaluate this Estimator with an input function:
###Code
def input_fn():
dataset = tf.data.Dataset.from_tensors(({"feats":[1.]}, [1.]))
return dataset.repeat(1000).batch(10)
regressor.train(input_fn=input_fn, steps=10)
regressor.evaluate(input_fn=input_fn, steps=10)
###Output
_____no_output_____
###Markdown
Another difference to highlight here between Estimator and Keras is the input handling. In Keras, we mentioned that each batch of the dataset is split across the multiple replicas. In Estimator, however, the user provides an `input_fn` and have full control over how they want their data to be distributed across workers and devices. We do not do automatic splitting of batch, nor automatically shard the data across different workers. The provided `input_fn` is called once per worker, thus giving one dataset per worker. Then one batch from that dataset is fed to one replica on that worker, thereby consuming N batches for N replicas on 1 worker. In other words, the dataset returned by the `input_fn` should provide batches of size `PER_REPLICA_BATCH_SIZE`. And the global batch size for a step can be obtained as `PER_REPLICA_BATCH_SIZE * strategy.num_replicas_in_sync`. When doing multi worker training, users will also want to either split their data across the workers, or shuffle with a random seed on each. You can see an example of how to do this in the [multi-worker tutorial](../tutorials/distribute/multi_worker.ipynb). We showed an example of using `MirroredStrategy` with Estimator. You can also use `TPUStrategy` with Estimator as well, in the exact same way:```config = tf.estimator.RunConfig( train_distribute=tpu_strategy, eval_distribute=tpu_strategy)``` And similarly, you can use multi worker and parameter server strategies as well. The code remains the same, but you need to use `tf.estimator.train_and_evaluate`, and set "TF_CONFIG" environment variables for each binary running in your cluster. What's supported now?In TF 2.0 alpha release, we support training with Estimator using all strategies. Examples and TutorialsHere are some examples that show end to end usage of various strategies with Estimator:1. [Tutorial](../tutorials/distribute/multi_worker.ipynb) to train MNIST with multiple workers using `MultiWorkerMirroredStrategy`.2. [End to end example](https://github.com/tensorflow/ecosystem/tree/master/distribution_strategy) for multi worker training in tensorflow/ecosystem using Kuberentes templates. This example starts with a Keras model and converts it to an Estimator using the `tf.keras.estimator.model_to_estimator` API.3. Official [ResNet50](https://github.com/tensorflow/models/blob/master/official/resnet/imagenet_main.py) model, which can be trained using either `MirroredStrategy` or `MultiWorkerMirroredStrategy`.4. [ResNet50](https://github.com/tensorflow/tpu/blob/master/models/experimental/distribution_strategy/resnet_estimator.py) example with TPUStrategy. Using `tf.distribute.Strategy` with custom training loopsAs you've seen, using `tf.distrbute.Strategy` with high level APIs is only a couple lines of code change. With a little more effort, `tf.distrbute.Strategy` can also be used by other users who are not using these frameworks.TensorFlow is used for a wide variety of use cases and some users (such as researchers) require more flexibility and control over their training loops. This makes it hard for them to use the high level frameworks such as Estimator or Keras. For instance, someone using a GAN may want to take a different number of generator or discriminator steps each round. Similarly, the high level frameworks are not very suitable for Reinforcement Learning training. So these users will usually write their own training loops.For these users, we provide a core set of methods through the `tf.distrbute.Strategy` classes. Using these may require minor restructuring of the code initially, but once that is done, the user should be able to switch between GPUs / TPUs / multiple machines by just changing the strategy instance.Here we will show a brief snippet illustrating this use case for a simple training example using the same Keras model as before.Note: These APIs are still experimental and we are improving them to make them more user friendly in TensorFlow 2.0. First, we create the model and optimizer inside the strategy's scope. This ensures that any variables created with the model and optimizer are mirrored variables.
###Code
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
optimizer = tf.keras.optimizers.SGD()
###Output
_____no_output_____
###Markdown
Next, we create the input dataset and call `make_dataset_iterator` to distribute the dataset based on the strategy. This API is expected to change in the near future.
###Code
with mirrored_strategy.scope():
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(1000).batch(
global_batch_size)
input_iterator = mirrored_strategy.make_dataset_iterator(dataset)
###Output
_____no_output_____
###Markdown
Copyright 2018 The TensorFlow Authors.
###Code
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###Output
_____no_output_____
###Markdown
Distributed Training in TensorFlow View on TensorFlow.org Run in Google Colab View source on GitHub Overview`tf.distribute.Strategy` is a TensorFlow API to distribute trainingacross multiple GPUs, multiple machines or TPUs. Using this API, users can distribute their existing models and training code with minimal code changes.`tf.distribute.Strategy` has been designed with these key goals in mind:* Easy to use and support multiple user segments, including researchers, ML engineers, etc.* Provide good performance out of the box.* Easy switching between strategies.`tf.distribute.Strategy` can be used with TensorFlow's high level APIs, [tf.keras](https://www.tensorflow.org/guide/keras) and [tf.estimator](https://www.tensorflow.org/guide/estimators), with just a couple of lines of code change. It also provides an API that can be used to distribute custom training loops (and in general any computation using TensorFlow).In TensorFlow 2.0, users can execute their programs eagerly, or in a graph using [`tf.function`](../tutorials/eager/tf_function.ipynb). `tf.distribute.Strategy` intends to support both these modes of execution. Note that we may talk about training most of the time in this guide, but this API can also be used for distributing evaluation and prediction on different platforms.As you will see in a bit, very few changes are needed to use `tf.distribute.Strategy` with your code. This is because we have changed the underlying components of TensorFlow to become strategy-aware. This includes variables, layers, models, optimizers, metrics, summaries, and checkpoints.In this guide, we will talk about various types of strategies and how one can use them in a different situations.
###Code
# Import TensorFlow
from __future__ import absolute_import, division, print_function, unicode_literals
!pip install tensorflow-gpu==2.0.0-alpha0
import tensorflow as tf
###Output
_____no_output_____
###Markdown
Types of strategies`tf.distribute.Strategy` intends to cover a number of use cases along different axes. Some of these combinations are currently supported and others will be added in the future. Some of these axes are:* Syncronous vs asynchronous training: These are two common ways of distributing training with data parallelism. In sync training, all workers train over different slices of input data in sync, and aggregating gradients at each step. In async training, all workers are independently training over the input data and updating variables asynchronously. Typically sync training is supported via all-reduce and async through parameter server architecture.* Hardware platform: Users may want to scale their training onto multiple GPUs on one machine, or multiple machines in a network (with 0 or more GPUs each), or on Cloud TPUs.In order to support these use cases, we have 4 strategies available. In the next section we will talk about which of these are supported in which scenarios in TF 2.0-alpha at this time. MirroredStrategy`tf.distribute.MirroredStrategy` support synchronous distributed training on multiple GPUs on one machine. It creates one replica per GPU device. Each variable in the model is mirrored across all the replicas. Together, these variables form a single conceptual variable called `MirroredVariable`. These variables are kept in sync with each other by applying identical updates.Efficient all-reduce algorithms are used to communicate the variable updates across the devices.All-reduce aggregates tensors across all the devices by adding them up, and makes them available on each device.It’s a fused algorithm that is very efficient and can reduce the overhead of synchronization significantly. There are many all-reduce algorithms and implementations available, depending on the type of communication available between devices. By default, it uses NVIDIA NCCL as the all-reduce implementation. The user can also choose between a few other options we provide, or write their own.Here is the simplest way of creating `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
###Output
_____no_output_____
###Markdown
This will create a `MirroredStrategy` instance which will use all the GPUs that are visible to TensorFlow, and use NCCL as the cross device communication.If you wish to use only some of the GPUs on your machine, you can do so like this:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(devices=["/gpu:0", "/gpu:1"])
###Output
_____no_output_____
###Markdown
If you wish to override the cross device communication, you can do so using the `cross_device_ops` argument by supplying an instance of `tf.distribute.CrossDeviceOps`. Currently we provide `tf.distribute.HierarchicalCopyAllReduce` and `tf.distribute.ReductionToOneDevice` as 2 other options other than `tf.distribute.NcclAllReduce` which is the default.
###Code
mirrored_strategy = tf.distribute.MirroredStrategy(
cross_device_ops=tf.distribute.HierarchicalCopyAllReduce())
###Output
_____no_output_____
###Markdown
CentralStorageStrategy`tf.distribute.experimental.CentralStorageStrategy` does synchronous training as well. Variables are not mirrored, instead they are placed on the CPU and operations are replicated across all local GPUs. If there is only one GPU, all variables and operations will be placed on that GPU.Create a `CentralStorageStrategy` by:
###Code
central_storage_strategy = tf.distribute.experimental.CentralStorageStrategy()
###Output
_____no_output_____
###Markdown
This will create a `CentralStorageStrategy` instance which will use all visible GPUs and CPU. Update to variables on replicas will be aggragated before being applied to variables. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. MultiWorkerMirroredStrategy`tf.distribute.experimental.MultiWorkerMirroredStrategy` is very similar to `MirroredStrategy`. It implements synchronous distributed training across multiple workers, each with potentially multiple GPUs. Similar to `MirroredStrategy`, it creates copies of all variables in the model on each device across all workers.It uses [CollectiveOps](https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/collective_ops.py) as the multi-worker all-reduce communication method used to keep variables in sync. A collective op is a single op in the TensorFlow graph which can automatically choose an all-reduce algorithm in the TensorFlow runtime according to hardware, network topology and tensor sizes.It also implements additional performance optimizations. For example, it includes a static optimization that converts multiple all-reductions on small tensors into fewer all-reductions on larger tensors. In addition, we are designing it to have a plugin architecture - so that in the future, users will be able to plugin algorithms that are better tuned for their hardware. Note that collective ops also implement other collective operations such as broadcast and all-gather.Here is the simplest way of creating `MultiWorkerMirroredStrategy`:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()
###Output
_____no_output_____
###Markdown
`MultiWorkerMirroredStrategy` currently allows you to choose between two different implementations of collective ops. `CollectiveCommunication.RING` implements ring-based collectives using gRPC as the communication layer. `CollectiveCommunication.NCCL` uses [Nvidia's NCCL](https://developer.nvidia.com/nccl) to implement collectives. `CollectiveCommunication.AUTO` defers the choice to the runtime. The best choice of collective implementation depends upon the number and kind of GPUs, and the network interconnect in the cluster. You can specify them like so:
###Code
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy(
tf.distribute.experimental.CollectiveCommunication.NCCL)
###Output
_____no_output_____
###Markdown
One of the key differences to get multi worker training going, as compared to multi-GPU training, is the multi-worker setup. "TF_CONFIG" environment variable is the standard way in TensorFlow to specify the cluster configuration to each worker that is part of the cluster. See section on ["TF_CONFIG" below](TF_CONFIG) for more details on how this can be done. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. TPUStrategy`tf.distribute.experimental.TPUStrategy` lets users run their TensorFlow training on Tensor Processing Units (TPUs). TPUs are Google's specialized ASICs designed to dramatically accelerate machine learning workloads. They are available on Google Colab, the [TensorFlow Research Cloud](https://www.tensorflow.org/tfrc) and [Google Compute Engine](https://cloud.google.com/tpu).In terms of distributed training architecture, TPUStrategy is the same `MirroredStrategy` - it implements synchronous distributed training. TPUs provide their own implementation of efficient all-reduce and other collective operations across multiple TPU cores, which are used in `TPUStrategy`.Here is how you would instantiate `TPUStrategy`.Note: To run this code in Colab, you should select TPU as the Colab runtime. See [Using TPUs]( tpu.ipynb) guide for a runnable version.```resolver = tf.distribute.cluster_resolver.TPUClusterResolver()tf.tpu.experimental.initialize_tpu_system(resolver)tpu_strategy = tf.distribute.experimental.TPUStrategy(resolver)``` `TPUClusterResolver` instance helps locate the TPUs. In Colab, you don't need to specify any arguments to it. If you want to use this for Cloud TPUs, you will need to specify the name of your TPU resource in `tpu` argument. We also need to initialize the tpu system explicitly at the start of the program. This is required before TPUs can be used for computation and should ideally be done at the beginning because it also wipes out the TPU memory so all state will be lost. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it and making it work for more scenarios. As part of this, please expect the APIs to change in the future. ParameterServerStrategy`tf.distribute.experimental.ParameterServerStrategy` supports parameter servers training on multiple machines. In this setup, some machines are designated as workers and some as parameter servers. Each variable of the model is placed on one parameter server. Computation is replicated across all GPUs of the all the workers.In terms of code, it looks similar to other strategies:```ps_strategy = tf.distribute.experimental.ParameterServerStrategy()``` For multi worker training, "TF_CONFIG" needs to specify the configuration of parameter servers and workers in your cluster, which you can read more about in ["TF_CONFIG" below](TF_CONFIG) below. So far we've talked about what are the different stategies available and how you can instantiate them. In the next few sections, we will talk about the different ways in which you can use them to distribute your training. We will show short code snippets in this guide and link off to full tutorials which you can run end to end. Using `tf.distribute.Strategy` with KerasWe've integrated `tf.distribute.Strategy` into `tf.keras` which is TensorFlow's implementation of the[Keras API specification](https://keras.io). `tf.keras` is a high-level API to build and train models. By integrating into `tf.keras` backend, we've made it seamless for Keras users to distribute their training written in the Keras training framework. The only things that need to change in a user's program are: (1) Create an instance of the appropriate `tf.distribute.Strategy` and (2) Move the creation and compiling of Keras model inside `strategy.scope`.Here is a snippet of code to do this for a very simple Keras model with one dense layer:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
model.compile(loss='mse', optimizer='sgd')
###Output
_____no_output_____
###Markdown
In this example we used `MirroredStrategy` so we can run this on a machine with multiple GPUs. `strategy.scope()` indicated which parts of the code to run distributed. Creating a model inside this scope allows us to create mirrored variables instead of regular variables. Compiling under the scope allows us to know that the user intends to train this model using this strategy. Once this is setup, you can fit your model like you would normally. `MirroredStrategy` takes care of replicating the model's training on the available GPUs, aggregating gradients etc.
###Code
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100).batch(10)
model.fit(dataset, epochs=2)
model.evaluate(dataset)
###Output
_____no_output_____
###Markdown
Here we used a `tf.data.Dataset` to provide the training and eval input. You can also use numpy arrays:
###Code
import numpy as np
inputs, targets = np.ones((100, 1)), np.ones((100, 1))
model.fit(inputs, targets, epochs=2, batch_size=10)
###Output
_____no_output_____
###Markdown
In both cases (dataset or numpy), each batch of the given input is divided equally among the multiple replicas. For instance, if using `MirroredStrategy` with 2 GPUs, each batch of size 10 will get divided among the 2 GPUs, with each receiving 5 input examples in each step. Each epoch will then train faster as you add more GPUs. Typically, you would want to increase your batch size as you add more accelerators so as to make effective use of the extra computing power. You will also need to re-tune your learning rate, depending on the model. You can use `strategy.num_replicas_in_sync` to get the number of replicas.
###Code
# Compute global batch size using number of replicas.
BATCH_SIZE_PER_REPLICA = 5
global_batch_size = (BATCH_SIZE_PER_REPLICA *
mirrored_strategy.num_replicas_in_sync)
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100)
dataset = dataset.batch(global_batch_size)
LEARNING_RATES_BY_BATCH_SIZE = {5: 0.1, 10: 0.15}
learning_rate = LEARNING_RATES_BY_BATCH_SIZE[global_batch_size]
###Output
_____no_output_____
###Markdown
What's supported now?In TF 2.0 alpha release, we support training with Keras using `MirroredStrategy`, as well as one machine parameter server using `ParameterServerStrategy`.Support for other strategies will be coming soon. The API and how to use will be exactly the same as above. If you wish to use the other strategies like `TPUStrategy` or `MultiWorkerMirorredStrategy` in Keras in TF 2.0, you can currently do so by disabling eager execution (`tf.compat.v1.disable_eager_execution()`). Another thing to note is that when using `MultiWorkerMirorredStrategy` for multiple workers with Keras, currently the user will have to explicitly shard or shuffle the data for different workers, but we will change this in the future to automatically shard the input data intelligently. Examples and TutorialsHere is a list of tutorials and examples that illustrate the above integration end to end with Keras:1. [Tutorial](../tutorials/distribute/keras.ipynb) to train MNIST with `MirroredStrategy`.2. [Tutorial](tpu.ipynb) to train Fashion MNIST with `TPUStrategy` (currently uses `disable_eager_execution`)3. Official [ResNet50](https://github.com/tensorflow/models/blob/master/official/resnet/keras/keras_imagenet_main.py) training with ImageNet data using `MirroredStrategy`.4. [ResNet50](https://github.com/tensorflow/tpu/blob/master/models/experimental/resnet50_keras/resnet50.py) trained with Imagenet data on Cloud TPus with `TPUStrategy`. Note that this example only works with TensorFlow 1.x currently. Using `tf.distribute.Strategy` with Estimator`tf.estimator` is a distributed training TensorFlow API that originally supported the async parameter server approach. Like with Keras, we've integrated `tf.distribute.Strategy` into `tf.Estimator` so that a user who is using Estimator for their training can easily change their training is distributed with very few changes to your their code. With this, estimator users can now do synchronous distributed training on multiple GPUs and multiple workers, as well as use TPUs.The usage of `tf.distribute.Strategy` with Estimator is slightly different than the Keras case. Instead of using `strategy.scope`, now we pass the strategy object into the [`RunConfig`](https://www.tensorflow.org/api_docs/python/tf/estimator/RunConfig) for the Estimator.Here is a snippet of code that shows this with a premade estimator `LinearRegressor` and `MirroredStrategy`:
###Code
mirrored_strategy = tf.distribute.MirroredStrategy()
config = tf.estimator.RunConfig(
train_distribute=mirrored_strategy, eval_distribute=mirrored_strategy)
regressor = tf.estimator.LinearRegressor(
feature_columns=[tf.feature_column.numeric_column('feats')],
optimizer='SGD',
config=config)
###Output
_____no_output_____
###Markdown
We use a premade Estimator here, but the same code works with a custom Estimator as well. `train_distribute` determines how training will be distributed, and `eval_distribute` determines how evaluation will be distributed. This is another difference from Keras where we use the same strategy for both training and eval.Now we can train and evaluate this Estimator with an input function:
###Code
def input_fn():
dataset = tf.data.Dataset.from_tensors(({"feats":[1.]}, [1.]))
return dataset.repeat(1000).batch(10)
regressor.train(input_fn=input_fn, steps=10)
regressor.evaluate(input_fn=input_fn, steps=10)
###Output
_____no_output_____
###Markdown
Another difference to highlight here between Estimator and Keras is the input handling. In Keras, we mentioned that each batch of the dataset is split across the multiple replicas. In Estimator, however, the user provides an `input_fn` and have full control over how they want their data to be distributed across workers and devices. We do not do automatic splitting of batch, nor automatically shard the data across different workers. The provided `input_fn` is called once per worker, thus giving one dataset per worker. Then one batch from that dataset is fed to one replica on that worker, thereby consuming N batches for N replicas on 1 worker. In other words, the dataset returned by the `input_fn` should provide batches of size `PER_REPLICA_BATCH_SIZE`. And the global batch size for a step can be obtained as `PER_REPLICA_BATCH_SIZE * strategy.num_replicas_in_sync`. When doing multi worker training, users will also want to either split their data across the workers, or shuffle with a random seed on each. You can see an example of how to do this in the [multi-worker tutorial](../tutorials/distribute/multi_worker.ipynb). We showed an example of using `MirroredStrategy` with Estimator. You can also use `TPUStrategy` with Estimator as well, in the exact same way:```config = tf.estimator.RunConfig( train_distribute=tpu_strategy, eval_distribute=tpu_strategy)``` And similarly, you can use multi worker and parameter server strategies as well. The code remains the same, but you need to use `tf.estimator.train_and_evaluate`, and set "TF_CONFIG" environment variables for each binary running in your cluster. What's supported now?In TF 2.0 alpha release, we support training with Estimator using all strategies. Examples and TutorialsHere are some examples that show end to end usage of various strategies with Estimator:1. [Tutorial]((../tutorials/distribute/multi_worker.ipynb) to train MNIST with multiple workers using `MultiWorkerMirroredStrategy`.2. [End to end example](https://github.com/tensorflow/ecosystem/tree/master/distribution_strategy) for multi worker training in tensorflow/ecosystem using Kuberentes templates. This example starts with a Keras model and converts it to an Estimator using the `tf.keras.estimator.model_to_estimator` API.3. Official [ResNet50](https://github.com/tensorflow/models/blob/master/official/resnet/imagenet_main.py) model, which can be trained using either `MirroredStrategy` or `MultiWorkerMirroredStrategy`.4. [ResNet50](https://github.com/tensorflow/tpu/blob/master/models/experimental/distribution_strategy/resnet_estimator.py) example with TPUStrategy. Using `tf.distribute.Strategy` with custom training loopsAs you've seen, using `tf.distrbute.Strategy` with high level APIs is only a couple lines of code change. With a little more effort, `tf.distrbute.Strategy` can also be used by other users who are not using these frameworks.TensorFlow is used for a wide variety of use cases and some users (such as researchers) require more flexibility and control over their training loops. This makes it hard for them to use the high level frameworks such as Estimator or Keras. For instance, someone using a GAN may want to take a different number of generator or discriminator steps each round. Similarly, the high level frameworks are not very suitable for Reinforcement Learning training. So these users will usually write their own training loops.For these users, we provide a core set of methods through the `tf.distrbute.Strategy` classes. Using these may require minor restructuring of the code initially, but once that is done, the user should be able to switch between GPUs / TPUs / multiple machines by just changing the strategy instance.Here we will show a brief snippet illustrating this use case for a simple training example using the same Keras model as before.Note: These APIs are still experimental and we are improving them to make them more user friendly in TensorFlow 2.0. First, we create the model and optimizer inside the strategy's scope. This ensures that any variables created with the model and optimizer are mirrored variables.
###Code
with mirrored_strategy.scope():
model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))])
optimizer = tf.keras.optimizers.SGD()
###Output
_____no_output_____
###Markdown
Next, we create the input dataset and call `make_dataset_iterator` to distribute the dataset based on the strategy. This API is expected to change in the near future.
###Code
with mirrored_strategy.scope():
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(1000).batch(
global_batch_size)
input_iterator = mirrored_strategy.make_dataset_iterator(dataset)
###Output
_____no_output_____
###Markdown
Then, we define one step of the training. We will use `tf.GradientTape` to compute gradients and optimizer to apply those gradients to update our model's variables. To distribute this training step, we put in in a function `step_fn` and pass it to `strategy.experimental_run` along with the iterator created before:
###Code
@tf.function
def train_step():
def step_fn(inputs):
features, labels = inputs
with tf.GradientTape() as tape:
logits = model(features)
cross_entropy = tf.nn.softmax_cross_entropy_with_logits(
logits=logits, labels=labels)
loss = tf.reduce_sum(cross_entropy) * (1.0 / global_batch_size)
grads = tape.gradient(loss, model.trainable_variables)
optimizer.apply_gradients(list(zip(grads, model.trainable_variables)))
return loss
per_replica_losses = mirrored_strategy.experimental_run(
step_fn, input_iterator)
mean_loss = mirrored_strategy.reduce(
tf.distribute.ReduceOp.SUM, per_replica_losses, axis=None)
return mean_loss
###Output
_____no_output_____
###Markdown
A few other things to note in the code above:1. We used `tf.nn.softmax_cross_entropy_with_logits` to compute the loss. And then we scaled the total loss by the global batch size. This is important because all the replicas are training in sync and number of examples in each step of training is the global batch. If you're using TensorFlow's standard losses from `tf.losses` or `tf.keras.losses`, they are distribution aware and will take care of the scaling by number of replicas whenever a strategy is in scope.2. We used the `strategy.reduce` API to aggregate the results returned by `experimental_run`. `experimental_run` returns results from each local replica in the strategy, and there are multiple ways to consume this result. You can `reduce` them to get an aggregated value. You can also do `strategy.unwrap(results)`* to get the list of values contained in the result, one per local replica.*expected to change Finally, once we have defined the training step, we can initialize the iterator and run the training in a loop:
###Code
with mirrored_strategy.scope():
input_iterator.initialize()
for _ in range(10):
print(train_step())
###Output
_____no_output_____ |
new_dataset_merging.ipynb | ###Markdown
Importo librerie
###Code
import pandas as pd
import numpy as np
import time
!pip install -U -q PyDrive
from pydrive.auth import GoogleAuth
from pydrive.drive import GoogleDrive
from google.colab import auth
from oauth2client.client import GoogleCredentials
###Output
_____no_output_____
###Markdown
Importo dataset
###Code
# autenticazione google drive
auth.authenticate_user()
gauth = GoogleAuth()
gauth.credentials = GoogleCredentials.get_application_default()
drive = GoogleDrive(gauth)
# dataset principale
drive.CreateFile({'id':'1eOqgPk_izGXKIT5y6KfqPkmKWqBonVc0'}).GetContentFile('dataset2_X_billboard.csv')
df_songs = pd.read_csv("dataset2_X_billboard.csv").drop('Unnamed: 0',axis=1)
# dataset billboard new pt.1
drive.CreateFile({'id':'1ZkinTIZIGEm6u2JtlD1MmpsIsbnNt9-C'}).GetContentFile('billboard+features_0.csv')
df_billboard_0 = pd.read_csv("billboard+features_0.csv").drop('Unnamed: 0',axis=1).dropna() # NB: elimino valori nulli risultanti da eventuali precedenti errori
# dataset billboard new pt.2
drive.CreateFile({'id':'1-3tSmqYTJU4lIp1Cz9nNQjRf_2OHzMec'}).GetContentFile('billboard+features_1.csv')
df_billboard_1 = pd.read_csv("billboard+features_1.csv").drop('Unnamed: 0',axis=1).dropna()
# dataset billboard new pt.3
drive.CreateFile({'id':'1-2WVMYcVJpGci_lL-OwSXd2-4Fmuc00k'}).GetContentFile('billboard+features_2.csv')
df_billboard_2 = pd.read_csv("billboard+features_2.csv").drop('Unnamed: 0',axis=1).dropna()
# dataset billboard new pt.4
drive.CreateFile({'id':'1-8DJGUMvOUYLupJ2qp9r3szhMQaTAUjJ'}).GetContentFile('billboard+features_3.csv')
df_billboard_3 = pd.read_csv("billboard+features_3.csv").drop('Unnamed: 0',axis=1).dropna()
###Output
_____no_output_____
###Markdown
Dataset merging
###Code
df_songs.info()
df_billboard_0.info()
new_datapoints = [df_billboard_0, df_billboard_1, df_billboard_2, df_billboard_3]
for x in new_datapoints:
x.rename(columns={'title':'name','artist':'artists'}, inplace=True) # rinomino colonne con nome diverso
x = x[list(df_songs.columns)] # riordino colonne in base a schema df_songs
df_songs = pd.concat([df_songs, x]) # inserisco nuovi datapoints nel df_songs
# elimino tracce precedenti al 1960
mask = df_songs.year > 1959
df_songs = df_songs[mask]
###Output
_____no_output_____
###Markdown
Esporto
###Code
# esporto in google drive
from google.colab import drive
# mounts the google drive to Colab Notebook
drive.mount('/content/drive',force_remount=True)
df_songs.to_csv('/content/drive/My Drive/Colab Notebooks/datasets/dataset2_X_billboard_plus.csv')
df_songs.info()
###Output
<class 'pandas.core.frame.DataFrame'>
Int64Index: 123212 entries, 0 to 4035
Data columns (total 21 columns):
# Column Non-Null Count Dtype
--- ------ -------------- -----
0 valence 123212 non-null float64
1 year 123212 non-null int64
2 acousticness 123212 non-null float64
3 artists 123212 non-null object
4 danceability 123212 non-null float64
5 duration_ms 123212 non-null float64
6 energy 123212 non-null float64
7 explicit 123212 non-null int64
8 id 123212 non-null object
9 instrumentalness 123212 non-null float64
10 key 123212 non-null float64
11 liveness 123212 non-null float64
12 loudness 123212 non-null float64
13 mode 123212 non-null float64
14 name 123212 non-null object
15 popularity 123212 non-null float64
16 release_date 123212 non-null object
17 speechiness 123212 non-null float64
18 tempo 123212 non-null float64
19 hit 123212 non-null float64
20 weeks 123212 non-null float64
dtypes: float64(15), int64(2), object(4)
memory usage: 20.7+ MB
|
day2/Part 7 - Loading Image Data (Exercises).ipynb | ###Markdown
Loading Image DataSo far we've been working with fairly artificial datasets that you wouldn't typically be using in real projects. Instead, you'll likely be dealing with full-sized images like you'd get from smart phone cameras. In this notebook, we'll look at how to load images and use them to train neural networks.We'll be using a [dataset of cat and dog photos](https://www.kaggle.com/c/dogs-vs-cats) available from Kaggle. Here are a couple example images:We'll use this dataset to train a neural network that can differentiate between cats and dogs. These days it doesn't seem like a big accomplishment, but five years ago it was a serious challenge for computer vision systems.
###Code
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
import matplotlib.pyplot as plt
import torch
from torchvision import datasets, transforms
import helper
###Output
_____no_output_____
###Markdown
The easiest way to load image data is with `datasets.ImageFolder` from `torchvision` ([documentation](http://pytorch.org/docs/master/torchvision/datasets.htmlimagefolder)). In general you'll use `ImageFolder` like so:```pythondataset = datasets.ImageFolder('path/to/data', transform=transform)```where `'path/to/data'` is the file path to the data directory and `transform` is a list of processing steps built with the [`transforms`](http://pytorch.org/docs/master/torchvision/transforms.html) module from `torchvision`. ImageFolder expects the files and directories to be constructed like so:```root/dog/xxx.pngroot/dog/xxy.pngroot/dog/xxz.pngroot/cat/123.pngroot/cat/nsdf3.pngroot/cat/asd932_.png```where each class has it's own directory (`cat` and `dog`) for the images. The images are then labeled with the class taken from the directory name. So here, the image `123.png` would be loaded with the class label `cat`. You can download the dataset already structured like this [from here](https://s3.amazonaws.com/content.udacity-data.com/nd089/Cat_Dog_data.zip). I've also split it into a training set and test set. TransformsWhen you load in the data with `ImageFolder`, you'll need to define some transforms. For example, the images are different sizes but we'll need them to all be the same size for training. You can either resize them with `transforms.Resize()` or crop with `transforms.CenterCrop()`, `transforms.RandomResizedCrop()`, etc. We'll also need to convert the images to PyTorch tensors with `transforms.ToTensor()`. Typically you'll combine these transforms into a pipeline with `transforms.Compose()`, which accepts a list of transforms and runs them in sequence. It looks something like this to scale, then crop, then convert to a tensor:```pythontransform = transforms.Compose([transforms.Resize(255), transforms.CenterCrop(224), transforms.ToTensor()])```There are plenty of transforms available, I'll cover more in a bit and you can read through the [documentation](http://pytorch.org/docs/master/torchvision/transforms.html). Data LoadersWith the `ImageFolder` loaded, you have to pass it to a [`DataLoader`](http://pytorch.org/docs/master/data.htmltorch.utils.data.DataLoader). The `DataLoader` takes a dataset (such as you would get from `ImageFolder`) and returns batches of images and the corresponding labels. You can set various parameters like the batch size and if the data is shuffled after each epoch.```pythondataloader = torch.utils.data.DataLoader(dataset, batch_size=32, shuffle=True)```Here `dataloader` is a [generator](https://jeffknupp.com/blog/2013/04/07/improve-your-python-yield-and-generators-explained/). To get data out of it, you need to loop through it or convert it to an iterator and call `next()`.```python Looping through it, get a batch on each loop for images, labels in dataloader: pass Get one batchimages, labels = next(iter(dataloader))``` >**Exercise:** Load images from the `Cat_Dog_data/train` folder, define a few transforms, then build the dataloader.
###Code
data_dir = 'Cat_Dog_data/train'
transform = transforms.Compose([transforms.Resize(255),
transforms.CenterCrop(224),
transforms.ToTensor()]) # TODO: compose transforms here
dataset = datasets.ImageFolder(data_dir, transform = transform) # TODO: create the ImageFolder
dataloader = torch.utils.data.DataLoader(dataset, batch_size=32, shuffle=True) # TODO: use the ImageFolder dataset to create the DataLoader
# Run this to test your data loader
images, labels = next(iter(dataloader))
helper.imshow(images[0], normalize=False)
###Output
_____no_output_____
###Markdown
If you loaded the data correctly, you should see something like this (your image will be different): Data AugmentationA common strategy for training neural networks is to introduce randomness in the input data itself. For example, you can randomly rotate, mirror, scale, and/or crop your images during training. This will help your network generalize as it's seeing the same images but in different locations, with different sizes, in different orientations, etc.To randomly rotate, scale and crop, then flip your images you would define your transforms like this:```pythontrain_transforms = transforms.Compose([transforms.RandomRotation(30), transforms.RandomResizedCrop(224), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])])```You'll also typically want to normalize images with `transforms.Normalize`. You pass in a list of means and list of standard deviations, then the color channels are normalized like so```input[channel] = (input[channel] - mean[channel]) / std[channel]```Subtracting `mean` centers the data around zero and dividing by `std` squishes the values to be between -1 and 1. Normalizing helps keep the network work weights near zero which in turn makes backpropagation more stable. Without normalization, networks will tend to fail to learn.You can find a list of all [the available transforms here](http://pytorch.org/docs/0.3.0/torchvision/transforms.html). When you're testing however, you'll want to use images that aren't altered (except you'll need to normalize the same way). So, for validation/test images, you'll typically just resize and crop.>**Exercise:** Define transforms for training data and testing data below. Leave off normalization for now.
###Code
data_dir = 'Cat_Dog_data'
# TODO: Define transforms for the training data and testing data
train_transforms = transforms.Compose([transforms.RandomRotation(30),
transforms.RandomResizedCrop(224),
transforms.RandomHorizontalFlip(),
transforms.ToTensor()])
test_transforms = transforms.Compose([transforms.Resize(255),
transforms.CenterCrop(224),
transforms.ToTensor()])
# Pass transforms in here, then run the next cell to see how the transforms look
train_data = datasets.ImageFolder(data_dir + '/train', transform=train_transforms)
test_data = datasets.ImageFolder(data_dir + '/test', transform=test_transforms)
trainloader = torch.utils.data.DataLoader(train_data, batch_size=32)
testloader = torch.utils.data.DataLoader(test_data, batch_size=32)
# change this to the trainloader or testloader
data_iter = iter(testloader)
images, labels = next(data_iter)
fig, axes = plt.subplots(figsize=(10,4), ncols=4)
for ii in range(4):
ax = axes[ii]
helper.imshow(images[ii], ax=ax, normalize=False)
###Output
_____no_output_____
###Markdown
Your transformed images should look something like this.Training examples:Testing examples: At this point you should be able to load data for training and testing. Now, you should try building a network that can classify cats vs dogs. This is quite a bit more complicated than before with the MNIST and Fashion-MNIST datasets. To be honest, you probably won't get it to work with a fully-connected network, no matter how deep. These images have three color channels and at a higher resolution (so far you've seen 28x28 images which are tiny).In the next part, I'll show you how to use a pre-trained network to build a model that can actually solve this problem.
###Code
# Optional TODO: Attempt to build a network to classify cats vs dogs from this dataset
###Output
_____no_output_____ |
FinRL_StockTrading_Fundamental.ipynb | ###Markdown
Automated stock trading using FinRL with financial dataTrained a Deep Reinforcement Learning model using FinRL and companies' financial ratio, and then backtested the model to examine how well-trained the model is* This Google Colabolatory notebook is based on the tutorial of FinRL: https://towardsdatascience.com/finrl-for-quantitative-finance-tutorial-for-multiple-stock-trading-7b00763b7530* This project is a final project of the almuni-mentored research project at Columbia University, Application of Reinforcement Learning to Finance, mentored by Bruce Yang from AI4Finance.* For more detailed explanation, please check out my Medium post: https://medium.com/@mariko.sawada1/automated-stock-trading-with-deep-reinforcement-learning-and-financial-data-a63286ccbe2b Content * [1. Problem Definition](0)* [2. Getting Started - Load Python packages](1) * [2.1. Install Packages](1.1) * [2.2. Check Additional Packages](1.2) * [2.3. Import Packages](1.3) * [2.4. Create Folders](1.4)* [3. Download Data](2)* [4. Preprocess fundamental Data](3) * [4-1 Import financial data](3.1) * [4-2 Specify items needed to calculate financial ratios](3.2) * [4-3 Calculate financial ratios](3.3) * [4-4 Deal with NAs and infinite values](3.4) * [4-5 Merge stock price data and ratios into one dataframe](3.5) * [4-6 Calculate market valuation ratios using daily stock price data](3.6)* [5.Build Environment](4) * [5.1. Training & Trade Data Split](4.1) * [5.2. User-defined Environment](4.2) * [5.3. Initialize Environment](4.3) * [6.Implement DRL Algorithms](5) * [7.Backtesting Performance](6) * [7.1. BackTestStats](6.1) * [7.2. BackTestPlot](6.2) * [7.3. Baseline Stats](6.3) * [7.3. Compare to Stock Market Index](6.4) Part 1. Problem Definition This problem is to design an automated trading solution for single stock trading. We model the stock trading process as a Markov Decision Process (MDP). We then formulate our trading goal as a maximization problem.The algorithm is trained using Deep Reinforcement Learning (DRL) algorithms and the components of the reinforcement learning environment are:* Action: The action space describes the allowed actions that the agent interacts with theenvironment. Normally, a ∈ A includes three actions: a ∈ {−1, 0, 1}, where −1, 0, 1 representselling, holding, and buying one stock. Also, an action can be carried upon multiple shares. We usean action space {−k, ..., −1, 0, 1, ..., k}, where k denotes the number of shares. For example, "Buy10 shares of AAPL" or "Sell 10 shares of AAPL" are 10 or −10, respectively* Reward function: r(s, a, s′) is the incentive mechanism for an agent to learn a better action. The change of the portfolio value when action a is taken at state s and arriving at new state s', i.e., r(s, a, s′) = v′ − v, where v′ and v represent the portfoliovalues at state s′ and s, respectively* State: The state space describes the observations that the agent receives from the environment. Just as a human trader needs to analyze various information before executing a trade, soour trading agent observes many different features to better learn in an interactive environment.* Environment: Dow 30 consituentsThe data of the single stock that we will be using for this case study is obtained from Yahoo Finance API. The data contains Open-High-Low-Close price and volume. Part 2. Load Python Packages 2.1. Install all the packages through FinRL library
###Code
## install finrl library
!pip install git+https://github.com/AI4Finance-LLC/FinRL-Library.git
###Output
Collecting git+https://github.com/AI4Finance-LLC/FinRL-Library.git
Cloning https://github.com/AI4Finance-LLC/FinRL-Library.git to /tmp/pip-req-build-sh40mnb8
Running command git clone -q https://github.com/AI4Finance-LLC/FinRL-Library.git /tmp/pip-req-build-sh40mnb8
Collecting pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2
Cloning https://github.com/quantopian/pyfolio.git to /tmp/pip-install-djvoe7ii/pyfolio_43f26b0cfe004ec394108e8d73166b45
Running command git clone -q https://github.com/quantopian/pyfolio.git /tmp/pip-install-djvoe7ii/pyfolio_43f26b0cfe004ec394108e8d73166b45
Requirement already satisfied: numpy>=1.17.3 in /usr/local/lib/python3.7/dist-packages (from finrl==0.3.0) (1.19.5)
Requirement already satisfied: pandas>=1.1.5 in /usr/local/lib/python3.7/dist-packages (from finrl==0.3.0) (1.1.5)
Requirement already satisfied: stockstats in /usr/local/lib/python3.7/dist-packages (from finrl==0.3.0) (0.3.2)
Requirement already satisfied: yfinance in /usr/local/lib/python3.7/dist-packages (from finrl==0.3.0) (0.1.63)
Requirement already satisfied: matplotlib in /usr/local/lib/python3.7/dist-packages (from finrl==0.3.0) (3.2.2)
Requirement already satisfied: scikit-learn>=0.21.0 in /usr/local/lib/python3.7/dist-packages (from finrl==0.3.0) (0.22.2.post1)
Requirement already satisfied: gym>=0.17 in /usr/local/lib/python3.7/dist-packages (from finrl==0.3.0) (0.17.3)
Requirement already satisfied: stable-baselines3[extra] in /usr/local/lib/python3.7/dist-packages (from finrl==0.3.0) (1.1.0)
Requirement already satisfied: pytest in /usr/local/lib/python3.7/dist-packages (from finrl==0.3.0) (3.6.4)
Requirement already satisfied: setuptools>=41.4.0 in /usr/local/lib/python3.7/dist-packages (from finrl==0.3.0) (57.4.0)
Requirement already satisfied: wheel>=0.33.6 in /usr/local/lib/python3.7/dist-packages (from finrl==0.3.0) (0.37.0)
Requirement already satisfied: ipython>=3.2.3 in /usr/local/lib/python3.7/dist-packages (from pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (5.5.0)
Requirement already satisfied: pytz>=2014.10 in /usr/local/lib/python3.7/dist-packages (from pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (2018.9)
Requirement already satisfied: scipy>=0.14.0 in /usr/local/lib/python3.7/dist-packages (from pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (1.4.1)
Requirement already satisfied: seaborn>=0.7.1 in /usr/local/lib/python3.7/dist-packages (from pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (0.11.1)
Requirement already satisfied: empyrical>=0.5.0 in /usr/local/lib/python3.7/dist-packages (from pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (0.5.5)
Requirement already satisfied: pandas-datareader>=0.2 in /usr/local/lib/python3.7/dist-packages (from empyrical>=0.5.0->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (0.9.0)
Requirement already satisfied: cloudpickle<1.7.0,>=1.2.0 in /usr/local/lib/python3.7/dist-packages (from gym>=0.17->finrl==0.3.0) (1.3.0)
Requirement already satisfied: pyglet<=1.5.0,>=1.4.0 in /usr/local/lib/python3.7/dist-packages (from gym>=0.17->finrl==0.3.0) (1.5.0)
Requirement already satisfied: decorator in /usr/local/lib/python3.7/dist-packages (from ipython>=3.2.3->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (4.4.2)
Requirement already satisfied: pexpect in /usr/local/lib/python3.7/dist-packages (from ipython>=3.2.3->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (4.8.0)
Requirement already satisfied: simplegeneric>0.8 in /usr/local/lib/python3.7/dist-packages (from ipython>=3.2.3->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (0.8.1)
Requirement already satisfied: prompt-toolkit<2.0.0,>=1.0.4 in /usr/local/lib/python3.7/dist-packages (from ipython>=3.2.3->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (1.0.18)
Requirement already satisfied: pygments in /usr/local/lib/python3.7/dist-packages (from ipython>=3.2.3->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (2.6.1)
Requirement already satisfied: traitlets>=4.2 in /usr/local/lib/python3.7/dist-packages (from ipython>=3.2.3->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (5.0.5)
Requirement already satisfied: pickleshare in /usr/local/lib/python3.7/dist-packages (from ipython>=3.2.3->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (0.7.5)
Requirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->finrl==0.3.0) (2.8.2)
Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->finrl==0.3.0) (1.3.1)
Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib->finrl==0.3.0) (0.10.0)
Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->finrl==0.3.0) (2.4.7)
Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from cycler>=0.10->matplotlib->finrl==0.3.0) (1.15.0)
Requirement already satisfied: requests>=2.19.0 in /usr/local/lib/python3.7/dist-packages (from pandas-datareader>=0.2->empyrical>=0.5.0->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (2.23.0)
Requirement already satisfied: lxml in /usr/local/lib/python3.7/dist-packages (from pandas-datareader>=0.2->empyrical>=0.5.0->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (4.6.3)
Requirement already satisfied: wcwidth in /usr/local/lib/python3.7/dist-packages (from prompt-toolkit<2.0.0,>=1.0.4->ipython>=3.2.3->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (0.2.5)
Requirement already satisfied: future in /usr/local/lib/python3.7/dist-packages (from pyglet<=1.5.0,>=1.4.0->gym>=0.17->finrl==0.3.0) (0.16.0)
Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19.0->pandas-datareader>=0.2->empyrical>=0.5.0->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (2.10)
Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19.0->pandas-datareader>=0.2->empyrical>=0.5.0->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (2021.5.30)
Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19.0->pandas-datareader>=0.2->empyrical>=0.5.0->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (1.24.3)
Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19.0->pandas-datareader>=0.2->empyrical>=0.5.0->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (3.0.4)
Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn>=0.21.0->finrl==0.3.0) (1.0.1)
Requirement already satisfied: ipython-genutils in /usr/local/lib/python3.7/dist-packages (from traitlets>=4.2->ipython>=3.2.3->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (0.2.0)
Requirement already satisfied: ptyprocess>=0.5 in /usr/local/lib/python3.7/dist-packages (from pexpect->ipython>=3.2.3->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (0.7.0)
Requirement already satisfied: more-itertools>=4.0.0 in /usr/local/lib/python3.7/dist-packages (from pytest->finrl==0.3.0) (8.8.0)
Requirement already satisfied: attrs>=17.4.0 in /usr/local/lib/python3.7/dist-packages (from pytest->finrl==0.3.0) (21.2.0)
Requirement already satisfied: atomicwrites>=1.0 in /usr/local/lib/python3.7/dist-packages (from pytest->finrl==0.3.0) (1.4.0)
Requirement already satisfied: py>=1.5.0 in /usr/local/lib/python3.7/dist-packages (from pytest->finrl==0.3.0) (1.10.0)
Requirement already satisfied: pluggy<0.8,>=0.5 in /usr/local/lib/python3.7/dist-packages (from pytest->finrl==0.3.0) (0.7.1)
Requirement already satisfied: torch>=1.4.0 in /usr/local/lib/python3.7/dist-packages (from stable-baselines3[extra]->finrl==0.3.0) (1.9.0+cu102)
Requirement already satisfied: pillow in /usr/local/lib/python3.7/dist-packages (from stable-baselines3[extra]->finrl==0.3.0) (7.1.2)
Requirement already satisfied: opencv-python in /usr/local/lib/python3.7/dist-packages (from stable-baselines3[extra]->finrl==0.3.0) (4.1.2.30)
Requirement already satisfied: atari-py~=0.2.0 in /usr/local/lib/python3.7/dist-packages (from stable-baselines3[extra]->finrl==0.3.0) (0.2.9)
Requirement already satisfied: psutil in /usr/local/lib/python3.7/dist-packages (from stable-baselines3[extra]->finrl==0.3.0) (5.4.8)
Requirement already satisfied: tensorboard>=2.2.0 in /usr/local/lib/python3.7/dist-packages (from stable-baselines3[extra]->finrl==0.3.0) (2.5.0)
Requirement already satisfied: protobuf>=3.6.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.0) (3.17.3)
Requirement already satisfied: grpcio>=1.24.3 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.0) (1.34.1)
Requirement already satisfied: werkzeug>=0.11.15 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.0) (1.0.1)
Requirement already satisfied: absl-py>=0.4 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.0) (0.12.0)
Requirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.0) (3.3.4)
Requirement already satisfied: tensorboard-data-server<0.7.0,>=0.6.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.0) (0.6.1)
Requirement already satisfied: google-auth<2,>=1.6.3 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.0) (1.34.0)
Requirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.0) (0.4.5)
Requirement already satisfied: tensorboard-plugin-wit>=1.6.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.0) (1.8.0)
Requirement already satisfied: rsa<5,>=3.1.4 in /usr/local/lib/python3.7/dist-packages (from google-auth<2,>=1.6.3->tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.0) (4.7.2)
Requirement already satisfied: cachetools<5.0,>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from google-auth<2,>=1.6.3->tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.0) (4.2.2)
Requirement already satisfied: pyasn1-modules>=0.2.1 in /usr/local/lib/python3.7/dist-packages (from google-auth<2,>=1.6.3->tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.0) (0.2.8)
Requirement already satisfied: requests-oauthlib>=0.7.0 in /usr/local/lib/python3.7/dist-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.0) (1.3.0)
Requirement already satisfied: importlib-metadata in /usr/local/lib/python3.7/dist-packages (from markdown>=2.6.8->tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.0) (4.6.3)
Requirement already satisfied: pyasn1<0.5.0,>=0.4.6 in /usr/local/lib/python3.7/dist-packages (from pyasn1-modules>=0.2.1->google-auth<2,>=1.6.3->tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.0) (0.4.8)
Requirement already satisfied: oauthlib>=3.0.0 in /usr/local/lib/python3.7/dist-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.0) (3.1.1)
Requirement already satisfied: typing-extensions in /usr/local/lib/python3.7/dist-packages (from torch>=1.4.0->stable-baselines3[extra]->finrl==0.3.0) (3.7.4.3)
Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata->markdown>=2.6.8->tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.0) (3.5.0)
Requirement already satisfied: int-date>=0.1.7 in /usr/local/lib/python3.7/dist-packages (from stockstats->finrl==0.3.0) (0.1.8)
Requirement already satisfied: multitasking>=0.0.7 in /usr/local/lib/python3.7/dist-packages (from yfinance->finrl==0.3.0) (0.0.9)
###Markdown
2.2. Check if the additional packages needed are present, if not install them. * Yahoo Finance API* pandas* numpy* matplotlib* stockstats* OpenAI gym* stable-baselines* tensorflow* pyfolio 2.3. Import Packages
###Code
import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
# matplotlib.use('Agg')
import datetime
%matplotlib inline
from finrl.apps import config
from finrl.neo_finrl.preprocessor.yahoodownloader import YahooDownloader
from finrl.neo_finrl.preprocessor.preprocessors import FeatureEngineer, data_split
from finrl.neo_finrl.env_stock_trading.env_stocktrading import StockTradingEnv
from finrl.drl_agents.stablebaselines3.models import DRLAgent
from finrl.plot import backtest_stats, backtest_plot, get_daily_return, get_baseline
from pprint import pprint
import sys
sys.path.append("../FinRL-Library")
import itertools
###Output
/home/taylor/.local/lib/python3.8/site-packages/pyfolio/pos.py:26: UserWarning: Module "zipline.assets" not found; multipliers will not be applied to position notionals.
warnings.warn(
###Markdown
2.4. Create Folders
###Code
import os
if not os.path.exists("./" + config.DATA_SAVE_DIR):
os.makedirs("./" + config.DATA_SAVE_DIR)
if not os.path.exists("./" + config.TRAINED_MODEL_DIR):
os.makedirs("./" + config.TRAINED_MODEL_DIR)
if not os.path.exists("./" + config.TENSORBOARD_LOG_DIR):
os.makedirs("./" + config.TENSORBOARD_LOG_DIR)
if not os.path.exists("./" + config.RESULTS_DIR):
os.makedirs("./" + config.RESULTS_DIR)
###Output
_____no_output_____
###Markdown
Part 3. Download Stock Data from Yahoo FinanceYahoo Finance is a website that provides stock data, financial news, financial reports, etc. All the data provided by Yahoo Finance is free.* FinRL uses a class **YahooDownloader** to fetch data from Yahoo Finance API* Call Limit: Using the Public API (without authentication), you are limited to 2,000 requests per hour per IP (or up to a total of 48,000 requests a day). -----class YahooDownloader: Provides methods for retrieving daily stock data from Yahoo Finance API Attributes ---------- start_date : str start date of the data (modified from config.py) end_date : str end date of the data (modified from config.py) ticker_list : list a list of stock tickers (modified from config.py) Methods ------- fetch_data() Fetches data from yahoo API
###Code
# from config.py start_date is a string
config.START_DATE
# from config.py end_date is a string
config.END_DATE
print(config.DOW_30_TICKER)
df = YahooDownloader(start_date = '2009-01-01',
end_date = '2021-01-01',
ticker_list = config.DOW_30_TICKER).fetch_data()
df.shape
df.head()
df['date'] = pd.to_datetime(df['date'],format='%Y-%m-%d')
df.sort_values(['date','tic'],ignore_index=True).head()
###Output
_____no_output_____
###Markdown
Part 4: Preprocess fundamental data- Import finanical data downloaded from Compustat via WRDS(Wharton Research Data Service)- Preprocess the dataset and calculate financial ratios- Add those ratios to the price data preprocessed in Part 3- Calculate price-related ratios such as P/E and P/B 4-1 Import the financial data
###Code
# Import fundamental data from my GitHub repository
url = 'https://raw.githubusercontent.com/mariko-sawada/FinRL_with_fundamental_data/main/dow_30_fundamental_wrds.csv'
fund = pd.read_csv(url)
# Check the imported dataset
fund.head()
###Output
_____no_output_____
###Markdown
4-2 Specify items needed to calculate financial ratios- To know more about the data description of the dataset, please check WRDS's website(https://wrds-www.wharton.upenn.edu/). Login will be required.
###Code
# List items that are used to calculate financial ratios
items = [
'datadate', # Date
'tic', # Ticker
'oiadpq', # Quarterly operating income
'revtq', # Quartely revenue
'niq', # Quartely net income
'atq', # Total asset
'teqq', # Shareholder's equity
'epspiy', # EPS(Basic) incl. Extraordinary items
'ceqq', # Common Equity
'cshoq', # Common Shares Outstanding
'dvpspq', # Dividends per share
'actq', # Current assets
'lctq', # Current liabilities
'cheq', # Cash & Equivalent
'rectq', # Recievalbles
'cogsq', # Cost of Goods Sold
'invtq', # Inventories
'apq',# Account payable
'dlttq', # Long term debt
'dlcq', # Debt in current liabilites
'ltq' # Liabilities
]
# Omit items that will not be used
fund_data = fund[items]
# Rename column names for the sake of readability
fund_data = fund_data.rename(columns={
'datadate':'date', # Date
'oiadpq':'op_inc_q', # Quarterly operating income
'revtq':'rev_q', # Quartely revenue
'niq':'net_inc_q', # Quartely net income
'atq':'tot_assets', # Assets
'teqq':'sh_equity', # Shareholder's equity
'epspiy':'eps_incl_ex', # EPS(Basic) incl. Extraordinary items
'ceqq':'com_eq', # Common Equity
'cshoq':'sh_outstanding', # Common Shares Outstanding
'dvpspq':'div_per_sh', # Dividends per share
'actq':'cur_assets', # Current assets
'lctq':'cur_liabilities', # Current liabilities
'cheq':'cash_eq', # Cash & Equivalent
'rectq':'receivables', # Receivalbles
'cogsq':'cogs_q', # Cost of Goods Sold
'invtq':'inventories', # Inventories
'apq': 'payables',# Account payable
'dlttq':'long_debt', # Long term debt
'dlcq':'short_debt', # Debt in current liabilites
'ltq':'tot_liabilities' # Liabilities
})
# Check the data
fund_data.head()
###Output
_____no_output_____
###Markdown
4-3 Calculate financial ratios- For items from Profit/Loss statements, we calculate LTM (Last Twelve Months) and use them to derive profitability related ratios such as Operating Maring and ROE. For items from balance sheets, we use the numbers on the day.- To check the definitions of the financial ratios calculated here, please refer to CFI's website: https://corporatefinanceinstitute.com/resources/knowledge/finance/financial-ratios/
###Code
# Calculate financial ratios
date = pd.to_datetime(fund_data['date'],format='%Y%m%d')
tic = fund_data['tic'].to_frame('tic')
# Profitability ratios
# Operating Margin
OPM = pd.Series(np.empty(fund_data.shape[0],dtype=object),name='OPM')
for i in range(0, fund_data.shape[0]):
if i-3 < 0:
OPM[i] = np.nan
elif fund_data.iloc[i,1] != fund_data.iloc[i-3,1]:
OPM.iloc[i] = np.nan
else:
OPM.iloc[i] = np.sum(fund_data['op_inc_q'].iloc[i-3:i])/np.sum(fund_data['rev_q'].iloc[i-3:i])
# Net Profit Margin
NPM = pd.Series(np.empty(fund_data.shape[0],dtype=object),name='NPM')
for i in range(0, fund_data.shape[0]):
if i-3 < 0:
NPM[i] = np.nan
elif fund_data.iloc[i,1] != fund_data.iloc[i-3,1]:
NPM.iloc[i] = np.nan
else:
NPM.iloc[i] = np.sum(fund_data['net_inc_q'].iloc[i-3:i])/np.sum(fund_data['rev_q'].iloc[i-3:i])
# Return On Assets
ROA = pd.Series(np.empty(fund_data.shape[0],dtype=object),name='ROA')
for i in range(0, fund_data.shape[0]):
if i-3 < 0:
ROA[i] = np.nan
elif fund_data.iloc[i,1] != fund_data.iloc[i-3,1]:
ROA.iloc[i] = np.nan
else:
ROA.iloc[i] = np.sum(fund_data['net_inc_q'].iloc[i-3:i])/fund_data['tot_assets'].iloc[i]
# Return on Equity
ROE = pd.Series(np.empty(fund_data.shape[0],dtype=object),name='ROE')
for i in range(0, fund_data.shape[0]):
if i-3 < 0:
ROE[i] = np.nan
elif fund_data.iloc[i,1] != fund_data.iloc[i-3,1]:
ROE.iloc[i] = np.nan
else:
ROE.iloc[i] = np.sum(fund_data['net_inc_q'].iloc[i-3:i])/fund_data['sh_equity'].iloc[i]
# For calculating valuation ratios in the next subpart, calculate per share items in advance
# Earnings Per Share
EPS = fund_data['eps_incl_ex'].to_frame('EPS')
# Book Per Share
BPS = (fund_data['com_eq']/fund_data['sh_outstanding']).to_frame('BPS') # Need to check units
#Dividend Per Share
DPS = fund_data['div_per_sh'].to_frame('DPS')
# Liquidity ratios
# Current ratio
cur_ratio = (fund_data['cur_assets']/fund_data['cur_liabilities']).to_frame('cur_ratio')
# Quick ratio
quick_ratio = ((fund_data['cash_eq'] + fund_data['receivables'] )/fund_data['cur_liabilities']).to_frame('quick_ratio')
# Cash ratio
cash_ratio = (fund_data['cash_eq']/fund_data['cur_liabilities']).to_frame('cash_ratio')
# Efficiency ratios
# Inventory turnover ratio
inv_turnover = pd.Series(np.empty(fund_data.shape[0],dtype=object),name='inv_turnover')
for i in range(0, fund_data.shape[0]):
if i-3 < 0:
inv_turnover[i] = np.nan
elif fund_data.iloc[i,1] != fund_data.iloc[i-3,1]:
inv_turnover.iloc[i] = np.nan
else:
inv_turnover.iloc[i] = np.sum(fund_data['cogs_q'].iloc[i-3:i])/fund_data['inventories'].iloc[i]
# Receivables turnover ratio
acc_rec_turnover = pd.Series(np.empty(fund_data.shape[0],dtype=object),name='acc_rec_turnover')
for i in range(0, fund_data.shape[0]):
if i-3 < 0:
acc_rec_turnover[i] = np.nan
elif fund_data.iloc[i,1] != fund_data.iloc[i-3,1]:
acc_rec_turnover.iloc[i] = np.nan
else:
acc_rec_turnover.iloc[i] = np.sum(fund_data['rev_q'].iloc[i-3:i])/fund_data['receivables'].iloc[i]
# Payable turnover ratio
acc_pay_turnover = pd.Series(np.empty(fund_data.shape[0],dtype=object),name='acc_pay_turnover')
for i in range(0, fund_data.shape[0]):
if i-3 < 0:
acc_pay_turnover[i] = np.nan
elif fund_data.iloc[i,1] != fund_data.iloc[i-3,1]:
acc_pay_turnover.iloc[i] = np.nan
else:
acc_pay_turnover.iloc[i] = np.sum(fund_data['cogs_q'].iloc[i-3:i])/fund_data['payables'].iloc[i]
## Leverage financial ratios
# Debt ratio
debt_ratio = (fund_data['tot_liabilities']/fund_data['tot_assets']).to_frame('debt_ratio')
# Debt to Equity ratio
debt_to_equity = (fund_data['tot_liabilities']/fund_data['sh_equity']).to_frame('debt_to_equity')
# Create a dataframe that merges all the ratios
ratios = pd.concat([date,tic,OPM,NPM,ROA,ROE,EPS,BPS,DPS,
cur_ratio,quick_ratio,cash_ratio,inv_turnover,acc_rec_turnover,acc_pay_turnover,
debt_ratio,debt_to_equity], axis=1)
# Check the ratio data
ratios.head()
ratios.tail()
###Output
_____no_output_____
###Markdown
4-4 Deal with NAs and infinite values- We replace N/A and infinite values with zero so that they can be recognized as a state
###Code
# Replace NAs infinite values with zero
final_ratios = ratios.copy()
final_ratios = final_ratios.fillna(0)
final_ratios = final_ratios.replace(np.inf,0)
final_ratios.head()
final_ratios.tail()
###Output
_____no_output_____
###Markdown
4-5 Merge stock price data and ratios into one dataframe- Merge the price dataframe preprocessed in Part 3 and the ratio dataframe created in this part- Since the prices are daily and ratios are quartely, we have NAs in the ratio columns after merging the two dataframes. We deal with this by backfilling the ratios.
###Code
list_ticker = df["tic"].unique().tolist()
list_date = list(pd.date_range(df['date'].min(),df['date'].max()))
combination = list(itertools.product(list_date,list_ticker))
# Merge stock price data and ratios into one dataframe
processed_full = pd.DataFrame(combination,columns=["date","tic"]).merge(df,on=["date","tic"],how="left")
processed_full = processed_full.merge(final_ratios,how='left',on=['date','tic'])
processed_full = processed_full.sort_values(['tic','date'])
# Backfill the ratio data to make them daily
processed_full = processed_full.bfill(axis='rows')
###Output
_____no_output_____
###Markdown
4-6 Calculate market valuation ratios using daily stock price data
###Code
# Calculate P/E, P/B and dividend yield using daily closing price
processed_full['PE'] = processed_full['close']/processed_full['EPS']
processed_full['PB'] = processed_full['close']/processed_full['BPS']
processed_full['Div_yield'] = processed_full['DPS']/processed_full['close']
# Drop per share items used for the above calculation
processed_full = processed_full.drop(columns=['day','EPS','BPS','DPS'])
# Check the final data
processed_full.sort_values(['date','tic'],ignore_index=True).head(10)
###Output
_____no_output_____
###Markdown
Part 5. Design EnvironmentConsidering the stochastic and interactive nature of the automated stock trading tasks, a financial task is modeled as a **Markov Decision Process (MDP)** problem. The training process involves observing stock price change, taking an action and reward's calculation to have the agent adjusting its strategy accordingly. By interacting with the environment, the trading agent will derive a trading strategy with the maximized rewards as time proceeds.Our trading environments, based on OpenAI Gym framework, simulate live stock markets with real market data according to the principle of time-driven simulation.The action space describes the allowed actions that the agent interacts with the environment. Normally, action a includes three actions: {-1, 0, 1}, where -1, 0, 1 represent selling, holding, and buying one share. Also, an action can be carried upon multiple shares. We use an action space {-k,…,-1, 0, 1, …, k}, where k denotes the number of shares to buy and -k denotes the number of shares to sell. For example, "Buy 10 shares of AAPL" or "Sell 10 shares of AAPL" are 10 or -10, respectively. The continuous action space needs to be normalized to [-1, 1], since the policy is defined on a Gaussian distribution, which needs to be normalized and symmetric. 5-1 Split data into training and trade dataset- Training data split: 2009-01-01 to 2018-12-31- Trade data split: 2019-01-01 to 2020-09-30
###Code
train = data_split(processed_full, '2009-01-01','2019-01-01')
trade = data_split(processed_full, '2019-01-01','2021-01-01')
# Check the length of the two datasets
print(len(train))
print(len(trade))
train.head()
trade.head()
###Output
_____no_output_____
###Markdown
5-2 Set up the training environment
###Code
ratio_list = ['OPM', 'NPM','ROA', 'ROE', 'cur_ratio', 'quick_ratio', 'cash_ratio', 'inv_turnover','acc_rec_turnover', 'acc_pay_turnover', 'debt_ratio', 'debt_to_equity',
'PE', 'PB', 'Div_yield']
stock_dimension = len(train.tic.unique())
state_space = 1 + 2*stock_dimension + len(ratio_list)*stock_dimension
print(f"Stock Dimension: {stock_dimension}, State Space: {state_space}")
# Parameters for the environment
env_kwargs = {
"hmax": 100,
"initial_amount": 1000000,
"buy_cost_pct": 0.001,
"sell_cost_pct": 0.001,
"state_space": state_space,
"stock_dim": stock_dimension,
"tech_indicator_list": ratio_list,
"action_space": stock_dimension,
"reward_scaling": 1e-4
}
#Establish the training environment using StockTradingEnv() class
e_train_gym = StockTradingEnv(df = train, **env_kwargs)
###Output
_____no_output_____
###Markdown
Environment for Training
###Code
env_train, _ = e_train_gym.get_sb_env()
print(type(env_train))
###Output
<class 'stable_baselines3.common.vec_env.dummy_vec_env.DummyVecEnv'>
###Markdown
Part 6: Implement DRL Algorithms* The implementation of the DRL algorithms are based on **OpenAI Baselines** and **Stable Baselines**. Stable Baselines is a fork of OpenAI Baselines, with a major structural refactoring, and code cleanups.* FinRL library includes fine-tuned standard DRL algorithms, such as DQN, DDPG,Multi-Agent DDPG, PPO, SAC, A2C and TD3. We also allow users todesign their own DRL algorithms by adapting these DRL algorithms.
###Code
# Set up the agent using DRLAgent() class using the environment created in the previous part
agent = DRLAgent(env = env_train)
###Output
_____no_output_____
###Markdown
Model Training: 5 models, A2C DDPG, PPO, TD3, SAC Model 1: A2C
###Code
agent = DRLAgent(env = env_train)
model_a2c = agent.get_model("a2c")
trained_a2c = agent.train_model(model=model_a2c,
tb_log_name='a2c',
total_timesteps=100000)
###Output
Logging to tensorboard_log/a2c/a2c_1
###Markdown
Model 2: DDPG
###Code
agent = DRLAgent(env = env_train)
model_ddpg = agent.get_model("ddpg")
trained_ddpg = agent.train_model(model=model_ddpg,
tb_log_name='ddpg',
total_timesteps=50000)
###Output
Logging to tensorboard_log/ddpg/ddpg_1
###Markdown
Model 3: PPO
###Code
agent = DRLAgent(env = env_train)
PPO_PARAMS = {
"n_steps": 2048,
"ent_coef": 0.01,
"learning_rate": 0.00025,
"batch_size": 128,
}
model_ppo = agent.get_model("ppo",model_kwargs = PPO_PARAMS)
trained_ppo = agent.train_model(model=model_ppo,
tb_log_name='ppo',
total_timesteps=50000)
###Output
Logging to tensorboard_log/ppo/ppo_1
------------------------------------
| time/ | |
| fps | 120 |
| iterations | 1 |
| time_elapsed | 16 |
| total_timesteps | 2048 |
| train/ | |
| reward | -0.31566185 |
------------------------------------
###Markdown
Model 4: TD3
###Code
agent = DRLAgent(env = env_train)
TD3_PARAMS = {"batch_size": 100,
"buffer_size": 1000000,
"learning_rate": 0.001}
model_td3 = agent.get_model("td3",model_kwargs = TD3_PARAMS)
trained_td3 = agent.train_model(model=model_td3,
tb_log_name='td3',
total_timesteps=30000)
###Output
Logging to tensorboard_log/td3/td3_1
---------------------------------
| time/ | |
| episodes | 4 |
| fps | 26 |
| time_elapsed | 559 |
| total timesteps | 14604 |
| train/ | |
| actor_loss | 4.64 |
| critic_loss | 720 |
| learning_rate | 0.001 |
| n_updates | 10953 |
---------------------------------
---------------------------------
| time/ | |
| episodes | 8 |
| fps | 22 |
| time_elapsed | 1289 |
| total timesteps | 29208 |
| train/ | |
| actor_loss | 10.6 |
| critic_loss | 14.2 |
| learning_rate | 0.001 |
| n_updates | 25557 |
---------------------------------
day: 3650, episode: 40
begin_total_asset: 1000000.00
end_total_asset: 3319811.55
total_reward: 2319811.55
total_cost: 998.99
total_trades: 51100
Sharpe: 0.649
=================================
###Markdown
Model 5: SAC
###Code
agent = DRLAgent(env = env_train)
SAC_PARAMS = {
"batch_size": 128,
"buffer_size": 1000000,
"learning_rate": 0.0001,
"learning_starts": 100,
"ent_coef": "auto_0.1",
}
model_sac = agent.get_model("sac",model_kwargs = SAC_PARAMS)
trained_sac = agent.train_model(model=model_sac,
tb_log_name='sac',
total_timesteps=80000)
###Output
Logging to tensorboard_log/sac/sac_2
---------------------------------
| time/ | |
| episodes | 4 |
| fps | 21 |
| time_elapsed | 685 |
| total timesteps | 14604 |
| train/ | |
| actor_loss | 172 |
| critic_loss | 28.6 |
| ent_coef | 0.0742 |
| ent_coef_loss | -126 |
| learning_rate | 0.0001 |
| n_updates | 14503 |
---------------------------------
---------------------------------
| time/ | |
| episodes | 8 |
| fps | 20 |
| time_elapsed | 1401 |
| total timesteps | 29208 |
| train/ | |
| actor_loss | 9.68 |
| critic_loss | 9.81 |
| ent_coef | 0.0174 |
| ent_coef_loss | -173 |
| learning_rate | 0.0001 |
| n_updates | 29107 |
---------------------------------
day: 3650, episode: 10
begin_total_asset: 1000000.00
end_total_asset: 4889674.97
total_reward: 3889674.97
total_cost: 7706.97
total_trades: 70158
Sharpe: 0.752
=================================
---------------------------------
| time/ | |
| episodes | 12 |
| fps | 20 |
| time_elapsed | 2114 |
| total timesteps | 43812 |
| train/ | |
| actor_loss | -13.3 |
| critic_loss | 14 |
| ent_coef | 0.00427 |
| ent_coef_loss | -128 |
| learning_rate | 0.0001 |
| n_updates | 43711 |
---------------------------------
---------------------------------
| time/ | |
| episodes | 16 |
| fps | 20 |
| time_elapsed | 2842 |
| total timesteps | 58416 |
| train/ | |
| actor_loss | -7 |
| critic_loss | 8.71 |
| ent_coef | 0.00148 |
| ent_coef_loss | -3.87 |
| learning_rate | 0.0001 |
| n_updates | 58315 |
---------------------------------
day: 3650, episode: 20
begin_total_asset: 1000000.00
end_total_asset: 3389166.27
total_reward: 2389166.27
total_cost: 1895.61
total_trades: 62481
Sharpe: 0.623
=================================
---------------------------------
| time/ | |
| episodes | 20 |
| fps | 20 |
| time_elapsed | 3585 |
| total timesteps | 73020 |
| train/ | |
| actor_loss | -4.82 |
| critic_loss | 12.4 |
| ent_coef | 0.00159 |
| ent_coef_loss | -4.38 |
| learning_rate | 0.0001 |
| n_updates | 72919 |
---------------------------------
###Markdown
TradingAssume that we have $1,000,000 initial capital at 2019-01-01. We use the DDPG model to trade Dow jones 30 stocks. TradeDRL model needs to update periodically in order to take full advantage of the data, ideally we need to retrain our model yearly, quarterly, or monthly. We also need to tune the parameters along the way, in this notebook I only use the in-sample data from 2009-01 to 2018-12 to tune the parameters once, so there is some alpha decay here as the length of trade date extends. Numerous hyperparameters – e.g. the learning rate, the total number of samples to train on – influence the learning process and are usually determined by testing some variations.
###Code
trade = data_split(processed_full, '2019-01-01','2021-01-01')
e_trade_gym = StockTradingEnv(df = trade, **env_kwargs)
# env_trade, obs_trade = e_trade_gym.get_sb_env()
trade.head()
df_account_value, df_actions = DRLAgent.DRL_prediction(
model=trained_ddpg,
environment = e_trade_gym)
df_account_value.shape
df_account_value.tail()
df_actions.head()
###Output
_____no_output_____
###Markdown
Part 7: Backtest Our StrategyBacktesting plays a key role in evaluating the performance of a trading strategy. Automated backtesting tool is preferred because it reduces the human error. We usually use the Quantopian pyfolio package to backtest our trading strategies. It is easy to use and consists of various individual plots that provide a comprehensive image of the performance of a trading strategy. 7.1 BackTestStatspass in df_account_value, this information is stored in env class
###Code
print("==============Get Backtest Results===========")
now = datetime.datetime.now().strftime('%Y%m%d-%Hh%M')
perf_stats_all = backtest_stats(account_value=df_account_value)
perf_stats_all = pd.DataFrame(perf_stats_all)
perf_stats_all.to_csv("./"+config.RESULTS_DIR+"/perf_stats_all_"+now+'.csv')
#baseline stats
print("==============Get Baseline Stats===========")
baseline_df = get_baseline(
ticker="^DJI",
start = '2019-01-01',
end = '2021-01-01')
stats = backtest_stats(baseline_df, value_col_name = 'close')
###Output
==============Get Baseline Stats===========
[*********************100%***********************] 1 of 1 completed
Shape of DataFrame: (505, 8)
Annual return 0.144674
Cumulative returns 0.310981
Annual volatility 0.274619
Sharpe ratio 0.631418
Calmar ratio 0.390102
Stability 0.116677
Max drawdown -0.370862
Omega ratio 1.149365
Sortino ratio 0.870084
Skew NaN
Kurtosis NaN
Tail ratio 0.860710
Daily value at risk -0.033911
dtype: float64
###Markdown
7.2 BackTestPlot
###Code
print("==============Compare to DJIA===========")
%matplotlib inline
# S&P 500: ^GSPC
# Dow Jones Index: ^DJI
# NASDAQ 100: ^NDX
backtest_plot(df_account_value,
baseline_ticker = '^DJI',
baseline_start = '2019-01-01',
baseline_end = '2021-01-01')
pip install pandas==1.2.5
###Output
Collecting pandas==1.2.5
Downloading pandas-1.2.5-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.whl (9.7 MB)
[K |████████████████████████████████| 9.7 MB 4.5 MB/s eta 0:00:01
[?25hRequirement already satisfied: python-dateutil>=2.7.3 in /home/taylor/.local/lib/python3.8/site-packages (from pandas==1.2.5) (2.8.2)
Requirement already satisfied: pytz>=2017.3 in /home/taylor/.local/lib/python3.8/site-packages (from pandas==1.2.5) (2021.3)
Requirement already satisfied: numpy>=1.16.5 in /home/taylor/.local/lib/python3.8/site-packages (from pandas==1.2.5) (1.21.4)
Requirement already satisfied: six>=1.5 in /usr/lib/python3/dist-packages (from python-dateutil>=2.7.3->pandas==1.2.5) (1.14.0)
Installing collected packages: pandas
Attempting uninstall: pandas
Found existing installation: pandas 1.3.4
Uninstalling pandas-1.3.4:
Successfully uninstalled pandas-1.3.4
Successfully installed pandas-1.2.5
Note: you may need to restart the kernel to use updated packages.
###Markdown
Automated stock trading using FinRL with financial dataTrained a Deep Reinforcement Learning model using FinRL and companies' financial ratio, and then backtested the model to examine how well-trained the model is* This Google Colabolatory notebook is based on the tutorial of FinRL: https://towardsdatascience.com/finrl-for-quantitative-finance-tutorial-for-multiple-stock-trading-7b00763b7530* This project is a final project of the almuni-mentored research project at Columbia University, Application of Reinforcement Learning to Finance, mentored by Bruce Yang from AI4Finance.* For more detailed explanation, please check out my Medium post: https://medium.com/@mariko.sawada1/automated-stock-trading-with-deep-reinforcement-learning-and-financial-data-a63286ccbe2b Content * [1. Problem Definition](0)* [2. Getting Started - Load Python packages](1) * [2.1. Install Packages](1.1) * [2.2. Check Additional Packages](1.2) * [2.3. Import Packages](1.3) * [2.4. Create Folders](1.4)* [3. Download Data](2)* [4. Preprocess fundamental Data](3) * [4-1 Import financial data](3.1) * [4-2 Specify items needed to calculate financial ratios](3.2) * [4-3 Calculate financial ratios](3.3) * [4-4 Deal with NAs and infinite values](3.4) * [4-5 Merge stock price data and ratios into one dataframe](3.5) * [4-6 Calculate market valuation ratios using daily stock price data](3.6)* [5.Build Environment](4) * [5.1. Training & Trade Data Split](4.1) * [5.2. User-defined Environment](4.2) * [5.3. Initialize Environment](4.3) * [6.Implement DRL Algorithms](5) * [7.Backtesting Performance](6) * [7.1. BackTestStats](6.1) * [7.2. BackTestPlot](6.2) * [7.3. Baseline Stats](6.3) * [7.3. Compare to Stock Market Index](6.4) Part 1. Problem Definition This problem is to design an automated trading solution for single stock trading. We model the stock trading process as a Markov Decision Process (MDP). We then formulate our trading goal as a maximization problem.The algorithm is trained using Deep Reinforcement Learning (DRL) algorithms and the components of the reinforcement learning environment are:* Action: The action space describes the allowed actions that the agent interacts with theenvironment. Normally, a ∈ A includes three actions: a ∈ {−1, 0, 1}, where −1, 0, 1 representselling, holding, and buying one stock. Also, an action can be carried upon multiple shares. We usean action space {−k, ..., −1, 0, 1, ..., k}, where k denotes the number of shares. For example, "Buy10 shares of AAPL" or "Sell 10 shares of AAPL" are 10 or −10, respectively* Reward function: r(s, a, s′) is the incentive mechanism for an agent to learn a better action. The change of the portfolio value when action a is taken at state s and arriving at new state s', i.e., r(s, a, s′) = v′ − v, where v′ and v represent the portfoliovalues at state s′ and s, respectively* State: The state space describes the observations that the agent receives from the environment. Just as a human trader needs to analyze various information before executing a trade, soour trading agent observes many different features to better learn in an interactive environment.* Environment: Dow 30 consituentsThe data of the single stock that we will be using for this case study is obtained from Yahoo Finance API. The data contains Open-High-Low-Close price and volume. Part 2. Load Python Packages 2.1. Install all the packages through FinRL library
###Code
## install finrl library
!pip install git+https://github.com/AI4Finance-LLC/FinRL-Library.git
###Output
Collecting git+https://github.com/AI4Finance-LLC/FinRL-Library.git
Cloning https://github.com/AI4Finance-LLC/FinRL-Library.git to /tmp/pip-req-build-sh40mnb8
Running command git clone -q https://github.com/AI4Finance-LLC/FinRL-Library.git /tmp/pip-req-build-sh40mnb8
Collecting pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2
Cloning https://github.com/quantopian/pyfolio.git to /tmp/pip-install-djvoe7ii/pyfolio_43f26b0cfe004ec394108e8d73166b45
Running command git clone -q https://github.com/quantopian/pyfolio.git /tmp/pip-install-djvoe7ii/pyfolio_43f26b0cfe004ec394108e8d73166b45
Requirement already satisfied: numpy>=1.17.3 in /usr/local/lib/python3.7/dist-packages (from finrl==0.3.0) (1.19.5)
Requirement already satisfied: pandas>=1.1.5 in /usr/local/lib/python3.7/dist-packages (from finrl==0.3.0) (1.1.5)
Requirement already satisfied: stockstats in /usr/local/lib/python3.7/dist-packages (from finrl==0.3.0) (0.3.2)
Requirement already satisfied: yfinance in /usr/local/lib/python3.7/dist-packages (from finrl==0.3.0) (0.1.63)
Requirement already satisfied: matplotlib in /usr/local/lib/python3.7/dist-packages (from finrl==0.3.0) (3.2.2)
Requirement already satisfied: scikit-learn>=0.21.0 in /usr/local/lib/python3.7/dist-packages (from finrl==0.3.0) (0.22.2.post1)
Requirement already satisfied: gym>=0.17 in /usr/local/lib/python3.7/dist-packages (from finrl==0.3.0) (0.17.3)
Requirement already satisfied: stable-baselines3[extra] in /usr/local/lib/python3.7/dist-packages (from finrl==0.3.0) (1.1.0)
Requirement already satisfied: pytest in /usr/local/lib/python3.7/dist-packages (from finrl==0.3.0) (3.6.4)
Requirement already satisfied: setuptools>=41.4.0 in /usr/local/lib/python3.7/dist-packages (from finrl==0.3.0) (57.4.0)
Requirement already satisfied: wheel>=0.33.6 in /usr/local/lib/python3.7/dist-packages (from finrl==0.3.0) (0.37.0)
Requirement already satisfied: ipython>=3.2.3 in /usr/local/lib/python3.7/dist-packages (from pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (5.5.0)
Requirement already satisfied: pytz>=2014.10 in /usr/local/lib/python3.7/dist-packages (from pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (2018.9)
Requirement already satisfied: scipy>=0.14.0 in /usr/local/lib/python3.7/dist-packages (from pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (1.4.1)
Requirement already satisfied: seaborn>=0.7.1 in /usr/local/lib/python3.7/dist-packages (from pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (0.11.1)
Requirement already satisfied: empyrical>=0.5.0 in /usr/local/lib/python3.7/dist-packages (from pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (0.5.5)
Requirement already satisfied: pandas-datareader>=0.2 in /usr/local/lib/python3.7/dist-packages (from empyrical>=0.5.0->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (0.9.0)
Requirement already satisfied: cloudpickle<1.7.0,>=1.2.0 in /usr/local/lib/python3.7/dist-packages (from gym>=0.17->finrl==0.3.0) (1.3.0)
Requirement already satisfied: pyglet<=1.5.0,>=1.4.0 in /usr/local/lib/python3.7/dist-packages (from gym>=0.17->finrl==0.3.0) (1.5.0)
Requirement already satisfied: decorator in /usr/local/lib/python3.7/dist-packages (from ipython>=3.2.3->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (4.4.2)
Requirement already satisfied: pexpect in /usr/local/lib/python3.7/dist-packages (from ipython>=3.2.3->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (4.8.0)
Requirement already satisfied: simplegeneric>0.8 in /usr/local/lib/python3.7/dist-packages (from ipython>=3.2.3->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (0.8.1)
Requirement already satisfied: prompt-toolkit<2.0.0,>=1.0.4 in /usr/local/lib/python3.7/dist-packages (from ipython>=3.2.3->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (1.0.18)
Requirement already satisfied: pygments in /usr/local/lib/python3.7/dist-packages (from ipython>=3.2.3->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (2.6.1)
Requirement already satisfied: traitlets>=4.2 in /usr/local/lib/python3.7/dist-packages (from ipython>=3.2.3->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (5.0.5)
Requirement already satisfied: pickleshare in /usr/local/lib/python3.7/dist-packages (from ipython>=3.2.3->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (0.7.5)
Requirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->finrl==0.3.0) (2.8.2)
Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->finrl==0.3.0) (1.3.1)
Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib->finrl==0.3.0) (0.10.0)
Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->finrl==0.3.0) (2.4.7)
Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from cycler>=0.10->matplotlib->finrl==0.3.0) (1.15.0)
Requirement already satisfied: requests>=2.19.0 in /usr/local/lib/python3.7/dist-packages (from pandas-datareader>=0.2->empyrical>=0.5.0->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (2.23.0)
Requirement already satisfied: lxml in /usr/local/lib/python3.7/dist-packages (from pandas-datareader>=0.2->empyrical>=0.5.0->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (4.6.3)
Requirement already satisfied: wcwidth in /usr/local/lib/python3.7/dist-packages (from prompt-toolkit<2.0.0,>=1.0.4->ipython>=3.2.3->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (0.2.5)
Requirement already satisfied: future in /usr/local/lib/python3.7/dist-packages (from pyglet<=1.5.0,>=1.4.0->gym>=0.17->finrl==0.3.0) (0.16.0)
Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19.0->pandas-datareader>=0.2->empyrical>=0.5.0->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (2.10)
Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19.0->pandas-datareader>=0.2->empyrical>=0.5.0->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (2021.5.30)
Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19.0->pandas-datareader>=0.2->empyrical>=0.5.0->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (1.24.3)
Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19.0->pandas-datareader>=0.2->empyrical>=0.5.0->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (3.0.4)
Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn>=0.21.0->finrl==0.3.0) (1.0.1)
Requirement already satisfied: ipython-genutils in /usr/local/lib/python3.7/dist-packages (from traitlets>=4.2->ipython>=3.2.3->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (0.2.0)
Requirement already satisfied: ptyprocess>=0.5 in /usr/local/lib/python3.7/dist-packages (from pexpect->ipython>=3.2.3->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (0.7.0)
Requirement already satisfied: more-itertools>=4.0.0 in /usr/local/lib/python3.7/dist-packages (from pytest->finrl==0.3.0) (8.8.0)
Requirement already satisfied: attrs>=17.4.0 in /usr/local/lib/python3.7/dist-packages (from pytest->finrl==0.3.0) (21.2.0)
Requirement already satisfied: atomicwrites>=1.0 in /usr/local/lib/python3.7/dist-packages (from pytest->finrl==0.3.0) (1.4.0)
Requirement already satisfied: py>=1.5.0 in /usr/local/lib/python3.7/dist-packages (from pytest->finrl==0.3.0) (1.10.0)
Requirement already satisfied: pluggy<0.8,>=0.5 in /usr/local/lib/python3.7/dist-packages (from pytest->finrl==0.3.0) (0.7.1)
Requirement already satisfied: torch>=1.4.0 in /usr/local/lib/python3.7/dist-packages (from stable-baselines3[extra]->finrl==0.3.0) (1.9.0+cu102)
Requirement already satisfied: pillow in /usr/local/lib/python3.7/dist-packages (from stable-baselines3[extra]->finrl==0.3.0) (7.1.2)
Requirement already satisfied: opencv-python in /usr/local/lib/python3.7/dist-packages (from stable-baselines3[extra]->finrl==0.3.0) (4.1.2.30)
Requirement already satisfied: atari-py~=0.2.0 in /usr/local/lib/python3.7/dist-packages (from stable-baselines3[extra]->finrl==0.3.0) (0.2.9)
Requirement already satisfied: psutil in /usr/local/lib/python3.7/dist-packages (from stable-baselines3[extra]->finrl==0.3.0) (5.4.8)
Requirement already satisfied: tensorboard>=2.2.0 in /usr/local/lib/python3.7/dist-packages (from stable-baselines3[extra]->finrl==0.3.0) (2.5.0)
Requirement already satisfied: protobuf>=3.6.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.0) (3.17.3)
Requirement already satisfied: grpcio>=1.24.3 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.0) (1.34.1)
Requirement already satisfied: werkzeug>=0.11.15 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.0) (1.0.1)
Requirement already satisfied: absl-py>=0.4 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.0) (0.12.0)
Requirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.0) (3.3.4)
Requirement already satisfied: tensorboard-data-server<0.7.0,>=0.6.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.0) (0.6.1)
Requirement already satisfied: google-auth<2,>=1.6.3 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.0) (1.34.0)
Requirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.0) (0.4.5)
Requirement already satisfied: tensorboard-plugin-wit>=1.6.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.0) (1.8.0)
Requirement already satisfied: rsa<5,>=3.1.4 in /usr/local/lib/python3.7/dist-packages (from google-auth<2,>=1.6.3->tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.0) (4.7.2)
Requirement already satisfied: cachetools<5.0,>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from google-auth<2,>=1.6.3->tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.0) (4.2.2)
Requirement already satisfied: pyasn1-modules>=0.2.1 in /usr/local/lib/python3.7/dist-packages (from google-auth<2,>=1.6.3->tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.0) (0.2.8)
Requirement already satisfied: requests-oauthlib>=0.7.0 in /usr/local/lib/python3.7/dist-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.0) (1.3.0)
Requirement already satisfied: importlib-metadata in /usr/local/lib/python3.7/dist-packages (from markdown>=2.6.8->tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.0) (4.6.3)
Requirement already satisfied: pyasn1<0.5.0,>=0.4.6 in /usr/local/lib/python3.7/dist-packages (from pyasn1-modules>=0.2.1->google-auth<2,>=1.6.3->tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.0) (0.4.8)
Requirement already satisfied: oauthlib>=3.0.0 in /usr/local/lib/python3.7/dist-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.0) (3.1.1)
Requirement already satisfied: typing-extensions in /usr/local/lib/python3.7/dist-packages (from torch>=1.4.0->stable-baselines3[extra]->finrl==0.3.0) (3.7.4.3)
Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata->markdown>=2.6.8->tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.0) (3.5.0)
Requirement already satisfied: int-date>=0.1.7 in /usr/local/lib/python3.7/dist-packages (from stockstats->finrl==0.3.0) (0.1.8)
Requirement already satisfied: multitasking>=0.0.7 in /usr/local/lib/python3.7/dist-packages (from yfinance->finrl==0.3.0) (0.0.9)
###Markdown
2.2. Check if the additional packages needed are present, if not install them. * Yahoo Finance API* pandas* numpy* matplotlib* stockstats* OpenAI gym* stable-baselines* tensorflow* pyfolio 2.3. Import Packages
###Code
import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
# matplotlib.use('Agg')
import datetime
%matplotlib inline
from finrl.apps import config
from finrl.finrl_meta.preprocessor.yahoodownloader import YahooDownloader
from finrl.finrl_meta.preprocessor.preprocessors import FeatureEngineer, data_split
from finrl.finrl_meta.env_stock_trading.env_stocktrading import StockTradingEnv
from finrl.drl_agents.stablebaselines3.models import DRLAgent
from finrl.plot import backtest_stats, backtest_plot, get_daily_return, get_baseline
from pprint import pprint
import sys
sys.path.append("../FinRL-Library")
import itertools
###Output
_____no_output_____
###Markdown
2.4. Create Folders
###Code
import os
if not os.path.exists("./" + config.DATA_SAVE_DIR):
os.makedirs("./" + config.DATA_SAVE_DIR)
if not os.path.exists("./" + config.TRAINED_MODEL_DIR):
os.makedirs("./" + config.TRAINED_MODEL_DIR)
if not os.path.exists("./" + config.TENSORBOARD_LOG_DIR):
os.makedirs("./" + config.TENSORBOARD_LOG_DIR)
if not os.path.exists("./" + config.RESULTS_DIR):
os.makedirs("./" + config.RESULTS_DIR)
###Output
_____no_output_____
###Markdown
Part 3. Download Stock Data from Yahoo FinanceYahoo Finance is a website that provides stock data, financial news, financial reports, etc. All the data provided by Yahoo Finance is free.* FinRL uses a class **YahooDownloader** to fetch data from Yahoo Finance API* Call Limit: Using the Public API (without authentication), you are limited to 2,000 requests per hour per IP (or up to a total of 48,000 requests a day). -----class YahooDownloader: Provides methods for retrieving daily stock data from Yahoo Finance API Attributes ---------- start_date : str start date of the data (modified from config.py) end_date : str end date of the data (modified from config.py) ticker_list : list a list of stock tickers (modified from config.py) Methods ------- fetch_data() Fetches data from yahoo API
###Code
# from config.py start_date is a string
config.START_DATE
# from config.py end_date is a string
config.END_DATE
print(config.DOW_30_TICKER)
df = YahooDownloader(start_date = '2009-01-01',
end_date = '2021-01-01',
ticker_list = config.DOW_30_TICKER).fetch_data()
df.shape
df.head()
df['date'] = pd.to_datetime(df['date'],format='%Y-%m-%d')
df.sort_values(['date','tic'],ignore_index=True).head()
###Output
_____no_output_____
###Markdown
Part 4: Preprocess fundamental data- Import finanical data downloaded from Compustat via WRDS(Wharton Research Data Service)- Preprocess the dataset and calculate financial ratios- Add those ratios to the price data preprocessed in Part 3- Calculate price-related ratios such as P/E and P/B 4-1 Import the financial data
###Code
# Import fundamental data from my GitHub repository
url = 'https://raw.githubusercontent.com/mariko-sawada/FinRL_with_fundamental_data/main/dow_30_fundamental_wrds.csv'
fund = pd.read_csv(url)
# Check the imported dataset
fund.head()
###Output
_____no_output_____
###Markdown
4-2 Specify items needed to calculate financial ratios- To know more about the data description of the dataset, please check WRDS's website(https://wrds-www.wharton.upenn.edu/). Login will be required.
###Code
# List items that are used to calculate financial ratios
items = [
'datadate', # Date
'tic', # Ticker
'oiadpq', # Quarterly operating income
'revtq', # Quartely revenue
'niq', # Quartely net income
'atq', # Total asset
'teqq', # Shareholder's equity
'epspiy', # EPS(Basic) incl. Extraordinary items
'ceqq', # Common Equity
'cshoq', # Common Shares Outstanding
'dvpspq', # Dividends per share
'actq', # Current assets
'lctq', # Current liabilities
'cheq', # Cash & Equivalent
'rectq', # Recievalbles
'cogsq', # Cost of Goods Sold
'invtq', # Inventories
'apq',# Account payable
'dlttq', # Long term debt
'dlcq', # Debt in current liabilites
'ltq' # Liabilities
]
# Omit items that will not be used
fund_data = fund[items]
# Rename column names for the sake of readability
fund_data = fund_data.rename(columns={
'datadate':'date', # Date
'oiadpq':'op_inc_q', # Quarterly operating income
'revtq':'rev_q', # Quartely revenue
'niq':'net_inc_q', # Quartely net income
'atq':'tot_assets', # Assets
'teqq':'sh_equity', # Shareholder's equity
'epspiy':'eps_incl_ex', # EPS(Basic) incl. Extraordinary items
'ceqq':'com_eq', # Common Equity
'cshoq':'sh_outstanding', # Common Shares Outstanding
'dvpspq':'div_per_sh', # Dividends per share
'actq':'cur_assets', # Current assets
'lctq':'cur_liabilities', # Current liabilities
'cheq':'cash_eq', # Cash & Equivalent
'rectq':'receivables', # Receivalbles
'cogsq':'cogs_q', # Cost of Goods Sold
'invtq':'inventories', # Inventories
'apq': 'payables',# Account payable
'dlttq':'long_debt', # Long term debt
'dlcq':'short_debt', # Debt in current liabilites
'ltq':'tot_liabilities' # Liabilities
})
# Check the data
fund_data.head()
###Output
_____no_output_____
###Markdown
4-3 Calculate financial ratios- For items from Profit/Loss statements, we calculate LTM (Last Twelve Months) and use them to derive profitability related ratios such as Operating Maring and ROE. For items from balance sheets, we use the numbers on the day.- To check the definitions of the financial ratios calculated here, please refer to CFI's website: https://corporatefinanceinstitute.com/resources/knowledge/finance/financial-ratios/
###Code
# Calculate financial ratios
date = pd.to_datetime(fund_data['date'],format='%Y%m%d')
tic = fund_data['tic'].to_frame('tic')
# Profitability ratios
# Operating Margin
OPM = pd.Series(np.empty(fund_data.shape[0],dtype=object),name='OPM')
for i in range(0, fund_data.shape[0]):
if i-3 < 0:
OPM[i] = np.nan
elif fund_data.iloc[i,1] != fund_data.iloc[i-3,1]:
OPM.iloc[i] = np.nan
else:
OPM.iloc[i] = np.sum(fund_data['op_inc_q'].iloc[i-3:i])/np.sum(fund_data['rev_q'].iloc[i-3:i])
# Net Profit Margin
NPM = pd.Series(np.empty(fund_data.shape[0],dtype=object),name='NPM')
for i in range(0, fund_data.shape[0]):
if i-3 < 0:
NPM[i] = np.nan
elif fund_data.iloc[i,1] != fund_data.iloc[i-3,1]:
NPM.iloc[i] = np.nan
else:
NPM.iloc[i] = np.sum(fund_data['net_inc_q'].iloc[i-3:i])/np.sum(fund_data['rev_q'].iloc[i-3:i])
# Return On Assets
ROA = pd.Series(np.empty(fund_data.shape[0],dtype=object),name='ROA')
for i in range(0, fund_data.shape[0]):
if i-3 < 0:
ROA[i] = np.nan
elif fund_data.iloc[i,1] != fund_data.iloc[i-3,1]:
ROA.iloc[i] = np.nan
else:
ROA.iloc[i] = np.sum(fund_data['net_inc_q'].iloc[i-3:i])/fund_data['tot_assets'].iloc[i]
# Return on Equity
ROE = pd.Series(np.empty(fund_data.shape[0],dtype=object),name='ROE')
for i in range(0, fund_data.shape[0]):
if i-3 < 0:
ROE[i] = np.nan
elif fund_data.iloc[i,1] != fund_data.iloc[i-3,1]:
ROE.iloc[i] = np.nan
else:
ROE.iloc[i] = np.sum(fund_data['net_inc_q'].iloc[i-3:i])/fund_data['sh_equity'].iloc[i]
# For calculating valuation ratios in the next subpart, calculate per share items in advance
# Earnings Per Share
EPS = fund_data['eps_incl_ex'].to_frame('EPS')
# Book Per Share
BPS = (fund_data['com_eq']/fund_data['sh_outstanding']).to_frame('BPS') # Need to check units
#Dividend Per Share
DPS = fund_data['div_per_sh'].to_frame('DPS')
# Liquidity ratios
# Current ratio
cur_ratio = (fund_data['cur_assets']/fund_data['cur_liabilities']).to_frame('cur_ratio')
# Quick ratio
quick_ratio = ((fund_data['cash_eq'] + fund_data['receivables'] )/fund_data['cur_liabilities']).to_frame('quick_ratio')
# Cash ratio
cash_ratio = (fund_data['cash_eq']/fund_data['cur_liabilities']).to_frame('cash_ratio')
# Efficiency ratios
# Inventory turnover ratio
inv_turnover = pd.Series(np.empty(fund_data.shape[0],dtype=object),name='inv_turnover')
for i in range(0, fund_data.shape[0]):
if i-3 < 0:
inv_turnover[i] = np.nan
elif fund_data.iloc[i,1] != fund_data.iloc[i-3,1]:
inv_turnover.iloc[i] = np.nan
else:
inv_turnover.iloc[i] = np.sum(fund_data['cogs_q'].iloc[i-3:i])/fund_data['inventories'].iloc[i]
# Receivables turnover ratio
acc_rec_turnover = pd.Series(np.empty(fund_data.shape[0],dtype=object),name='acc_rec_turnover')
for i in range(0, fund_data.shape[0]):
if i-3 < 0:
acc_rec_turnover[i] = np.nan
elif fund_data.iloc[i,1] != fund_data.iloc[i-3,1]:
acc_rec_turnover.iloc[i] = np.nan
else:
acc_rec_turnover.iloc[i] = np.sum(fund_data['rev_q'].iloc[i-3:i])/fund_data['receivables'].iloc[i]
# Payable turnover ratio
acc_pay_turnover = pd.Series(np.empty(fund_data.shape[0],dtype=object),name='acc_pay_turnover')
for i in range(0, fund_data.shape[0]):
if i-3 < 0:
acc_pay_turnover[i] = np.nan
elif fund_data.iloc[i,1] != fund_data.iloc[i-3,1]:
acc_pay_turnover.iloc[i] = np.nan
else:
acc_pay_turnover.iloc[i] = np.sum(fund_data['cogs_q'].iloc[i-3:i])/fund_data['payables'].iloc[i]
## Leverage financial ratios
# Debt ratio
debt_ratio = (fund_data['tot_liabilities']/fund_data['tot_assets']).to_frame('debt_ratio')
# Debt to Equity ratio
debt_to_equity = (fund_data['tot_liabilities']/fund_data['sh_equity']).to_frame('debt_to_equity')
# Create a dataframe that merges all the ratios
ratios = pd.concat([date,tic,OPM,NPM,ROA,ROE,EPS,BPS,DPS,
cur_ratio,quick_ratio,cash_ratio,inv_turnover,acc_rec_turnover,acc_pay_turnover,
debt_ratio,debt_to_equity], axis=1)
# Check the ratio data
ratios.head()
ratios.tail()
###Output
_____no_output_____
###Markdown
4-4 Deal with NAs and infinite values- We replace N/A and infinite values with zero so that they can be recognized as a state
###Code
# Replace NAs infinite values with zero
final_ratios = ratios.copy()
final_ratios = final_ratios.fillna(0)
final_ratios = final_ratios.replace(np.inf,0)
final_ratios.head()
final_ratios.tail()
###Output
_____no_output_____
###Markdown
4-5 Merge stock price data and ratios into one dataframe- Merge the price dataframe preprocessed in Part 3 and the ratio dataframe created in this part- Since the prices are daily and ratios are quartely, we have NAs in the ratio columns after merging the two dataframes. We deal with this by backfilling the ratios.
###Code
list_ticker = df["tic"].unique().tolist()
list_date = list(pd.date_range(df['date'].min(),df['date'].max()))
combination = list(itertools.product(list_date,list_ticker))
# Merge stock price data and ratios into one dataframe
processed_full = pd.DataFrame(combination,columns=["date","tic"]).merge(df,on=["date","tic"],how="left")
processed_full = processed_full.merge(final_ratios,how='left',on=['date','tic'])
processed_full = processed_full.sort_values(['tic','date'])
# Backfill the ratio data to make them daily
processed_full = processed_full.bfill(axis='rows')
###Output
_____no_output_____
###Markdown
4-6 Calculate market valuation ratios using daily stock price data
###Code
# Calculate P/E, P/B and dividend yield using daily closing price
processed_full['PE'] = processed_full['close']/processed_full['EPS']
processed_full['PB'] = processed_full['close']/processed_full['BPS']
processed_full['Div_yield'] = processed_full['DPS']/processed_full['close']
# Drop per share items used for the above calculation
processed_full = processed_full.drop(columns=['day','EPS','BPS','DPS'])
# Check the final data
processed_full.sort_values(['date','tic'],ignore_index=True).head(10)
###Output
_____no_output_____
###Markdown
Part 5. Design EnvironmentConsidering the stochastic and interactive nature of the automated stock trading tasks, a financial task is modeled as a **Markov Decision Process (MDP)** problem. The training process involves observing stock price change, taking an action and reward's calculation to have the agent adjusting its strategy accordingly. By interacting with the environment, the trading agent will derive a trading strategy with the maximized rewards as time proceeds.Our trading environments, based on OpenAI Gym framework, simulate live stock markets with real market data according to the principle of time-driven simulation.The action space describes the allowed actions that the agent interacts with the environment. Normally, action a includes three actions: {-1, 0, 1}, where -1, 0, 1 represent selling, holding, and buying one share. Also, an action can be carried upon multiple shares. We use an action space {-k,…,-1, 0, 1, …, k}, where k denotes the number of shares to buy and -k denotes the number of shares to sell. For example, "Buy 10 shares of AAPL" or "Sell 10 shares of AAPL" are 10 or -10, respectively. The continuous action space needs to be normalized to [-1, 1], since the policy is defined on a Gaussian distribution, which needs to be normalized and symmetric. 5-1 Split data into training and trade dataset- Training data split: 2009-01-01 to 2018-12-31- Trade data split: 2019-01-01 to 2020-09-30
###Code
train = data_split(processed_full, '2009-01-01','2019-01-01')
trade = data_split(processed_full, '2019-01-01','2021-01-01')
# Check the length of the two datasets
print(len(train))
print(len(trade))
train.head()
trade.head()
###Output
_____no_output_____
###Markdown
5-2 Set up the training environment
###Code
ratio_list = ['OPM', 'NPM','ROA', 'ROE', 'cur_ratio', 'quick_ratio', 'cash_ratio', 'inv_turnover','acc_rec_turnover', 'acc_pay_turnover', 'debt_ratio', 'debt_to_equity',
'PE', 'PB', 'Div_yield']
stock_dimension = len(train.tic.unique())
state_space = 1 + 2*stock_dimension + len(ratio_list)*stock_dimension
print(f"Stock Dimension: {stock_dimension}, State Space: {state_space}")
# Parameters for the environment
env_kwargs = {
"hmax": 100,
"initial_amount": 1000000,
"buy_cost_pct": 0.001,
"sell_cost_pct": 0.001,
"state_space": state_space,
"stock_dim": stock_dimension,
"tech_indicator_list": ratio_list,
"action_space": stock_dimension,
"reward_scaling": 1e-4
}
#Establish the training environment using StockTradingEnv() class
e_train_gym = StockTradingEnv(df = train, **env_kwargs)
###Output
_____no_output_____
###Markdown
Environment for Training
###Code
env_train, _ = e_train_gym.get_sb_env()
print(type(env_train))
###Output
<class 'stable_baselines3.common.vec_env.dummy_vec_env.DummyVecEnv'>
###Markdown
Part 6: Implement DRL Algorithms* The implementation of the DRL algorithms are based on **OpenAI Baselines** and **Stable Baselines**. Stable Baselines is a fork of OpenAI Baselines, with a major structural refactoring, and code cleanups.* FinRL library includes fine-tuned standard DRL algorithms, such as DQN, DDPG,Multi-Agent DDPG, PPO, SAC, A2C and TD3. We also allow users todesign their own DRL algorithms by adapting these DRL algorithms.
###Code
# Set up the agent using DRLAgent() class using the environment created in the previous part
agent = DRLAgent(env = env_train)
###Output
_____no_output_____
###Markdown
Model Training: 5 models, A2C DDPG, PPO, TD3, SAC Model 1: A2C
###Code
agent = DRLAgent(env = env_train)
model_a2c = agent.get_model("a2c")
trained_a2c = agent.train_model(model=model_a2c,
tb_log_name='a2c',
total_timesteps=100000)
###Output
Logging to tensorboard_log/a2c/a2c_1
------------------------------------
| time/ | |
| fps | 60 |
| iterations | 100 |
| time_elapsed | 8 |
| total_timesteps | 500 |
| train/ | |
| entropy_loss | -42.9 |
| explained_variance | 0.157 |
| learning_rate | 0.0007 |
| n_updates | 99 |
| policy_loss | 165 |
| std | 1.01 |
| value_loss | 18.3 |
------------------------------------
------------------------------------
| time/ | |
| fps | 68 |
| iterations | 200 |
| time_elapsed | 14 |
| total_timesteps | 1000 |
| train/ | |
| entropy_loss | -43 |
| explained_variance | 0.0513 |
| learning_rate | 0.0007 |
| n_updates | 199 |
| policy_loss | 51.6 |
| std | 1.01 |
| value_loss | 17.2 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 71 |
| iterations | 300 |
| time_elapsed | 20 |
| total_timesteps | 1500 |
| train/ | |
| entropy_loss | -42.9 |
| explained_variance | -1.19e-06 |
| learning_rate | 0.0007 |
| n_updates | 299 |
| policy_loss | -1.03 |
| std | 1.01 |
| value_loss | 0.541 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 73 |
| iterations | 400 |
| time_elapsed | 27 |
| total_timesteps | 2000 |
| train/ | |
| entropy_loss | -43 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 399 |
| policy_loss | 103 |
| std | 1.01 |
| value_loss | 5.78 |
------------------------------------
------------------------------------
| time/ | |
| fps | 74 |
| iterations | 500 |
| time_elapsed | 33 |
| total_timesteps | 2500 |
| train/ | |
| entropy_loss | -43.1 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 499 |
| policy_loss | 158 |
| std | 1.02 |
| value_loss | 23.9 |
------------------------------------
------------------------------------
| time/ | |
| fps | 74 |
| iterations | 600 |
| time_elapsed | 40 |
| total_timesteps | 3000 |
| train/ | |
| entropy_loss | -43.1 |
| explained_variance | 5.96e-08 |
| learning_rate | 0.0007 |
| n_updates | 599 |
| policy_loss | 62.7 |
| std | 1.02 |
| value_loss | 2.76 |
------------------------------------
------------------------------------
| time/ | |
| fps | 75 |
| iterations | 700 |
| time_elapsed | 46 |
| total_timesteps | 3500 |
| train/ | |
| entropy_loss | -43.1 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 699 |
| policy_loss | -136 |
| std | 1.02 |
| value_loss | 17.3 |
------------------------------------
------------------------------------
| environment/ | |
| portfolio_value | 1.91e+06 |
| total_cost | 7.56e+04 |
| total_reward | 9.14e+05 |
| total_reward_pct | 91.4 |
| total_trades | 73316 |
| time/ | |
| fps | 75 |
| iterations | 800 |
| time_elapsed | 52 |
| total_timesteps | 4000 |
| train/ | |
| entropy_loss | -43.1 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 799 |
| policy_loss | -50.6 |
| std | 1.02 |
| value_loss | 1.55 |
------------------------------------
------------------------------------
| time/ | |
| fps | 75 |
| iterations | 900 |
| time_elapsed | 59 |
| total_timesteps | 4500 |
| train/ | |
| entropy_loss | -43.2 |
| explained_variance | 1.79e-07 |
| learning_rate | 0.0007 |
| n_updates | 899 |
| policy_loss | 76.5 |
| std | 1.02 |
| value_loss | 2.69 |
------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 1000 |
| time_elapsed | 65 |
| total_timesteps | 5000 |
| train/ | |
| entropy_loss | -43.2 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 999 |
| policy_loss | 175 |
| std | 1.02 |
| value_loss | 17.4 |
------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 1100 |
| time_elapsed | 72 |
| total_timesteps | 5500 |
| train/ | |
| entropy_loss | -43.2 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 1099 |
| policy_loss | -14.7 |
| std | 1.02 |
| value_loss | 0.158 |
------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 1200 |
| time_elapsed | 78 |
| total_timesteps | 6000 |
| train/ | |
| entropy_loss | -43.2 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 1199 |
| policy_loss | -84.2 |
| std | 1.02 |
| value_loss | 3.71 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 76 |
| iterations | 1300 |
| time_elapsed | 84 |
| total_timesteps | 6500 |
| train/ | |
| entropy_loss | -43.3 |
| explained_variance | -4.77e-07 |
| learning_rate | 0.0007 |
| n_updates | 1299 |
| policy_loss | -63.5 |
| std | 1.02 |
| value_loss | 3.31 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 1400 |
| time_elapsed | 91 |
| total_timesteps | 7000 |
| train/ | |
| entropy_loss | -43.3 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 1399 |
| policy_loss | -309 |
| std | 1.03 |
| value_loss | 60.1 |
------------------------------------
------------------------------------
| environment/ | |
| portfolio_value | 2.29e+06 |
| total_cost | 2.63e+04 |
| total_reward | 1.29e+06 |
| total_reward_pct | 129 |
| total_trades | 60684 |
| time/ | |
| fps | 76 |
| iterations | 1500 |
| time_elapsed | 97 |
| total_timesteps | 7500 |
| train/ | |
| entropy_loss | -43.4 |
| explained_variance | -0.33 |
| learning_rate | 0.0007 |
| n_updates | 1499 |
| policy_loss | 61.1 |
| std | 1.03 |
| value_loss | 3.06 |
------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 1600 |
| time_elapsed | 103 |
| total_timesteps | 8000 |
| train/ | |
| entropy_loss | -43.5 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 1599 |
| policy_loss | -19.4 |
| std | 1.03 |
| value_loss | 0.955 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 77 |
| iterations | 1700 |
| time_elapsed | 110 |
| total_timesteps | 8500 |
| train/ | |
| entropy_loss | -43.5 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 1699 |
| policy_loss | -50.8 |
| std | 1.03 |
| value_loss | 2.76 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 1800 |
| time_elapsed | 116 |
| total_timesteps | 9000 |
| train/ | |
| entropy_loss | -43.5 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 1799 |
| policy_loss | 19.4 |
| std | 1.03 |
| value_loss | 0.647 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 1900 |
| time_elapsed | 123 |
| total_timesteps | 9500 |
| train/ | |
| entropy_loss | -43.5 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 1899 |
| policy_loss | -187 |
| std | 1.03 |
| value_loss | 22.8 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 77 |
| iterations | 2000 |
| time_elapsed | 129 |
| total_timesteps | 10000 |
| train/ | |
| entropy_loss | -43.5 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 1999 |
| policy_loss | -71.4 |
| std | 1.03 |
| value_loss | 4.75 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 2100 |
| time_elapsed | 135 |
| total_timesteps | 10500 |
| train/ | |
| entropy_loss | -43.5 |
| explained_variance | 5.96e-08 |
| learning_rate | 0.0007 |
| n_updates | 2099 |
| policy_loss | 73.2 |
| std | 1.03 |
| value_loss | 4.46 |
------------------------------------
------------------------------------
| environment/ | |
| portfolio_value | 4.38e+06 |
| total_cost | 3.17e+04 |
| total_reward | 3.38e+06 |
| total_reward_pct | 338 |
| total_trades | 65214 |
| time/ | |
| fps | 77 |
| iterations | 2200 |
| time_elapsed | 142 |
| total_timesteps | 11000 |
| train/ | |
| entropy_loss | -43.7 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 2199 |
| policy_loss | -37.4 |
| std | 1.04 |
| value_loss | 1.05 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 2300 |
| time_elapsed | 148 |
| total_timesteps | 11500 |
| train/ | |
| entropy_loss | -43.7 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 2299 |
| policy_loss | -52.1 |
| std | 1.04 |
| value_loss | 2.56 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 2400 |
| time_elapsed | 155 |
| total_timesteps | 12000 |
| train/ | |
| entropy_loss | -43.7 |
| explained_variance | 5.96e-08 |
| learning_rate | 0.0007 |
| n_updates | 2399 |
| policy_loss | -91.9 |
| std | 1.04 |
| value_loss | 6.52 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 2500 |
| time_elapsed | 161 |
| total_timesteps | 12500 |
| train/ | |
| entropy_loss | -43.7 |
| explained_variance | 1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 2499 |
| policy_loss | 19.6 |
| std | 1.04 |
| value_loss | 0.766 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 2600 |
| time_elapsed | 167 |
| total_timesteps | 13000 |
| train/ | |
| entropy_loss | -43.7 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 2599 |
| policy_loss | -58.4 |
| std | 1.04 |
| value_loss | 2.59 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 2700 |
| time_elapsed | 174 |
| total_timesteps | 13500 |
| train/ | |
| entropy_loss | -43.8 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 2699 |
| policy_loss | -177 |
| std | 1.04 |
| value_loss | 24.6 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 2800 |
| time_elapsed | 180 |
| total_timesteps | 14000 |
| train/ | |
| entropy_loss | -43.8 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 2799 |
| policy_loss | 54.1 |
| std | 1.04 |
| value_loss | 1.96 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 2900 |
| time_elapsed | 187 |
| total_timesteps | 14500 |
| train/ | |
| entropy_loss | -43.8 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 2899 |
| policy_loss | 127 |
| std | 1.04 |
| value_loss | 15.7 |
------------------------------------
------------------------------------
| environment/ | |
| portfolio_value | 2.92e+06 |
| total_cost | 1.85e+04 |
| total_reward | 1.92e+06 |
| total_reward_pct | 192 |
| total_trades | 67453 |
| time/ | |
| fps | 77 |
| iterations | 3000 |
| time_elapsed | 193 |
| total_timesteps | 15000 |
| train/ | |
| entropy_loss | -43.8 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 2999 |
| policy_loss | -97.9 |
| std | 1.04 |
| value_loss | 5.52 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 3100 |
| time_elapsed | 199 |
| total_timesteps | 15500 |
| train/ | |
| entropy_loss | -43.9 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 3099 |
| policy_loss | -87.5 |
| std | 1.05 |
| value_loss | 4.94 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 3200 |
| time_elapsed | 206 |
| total_timesteps | 16000 |
| train/ | |
| entropy_loss | -44 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 3199 |
| policy_loss | -199 |
| std | 1.05 |
| value_loss | 21.3 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 77 |
| iterations | 3300 |
| time_elapsed | 212 |
| total_timesteps | 16500 |
| train/ | |
| entropy_loss | -44 |
| explained_variance | -3.58e-07 |
| learning_rate | 0.0007 |
| n_updates | 3299 |
| policy_loss | 59.4 |
| std | 1.05 |
| value_loss | 4.14 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 3400 |
| time_elapsed | 219 |
| total_timesteps | 17000 |
| train/ | |
| entropy_loss | -44 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 3399 |
| policy_loss | -32.7 |
| std | 1.05 |
| value_loss | 1.65 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 3500 |
| time_elapsed | 225 |
| total_timesteps | 17500 |
| train/ | |
| entropy_loss | -44 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 3499 |
| policy_loss | -85.8 |
| std | 1.05 |
| value_loss | 4.92 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 77 |
| iterations | 3600 |
| time_elapsed | 231 |
| total_timesteps | 18000 |
| train/ | |
| entropy_loss | -44 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 3599 |
| policy_loss | 118 |
| std | 1.05 |
| value_loss | 14.3 |
-------------------------------------
------------------------------------
| environment/ | |
| portfolio_value | 3.75e+06 |
| total_cost | 2.33e+04 |
| total_reward | 2.75e+06 |
| total_reward_pct | 275 |
| total_trades | 65849 |
| time/ | |
| fps | 77 |
| iterations | 3700 |
| time_elapsed | 238 |
| total_timesteps | 18500 |
| train/ | |
| entropy_loss | -43.9 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 3699 |
| policy_loss | -44.2 |
| std | 1.05 |
| value_loss | 1.43 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 77 |
| iterations | 3800 |
| time_elapsed | 244 |
| total_timesteps | 19000 |
| train/ | |
| entropy_loss | -43.9 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 3799 |
| policy_loss | 59.3 |
| std | 1.05 |
| value_loss | 1.79 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 3900 |
| time_elapsed | 251 |
| total_timesteps | 19500 |
| train/ | |
| entropy_loss | -43.9 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 3899 |
| policy_loss | 82.2 |
| std | 1.05 |
| value_loss | 3.91 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 4000 |
| time_elapsed | 257 |
| total_timesteps | 20000 |
| train/ | |
| entropy_loss | -43.9 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 3999 |
| policy_loss | -153 |
| std | 1.05 |
| value_loss | 13.7 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 4100 |
| time_elapsed | 263 |
| total_timesteps | 20500 |
| train/ | |
| entropy_loss | -44 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 4099 |
| policy_loss | 88 |
| std | 1.05 |
| value_loss | 4.7 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 4200 |
| time_elapsed | 270 |
| total_timesteps | 21000 |
| train/ | |
| entropy_loss | -44 |
| explained_variance | -0.0553 |
| learning_rate | 0.0007 |
| n_updates | 4199 |
| policy_loss | -65 |
| std | 1.05 |
| value_loss | 5.44 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 4300 |
| time_elapsed | 276 |
| total_timesteps | 21500 |
| train/ | |
| entropy_loss | -44 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 4299 |
| policy_loss | -55.7 |
| std | 1.05 |
| value_loss | 2.66 |
------------------------------------
------------------------------------
| environment/ | |
| portfolio_value | 3.83e+06 |
| total_cost | 8.83e+04 |
| total_reward | 2.83e+06 |
| total_reward_pct | 283 |
| total_trades | 71634 |
| time/ | |
| fps | 77 |
| iterations | 4400 |
| time_elapsed | 283 |
| total_timesteps | 22000 |
| train/ | |
| entropy_loss | -44 |
| explained_variance | -0.0125 |
| learning_rate | 0.0007 |
| n_updates | 4399 |
| policy_loss | 94.9 |
| std | 1.05 |
| value_loss | 5.92 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 4500 |
| time_elapsed | 289 |
| total_timesteps | 22500 |
| train/ | |
| entropy_loss | -44 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 4499 |
| policy_loss | -95.7 |
| std | 1.05 |
| value_loss | 6.98 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 4600 |
| time_elapsed | 296 |
| total_timesteps | 23000 |
| train/ | |
| entropy_loss | -44 |
| explained_variance | 1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 4599 |
| policy_loss | 0.903 |
| std | 1.05 |
| value_loss | 0.28 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 4700 |
| time_elapsed | 302 |
| total_timesteps | 23500 |
| train/ | |
| entropy_loss | -44 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 4699 |
| policy_loss | -79.2 |
| std | 1.05 |
| value_loss | 2.97 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 4800 |
| time_elapsed | 308 |
| total_timesteps | 24000 |
| train/ | |
| entropy_loss | -44 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 4799 |
| policy_loss | -23.5 |
| std | 1.05 |
| value_loss | 0.842 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 4900 |
| time_elapsed | 315 |
| total_timesteps | 24500 |
| train/ | |
| entropy_loss | -44 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 4899 |
| policy_loss | 54.6 |
| std | 1.05 |
| value_loss | 7.28 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 5000 |
| time_elapsed | 321 |
| total_timesteps | 25000 |
| train/ | |
| entropy_loss | -44.2 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 4999 |
| policy_loss | 34.9 |
| std | 1.06 |
| value_loss | 1.99 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 5100 |
| time_elapsed | 327 |
| total_timesteps | 25500 |
| train/ | |
| entropy_loss | -44.1 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 5099 |
| policy_loss | 352 |
| std | 1.05 |
| value_loss | 72.6 |
------------------------------------
------------------------------------
| environment/ | |
| portfolio_value | 3.24e+06 |
| total_cost | 1.66e+04 |
| total_reward | 2.24e+06 |
| total_reward_pct | 224 |
| total_trades | 61666 |
| time/ | |
| fps | 77 |
| iterations | 5200 |
| time_elapsed | 334 |
| total_timesteps | 26000 |
| train/ | |
| entropy_loss | -44.1 |
| explained_variance | 1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 5199 |
| policy_loss | 2.88 |
| std | 1.06 |
| value_loss | 0.137 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 5300 |
| time_elapsed | 340 |
| total_timesteps | 26500 |
| train/ | |
| entropy_loss | -44.2 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 5299 |
| policy_loss | -222 |
| std | 1.06 |
| value_loss | 30.4 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 5400 |
| time_elapsed | 347 |
| total_timesteps | 27000 |
| train/ | |
| entropy_loss | -44.2 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 5399 |
| policy_loss | -11.7 |
| std | 1.06 |
| value_loss | 0.156 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 5500 |
| time_elapsed | 353 |
| total_timesteps | 27500 |
| train/ | |
| entropy_loss | -44.2 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 5499 |
| policy_loss | 165 |
| std | 1.06 |
| value_loss | 13.7 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 5600 |
| time_elapsed | 359 |
| total_timesteps | 28000 |
| train/ | |
| entropy_loss | -44.2 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 5599 |
| policy_loss | 127 |
| std | 1.06 |
| value_loss | 15.9 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 77 |
| iterations | 5700 |
| time_elapsed | 366 |
| total_timesteps | 28500 |
| train/ | |
| entropy_loss | -44.2 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 5699 |
| policy_loss | 26.7 |
| std | 1.06 |
| value_loss | 0.48 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 5800 |
| time_elapsed | 372 |
| total_timesteps | 29000 |
| train/ | |
| entropy_loss | -44.2 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 5799 |
| policy_loss | 242 |
| std | 1.06 |
| value_loss | 37 |
------------------------------------
------------------------------------
| environment/ | |
| portfolio_value | 3.16e+06 |
| total_cost | 1.22e+04 |
| total_reward | 2.16e+06 |
| total_reward_pct | 216 |
| total_trades | 60801 |
| time/ | |
| fps | 77 |
| iterations | 5900 |
| time_elapsed | 379 |
| total_timesteps | 29500 |
| train/ | |
| entropy_loss | -44.2 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 5899 |
| policy_loss | 72.7 |
| std | 1.06 |
| value_loss | 4.37 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 6000 |
| time_elapsed | 385 |
| total_timesteps | 30000 |
| train/ | |
| entropy_loss | -44.2 |
| explained_variance | 1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 5999 |
| policy_loss | 58 |
| std | 1.06 |
| value_loss | 4.2 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 6100 |
| time_elapsed | 392 |
| total_timesteps | 30500 |
| train/ | |
| entropy_loss | -44.2 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 6099 |
| policy_loss | -132 |
| std | 1.06 |
| value_loss | 9.64 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 6200 |
| time_elapsed | 398 |
| total_timesteps | 31000 |
| train/ | |
| entropy_loss | -44.2 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 6199 |
| policy_loss | 25.9 |
| std | 1.06 |
| value_loss | 1.75 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 77 |
| iterations | 6300 |
| time_elapsed | 404 |
| total_timesteps | 31500 |
| train/ | |
| entropy_loss | -44.2 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 6299 |
| policy_loss | -84.4 |
| std | 1.06 |
| value_loss | 5.68 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 6400 |
| time_elapsed | 411 |
| total_timesteps | 32000 |
| train/ | |
| entropy_loss | -44.2 |
| explained_variance | 1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 6399 |
| policy_loss | -74.6 |
| std | 1.06 |
| value_loss | 3.73 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 6500 |
| time_elapsed | 417 |
| total_timesteps | 32500 |
| train/ | |
| entropy_loss | -44.2 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 6499 |
| policy_loss | 120 |
| std | 1.06 |
| value_loss | 21.8 |
------------------------------------
day: 3650, episode: 10
begin_total_asset: 1000000.00
end_total_asset: 4297821.94
total_reward: 3297821.94
total_cost: 12437.82
total_trades: 58594
Sharpe: 0.695
=================================
------------------------------------
| environment/ | |
| portfolio_value | 4.3e+06 |
| total_cost | 1.24e+04 |
| total_reward | 3.3e+06 |
| total_reward_pct | 330 |
| total_trades | 58594 |
| time/ | |
| fps | 77 |
| iterations | 6600 |
| time_elapsed | 424 |
| total_timesteps | 33000 |
| train/ | |
| entropy_loss | -44.2 |
| explained_variance | -0.112 |
| learning_rate | 0.0007 |
| n_updates | 6599 |
| policy_loss | 63.4 |
| std | 1.06 |
| value_loss | 4.21 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 6700 |
| time_elapsed | 430 |
| total_timesteps | 33500 |
| train/ | |
| entropy_loss | -44.2 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 6699 |
| policy_loss | 31.2 |
| std | 1.06 |
| value_loss | 3.92 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 77 |
| iterations | 6800 |
| time_elapsed | 437 |
| total_timesteps | 34000 |
| train/ | |
| entropy_loss | -44.3 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 6799 |
| policy_loss | 141 |
| std | 1.06 |
| value_loss | 16.5 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 6900 |
| time_elapsed | 443 |
| total_timesteps | 34500 |
| train/ | |
| entropy_loss | -44.3 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 6899 |
| policy_loss | -198 |
| std | 1.06 |
| value_loss | 23.1 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 7000 |
| time_elapsed | 450 |
| total_timesteps | 35000 |
| train/ | |
| entropy_loss | -44.3 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 6999 |
| policy_loss | 132 |
| std | 1.06 |
| value_loss | 12.7 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 7100 |
| time_elapsed | 456 |
| total_timesteps | 35500 |
| train/ | |
| entropy_loss | -44.2 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 7099 |
| policy_loss | -99.9 |
| std | 1.06 |
| value_loss | 5.45 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 77 |
| iterations | 7200 |
| time_elapsed | 462 |
| total_timesteps | 36000 |
| train/ | |
| entropy_loss | -44.2 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 7199 |
| policy_loss | 210 |
| std | 1.06 |
| value_loss | 32.8 |
-------------------------------------
-------------------------------------
| time/ | |
| fps | 77 |
| iterations | 7300 |
| time_elapsed | 469 |
| total_timesteps | 36500 |
| train/ | |
| entropy_loss | -44.2 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 7299 |
| policy_loss | -476 |
| std | 1.06 |
| value_loss | 271 |
-------------------------------------
------------------------------------
| environment/ | |
| portfolio_value | 4.94e+06 |
| total_cost | 8.73e+03 |
| total_reward | 3.94e+06 |
| total_reward_pct | 394 |
| total_trades | 58374 |
| time/ | |
| fps | 77 |
| iterations | 7400 |
| time_elapsed | 475 |
| total_timesteps | 37000 |
| train/ | |
| entropy_loss | -44.2 |
| explained_variance | 5.96e-08 |
| learning_rate | 0.0007 |
| n_updates | 7399 |
| policy_loss | 42.2 |
| std | 1.06 |
| value_loss | 2.51 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 7500 |
| time_elapsed | 482 |
| total_timesteps | 37500 |
| train/ | |
| entropy_loss | -44.1 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 7499 |
| policy_loss | 140 |
| std | 1.06 |
| value_loss | 10.6 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 7600 |
| time_elapsed | 488 |
| total_timesteps | 38000 |
| train/ | |
| entropy_loss | -44.2 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 7599 |
| policy_loss | -201 |
| std | 1.06 |
| value_loss | 45.9 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 7700 |
| time_elapsed | 495 |
| total_timesteps | 38500 |
| train/ | |
| entropy_loss | -44.2 |
| explained_variance | 5.96e-08 |
| learning_rate | 0.0007 |
| n_updates | 7699 |
| policy_loss | 28.5 |
| std | 1.06 |
| value_loss | 1.14 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 7800 |
| time_elapsed | 501 |
| total_timesteps | 39000 |
| train/ | |
| entropy_loss | -44.2 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 7799 |
| policy_loss | 520 |
| std | 1.06 |
| value_loss | 162 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 7900 |
| time_elapsed | 508 |
| total_timesteps | 39500 |
| train/ | |
| entropy_loss | -44.2 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 7899 |
| policy_loss | -54.3 |
| std | 1.06 |
| value_loss | 2.66 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 8000 |
| time_elapsed | 514 |
| total_timesteps | 40000 |
| train/ | |
| entropy_loss | -44.3 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 7999 |
| policy_loss | 58.2 |
| std | 1.06 |
| value_loss | 2.26 |
------------------------------------
-------------------------------------
| environment/ | |
| portfolio_value | 4.63e+06 |
| total_cost | 8.6e+03 |
| total_reward | 3.63e+06 |
| total_reward_pct | 363 |
| total_trades | 58469 |
| time/ | |
| fps | 77 |
| iterations | 8100 |
| time_elapsed | 520 |
| total_timesteps | 40500 |
| train/ | |
| entropy_loss | -44.3 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 8099 |
| policy_loss | -20.9 |
| std | 1.06 |
| value_loss | 0.355 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 8200 |
| time_elapsed | 527 |
| total_timesteps | 41000 |
| train/ | |
| entropy_loss | -44.3 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 8199 |
| policy_loss | -38.6 |
| std | 1.06 |
| value_loss | 0.935 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 8300 |
| time_elapsed | 533 |
| total_timesteps | 41500 |
| train/ | |
| entropy_loss | -44.3 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 8299 |
| policy_loss | 11.9 |
| std | 1.06 |
| value_loss | 0.774 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 8400 |
| time_elapsed | 540 |
| total_timesteps | 42000 |
| train/ | |
| entropy_loss | -44.3 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 8399 |
| policy_loss | -39.8 |
| std | 1.06 |
| value_loss | 1.31 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 8500 |
| time_elapsed | 546 |
| total_timesteps | 42500 |
| train/ | |
| entropy_loss | -44.2 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 8499 |
| policy_loss | -128 |
| std | 1.06 |
| value_loss | 16.3 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 8600 |
| time_elapsed | 553 |
| total_timesteps | 43000 |
| train/ | |
| entropy_loss | -44.3 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 8599 |
| policy_loss | 70.4 |
| std | 1.06 |
| value_loss | 2.69 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 8700 |
| time_elapsed | 559 |
| total_timesteps | 43500 |
| train/ | |
| entropy_loss | -44.3 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 8699 |
| policy_loss | 170 |
| std | 1.06 |
| value_loss | 57.3 |
------------------------------------
------------------------------------
| environment/ | |
| portfolio_value | 4.48e+06 |
| total_cost | 5.81e+03 |
| total_reward | 3.48e+06 |
| total_reward_pct | 348 |
| total_trades | 57804 |
| time/ | |
| fps | 77 |
| iterations | 8800 |
| time_elapsed | 565 |
| total_timesteps | 44000 |
| train/ | |
| entropy_loss | -44.3 |
| explained_variance | 0.00216 |
| learning_rate | 0.0007 |
| n_updates | 8799 |
| policy_loss | -63 |
| std | 1.06 |
| value_loss | 3.26 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 8900 |
| time_elapsed | 572 |
| total_timesteps | 44500 |
| train/ | |
| entropy_loss | -44.3 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 8899 |
| policy_loss | -111 |
| std | 1.06 |
| value_loss | 7.1 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 9000 |
| time_elapsed | 579 |
| total_timesteps | 45000 |
| train/ | |
| entropy_loss | -44.3 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 8999 |
| policy_loss | -72.9 |
| std | 1.06 |
| value_loss | 3.48 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 77 |
| iterations | 9100 |
| time_elapsed | 585 |
| total_timesteps | 45500 |
| train/ | |
| entropy_loss | -44.4 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 9099 |
| policy_loss | -18.6 |
| std | 1.06 |
| value_loss | 0.765 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 9200 |
| time_elapsed | 592 |
| total_timesteps | 46000 |
| train/ | |
| entropy_loss | -44.4 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 9199 |
| policy_loss | 71.5 |
| std | 1.07 |
| value_loss | 2.94 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 9300 |
| time_elapsed | 598 |
| total_timesteps | 46500 |
| train/ | |
| entropy_loss | -44.5 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 9299 |
| policy_loss | -8.18 |
| std | 1.07 |
| value_loss | 0.324 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 9400 |
| time_elapsed | 605 |
| total_timesteps | 47000 |
| train/ | |
| entropy_loss | -44.6 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 9399 |
| policy_loss | -262 |
| std | 1.07 |
| value_loss | 34.3 |
------------------------------------
------------------------------------
| environment/ | |
| portfolio_value | 3.96e+06 |
| total_cost | 4.92e+03 |
| total_reward | 2.96e+06 |
| total_reward_pct | 296 |
| total_trades | 58228 |
| time/ | |
| fps | 77 |
| iterations | 9500 |
| time_elapsed | 611 |
| total_timesteps | 47500 |
| train/ | |
| entropy_loss | -44.6 |
| explained_variance | 0.111 |
| learning_rate | 0.0007 |
| n_updates | 9499 |
| policy_loss | 58.7 |
| std | 1.07 |
| value_loss | 2.02 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 9600 |
| time_elapsed | 618 |
| total_timesteps | 48000 |
| train/ | |
| entropy_loss | -44.6 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 9599 |
| policy_loss | 103 |
| std | 1.07 |
| value_loss | 7.2 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 77 |
| iterations | 9700 |
| time_elapsed | 624 |
| total_timesteps | 48500 |
| train/ | |
| entropy_loss | -44.6 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 9699 |
| policy_loss | -62 |
| std | 1.07 |
| value_loss | 4.3 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 9800 |
| time_elapsed | 631 |
| total_timesteps | 49000 |
| train/ | |
| entropy_loss | -44.6 |
| explained_variance | 5.96e-08 |
| learning_rate | 0.0007 |
| n_updates | 9799 |
| policy_loss | 25.5 |
| std | 1.07 |
| value_loss | 1.05 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 77 |
| iterations | 9900 |
| time_elapsed | 637 |
| total_timesteps | 49500 |
| train/ | |
| entropy_loss | -44.6 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 9899 |
| policy_loss | 34.8 |
| std | 1.07 |
| value_loss | 1.79 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 10000 |
| time_elapsed | 644 |
| total_timesteps | 50000 |
| train/ | |
| entropy_loss | -44.6 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 9999 |
| policy_loss | -288 |
| std | 1.07 |
| value_loss | 45.4 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 77 |
| iterations | 10100 |
| time_elapsed | 650 |
| total_timesteps | 50500 |
| train/ | |
| entropy_loss | -44.7 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 10099 |
| policy_loss | 176 |
| std | 1.07 |
| value_loss | 17.8 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 10200 |
| time_elapsed | 657 |
| total_timesteps | 51000 |
| train/ | |
| entropy_loss | -44.7 |
| explained_variance | 5.96e-08 |
| learning_rate | 0.0007 |
| n_updates | 10199 |
| policy_loss | -22.3 |
| std | 1.08 |
| value_loss | 1.66 |
------------------------------------
------------------------------------
| environment/ | |
| portfolio_value | 4.38e+06 |
| total_cost | 5.66e+03 |
| total_reward | 3.38e+06 |
| total_reward_pct | 338 |
| total_trades | 61155 |
| time/ | |
| fps | 77 |
| iterations | 10300 |
| time_elapsed | 664 |
| total_timesteps | 51500 |
| train/ | |
| entropy_loss | -44.8 |
| explained_variance | 3.46e-06 |
| learning_rate | 0.0007 |
| n_updates | 10299 |
| policy_loss | -18.2 |
| std | 1.08 |
| value_loss | 0.59 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 10400 |
| time_elapsed | 670 |
| total_timesteps | 52000 |
| train/ | |
| entropy_loss | -44.8 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 10399 |
| policy_loss | -166 |
| std | 1.08 |
| value_loss | 15.3 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 10500 |
| time_elapsed | 677 |
| total_timesteps | 52500 |
| train/ | |
| entropy_loss | -44.8 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 10499 |
| policy_loss | -1.79 |
| std | 1.08 |
| value_loss | 0.733 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 10600 |
| time_elapsed | 683 |
| total_timesteps | 53000 |
| train/ | |
| entropy_loss | -44.9 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 10599 |
| policy_loss | -46.4 |
| std | 1.08 |
| value_loss | 1.3 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 10700 |
| time_elapsed | 690 |
| total_timesteps | 53500 |
| train/ | |
| entropy_loss | -44.9 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 10699 |
| policy_loss | 358 |
| std | 1.08 |
| value_loss | 72.7 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 10800 |
| time_elapsed | 696 |
| total_timesteps | 54000 |
| train/ | |
| entropy_loss | -45 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 10799 |
| policy_loss | 26.8 |
| std | 1.08 |
| value_loss | 0.888 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 10900 |
| time_elapsed | 703 |
| total_timesteps | 54500 |
| train/ | |
| entropy_loss | -45 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 10899 |
| policy_loss | -124 |
| std | 1.09 |
| value_loss | 34.6 |
------------------------------------
------------------------------------
| environment/ | |
| portfolio_value | 3.93e+06 |
| total_cost | 7.95e+03 |
| total_reward | 2.93e+06 |
| total_reward_pct | 293 |
| total_trades | 62120 |
| time/ | |
| fps | 77 |
| iterations | 11000 |
| time_elapsed | 710 |
| total_timesteps | 55000 |
| train/ | |
| entropy_loss | -45.1 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 10999 |
| policy_loss | 88.9 |
| std | 1.09 |
| value_loss | 4.3 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 11100 |
| time_elapsed | 716 |
| total_timesteps | 55500 |
| train/ | |
| entropy_loss | -45 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 11099 |
| policy_loss | 25.5 |
| std | 1.09 |
| value_loss | 0.656 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 11200 |
| time_elapsed | 723 |
| total_timesteps | 56000 |
| train/ | |
| entropy_loss | -45 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 11199 |
| policy_loss | -91.8 |
| std | 1.09 |
| value_loss | 5 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 11300 |
| time_elapsed | 729 |
| total_timesteps | 56500 |
| train/ | |
| entropy_loss | -45.1 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 11299 |
| policy_loss | -168 |
| std | 1.09 |
| value_loss | 18 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 11400 |
| time_elapsed | 736 |
| total_timesteps | 57000 |
| train/ | |
| entropy_loss | -45.1 |
| explained_variance | 5.96e-08 |
| learning_rate | 0.0007 |
| n_updates | 11399 |
| policy_loss | 163 |
| std | 1.09 |
| value_loss | 11.3 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 11500 |
| time_elapsed | 742 |
| total_timesteps | 57500 |
| train/ | |
| entropy_loss | -45.1 |
| explained_variance | 1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 11499 |
| policy_loss | -269 |
| std | 1.09 |
| value_loss | 35.7 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 11600 |
| time_elapsed | 749 |
| total_timesteps | 58000 |
| train/ | |
| entropy_loss | -45.1 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 11599 |
| policy_loss | 117 |
| std | 1.09 |
| value_loss | 19.2 |
------------------------------------
------------------------------------
| environment/ | |
| portfolio_value | 3.86e+06 |
| total_cost | 9.73e+03 |
| total_reward | 2.86e+06 |
| total_reward_pct | 286 |
| total_trades | 59593 |
| time/ | |
| fps | 77 |
| iterations | 11700 |
| time_elapsed | 756 |
| total_timesteps | 58500 |
| train/ | |
| entropy_loss | -45.1 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 11699 |
| policy_loss | 146 |
| std | 1.09 |
| value_loss | 15 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 77 |
| iterations | 11800 |
| time_elapsed | 762 |
| total_timesteps | 59000 |
| train/ | |
| entropy_loss | -45.1 |
| explained_variance | -2.38e-07 |
| learning_rate | 0.0007 |
| n_updates | 11799 |
| policy_loss | -6.42 |
| std | 1.09 |
| value_loss | 0.452 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 11900 |
| time_elapsed | 769 |
| total_timesteps | 59500 |
| train/ | |
| entropy_loss | -45.1 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 11899 |
| policy_loss | -116 |
| std | 1.09 |
| value_loss | 8.42 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 12000 |
| time_elapsed | 775 |
| total_timesteps | 60000 |
| train/ | |
| entropy_loss | -45.2 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 11999 |
| policy_loss | 115 |
| std | 1.09 |
| value_loss | 7.46 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 12100 |
| time_elapsed | 782 |
| total_timesteps | 60500 |
| train/ | |
| entropy_loss | -45.2 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 12099 |
| policy_loss | 27.9 |
| std | 1.09 |
| value_loss | 2.52 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 12200 |
| time_elapsed | 788 |
| total_timesteps | 61000 |
| train/ | |
| entropy_loss | -45.2 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 12199 |
| policy_loss | -49.7 |
| std | 1.09 |
| value_loss | 4.56 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 77 |
| iterations | 12300 |
| time_elapsed | 795 |
| total_timesteps | 61500 |
| train/ | |
| entropy_loss | -45.2 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 12299 |
| policy_loss | -61.2 |
| std | 1.09 |
| value_loss | 2.91 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 12400 |
| time_elapsed | 801 |
| total_timesteps | 62000 |
| train/ | |
| entropy_loss | -45.3 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 12399 |
| policy_loss | 74.6 |
| std | 1.1 |
| value_loss | 15.6 |
------------------------------------
-------------------------------------
| environment/ | |
| portfolio_value | 4.12e+06 |
| total_cost | 5.9e+03 |
| total_reward | 3.12e+06 |
| total_reward_pct | 312 |
| total_trades | 61004 |
| time/ | |
| fps | 77 |
| iterations | 12500 |
| time_elapsed | 808 |
| total_timesteps | 62500 |
| train/ | |
| entropy_loss | -45.4 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 12499 |
| policy_loss | 61 |
| std | 1.1 |
| value_loss | 3.23 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 12600 |
| time_elapsed | 815 |
| total_timesteps | 63000 |
| train/ | |
| entropy_loss | -45.5 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 12599 |
| policy_loss | 74.9 |
| std | 1.1 |
| value_loss | 2.61 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 12700 |
| time_elapsed | 821 |
| total_timesteps | 63500 |
| train/ | |
| entropy_loss | -45.5 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 12699 |
| policy_loss | 77.4 |
| std | 1.1 |
| value_loss | 3.81 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 12800 |
| time_elapsed | 828 |
| total_timesteps | 64000 |
| train/ | |
| entropy_loss | -45.5 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 12799 |
| policy_loss | -14.7 |
| std | 1.1 |
| value_loss | 7.94 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 77 |
| iterations | 12900 |
| time_elapsed | 834 |
| total_timesteps | 64500 |
| train/ | |
| entropy_loss | -45.5 |
| explained_variance | -2.38e-07 |
| learning_rate | 0.0007 |
| n_updates | 12899 |
| policy_loss | 1.03e+03 |
| std | 1.1 |
| value_loss | 505 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 13000 |
| time_elapsed | 841 |
| total_timesteps | 65000 |
| train/ | |
| entropy_loss | -45.6 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 12999 |
| policy_loss | 124 |
| std | 1.11 |
| value_loss | 11.5 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 13100 |
| time_elapsed | 848 |
| total_timesteps | 65500 |
| train/ | |
| entropy_loss | -45.6 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 13099 |
| policy_loss | -15 |
| std | 1.11 |
| value_loss | 1.22 |
------------------------------------
------------------------------------
| environment/ | |
| portfolio_value | 4.65e+06 |
| total_cost | 8.07e+03 |
| total_reward | 3.65e+06 |
| total_reward_pct | 365 |
| total_trades | 62460 |
| time/ | |
| fps | 77 |
| iterations | 13200 |
| time_elapsed | 854 |
| total_timesteps | 66000 |
| train/ | |
| entropy_loss | -45.6 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 13199 |
| policy_loss | 46.3 |
| std | 1.11 |
| value_loss | 0.915 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 13300 |
| time_elapsed | 861 |
| total_timesteps | 66500 |
| train/ | |
| entropy_loss | -45.6 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 13299 |
| policy_loss | -14.1 |
| std | 1.11 |
| value_loss | 0.13 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 13400 |
| time_elapsed | 867 |
| total_timesteps | 67000 |
| train/ | |
| entropy_loss | -45.7 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 13399 |
| policy_loss | 65 |
| std | 1.11 |
| value_loss | 4.92 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 13500 |
| time_elapsed | 874 |
| total_timesteps | 67500 |
| train/ | |
| entropy_loss | -45.7 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 13499 |
| policy_loss | 121 |
| std | 1.11 |
| value_loss | 7.18 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 77 |
| iterations | 13600 |
| time_elapsed | 880 |
| total_timesteps | 68000 |
| train/ | |
| entropy_loss | -45.7 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 13599 |
| policy_loss | 81.3 |
| std | 1.11 |
| value_loss | 14.1 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 13700 |
| time_elapsed | 887 |
| total_timesteps | 68500 |
| train/ | |
| entropy_loss | -45.7 |
| explained_variance | 1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 13699 |
| policy_loss | 104 |
| std | 1.11 |
| value_loss | 5.04 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 13800 |
| time_elapsed | 893 |
| total_timesteps | 69000 |
| train/ | |
| entropy_loss | -45.8 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 13799 |
| policy_loss | -263 |
| std | 1.11 |
| value_loss | 31.9 |
------------------------------------
day: 3650, episode: 20
begin_total_asset: 1000000.00
end_total_asset: 3959377.31
total_reward: 2959377.31
total_cost: 5535.60
total_trades: 64004
Sharpe: 0.755
=================================
------------------------------------
| environment/ | |
| portfolio_value | 3.96e+06 |
| total_cost | 5.54e+03 |
| total_reward | 2.96e+06 |
| total_reward_pct | 296 |
| total_trades | 64004 |
| time/ | |
| fps | 77 |
| iterations | 13900 |
| time_elapsed | 900 |
| total_timesteps | 69500 |
| train/ | |
| entropy_loss | -45.8 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 13899 |
| policy_loss | 25.9 |
| std | 1.11 |
| value_loss | 0.428 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 14000 |
| time_elapsed | 907 |
| total_timesteps | 70000 |
| train/ | |
| entropy_loss | -45.8 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 13999 |
| policy_loss | 40.9 |
| std | 1.12 |
| value_loss | 1.52 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 14100 |
| time_elapsed | 913 |
| total_timesteps | 70500 |
| train/ | |
| entropy_loss | -45.9 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 14099 |
| policy_loss | -0.995 |
| std | 1.12 |
| value_loss | 0.024 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 14200 |
| time_elapsed | 920 |
| total_timesteps | 71000 |
| train/ | |
| entropy_loss | -45.8 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 14199 |
| policy_loss | 21.5 |
| std | 1.12 |
| value_loss | 0.753 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 14300 |
| time_elapsed | 926 |
| total_timesteps | 71500 |
| train/ | |
| entropy_loss | -45.9 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 14299 |
| policy_loss | 96.7 |
| std | 1.12 |
| value_loss | 5.54 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 14400 |
| time_elapsed | 933 |
| total_timesteps | 72000 |
| train/ | |
| entropy_loss | -45.9 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 14399 |
| policy_loss | 99.8 |
| std | 1.12 |
| value_loss | 5.77 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 14500 |
| time_elapsed | 940 |
| total_timesteps | 72500 |
| train/ | |
| entropy_loss | -45.9 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 14499 |
| policy_loss | 43.6 |
| std | 1.12 |
| value_loss | 1.32 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 14600 |
| time_elapsed | 946 |
| total_timesteps | 73000 |
| train/ | |
| entropy_loss | -45.9 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 14599 |
| policy_loss | -874 |
| std | 1.12 |
| value_loss | 365 |
------------------------------------
------------------------------------
| environment/ | |
| portfolio_value | 3.87e+06 |
| total_cost | 5.34e+03 |
| total_reward | 2.87e+06 |
| total_reward_pct | 287 |
| total_trades | 67475 |
| time/ | |
| fps | 77 |
| iterations | 14700 |
| time_elapsed | 953 |
| total_timesteps | 73500 |
| train/ | |
| entropy_loss | -45.9 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 14699 |
| policy_loss | 36.2 |
| std | 1.12 |
| value_loss | 0.616 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 14800 |
| time_elapsed | 960 |
| total_timesteps | 74000 |
| train/ | |
| entropy_loss | -45.9 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 14799 |
| policy_loss | -129 |
| std | 1.12 |
| value_loss | 12.7 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 14900 |
| time_elapsed | 966 |
| total_timesteps | 74500 |
| train/ | |
| entropy_loss | -46 |
| explained_variance | 5.96e-08 |
| learning_rate | 0.0007 |
| n_updates | 14899 |
| policy_loss | 27.7 |
| std | 1.12 |
| value_loss | 1.76 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 15000 |
| time_elapsed | 973 |
| total_timesteps | 75000 |
| train/ | |
| entropy_loss | -46 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 14999 |
| policy_loss | 84 |
| std | 1.12 |
| value_loss | 5.1 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 77 |
| iterations | 15100 |
| time_elapsed | 979 |
| total_timesteps | 75500 |
| train/ | |
| entropy_loss | -45.9 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 15099 |
| policy_loss | -7.35 |
| std | 1.12 |
| value_loss | 1.71 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 15200 |
| time_elapsed | 986 |
| total_timesteps | 76000 |
| train/ | |
| entropy_loss | -45.9 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 15199 |
| policy_loss | 126 |
| std | 1.12 |
| value_loss | 8.75 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 15300 |
| time_elapsed | 993 |
| total_timesteps | 76500 |
| train/ | |
| entropy_loss | -45.9 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 15299 |
| policy_loss | 190 |
| std | 1.12 |
| value_loss | 31.7 |
------------------------------------
------------------------------------
| environment/ | |
| portfolio_value | 4.14e+06 |
| total_cost | 4.28e+03 |
| total_reward | 3.14e+06 |
| total_reward_pct | 314 |
| total_trades | 66224 |
| time/ | |
| fps | 77 |
| iterations | 15400 |
| time_elapsed | 999 |
| total_timesteps | 77000 |
| train/ | |
| entropy_loss | -46 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 15399 |
| policy_loss | 15.4 |
| std | 1.12 |
| value_loss | 0.418 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 77 |
| iterations | 15500 |
| time_elapsed | 1006 |
| total_timesteps | 77500 |
| train/ | |
| entropy_loss | -46.1 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 15499 |
| policy_loss | -1.22 |
| std | 1.13 |
| value_loss | 0.0144 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 15600 |
| time_elapsed | 1012 |
| total_timesteps | 78000 |
| train/ | |
| entropy_loss | -46.1 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 15599 |
| policy_loss | 126 |
| std | 1.13 |
| value_loss | 6.33 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 77 |
| iterations | 15700 |
| time_elapsed | 1019 |
| total_timesteps | 78500 |
| train/ | |
| entropy_loss | -46.2 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 15699 |
| policy_loss | -1.57 |
| std | 1.13 |
| value_loss | 0.0992 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 15800 |
| time_elapsed | 1026 |
| total_timesteps | 79000 |
| train/ | |
| entropy_loss | -46.2 |
| explained_variance | 1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 15799 |
| policy_loss | 177 |
| std | 1.13 |
| value_loss | 15.9 |
------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 15900 |
| time_elapsed | 1032 |
| total_timesteps | 79500 |
| train/ | |
| entropy_loss | -46.2 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 15899 |
| policy_loss | -99.7 |
| std | 1.13 |
| value_loss | 7.94 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 76 |
| iterations | 16000 |
| time_elapsed | 1039 |
| total_timesteps | 80000 |
| train/ | |
| entropy_loss | -46.2 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 15999 |
| policy_loss | -482 |
| std | 1.13 |
| value_loss | 114 |
-------------------------------------
-------------------------------------
| environment/ | |
| portfolio_value | 3.94e+06 |
| total_cost | 3.49e+03 |
| total_reward | 2.94e+06 |
| total_reward_pct | 294 |
| total_trades | 64301 |
| time/ | |
| fps | 76 |
| iterations | 16100 |
| time_elapsed | 1045 |
| total_timesteps | 80500 |
| train/ | |
| entropy_loss | -46.2 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 16099 |
| policy_loss | -23.5 |
| std | 1.13 |
| value_loss | 1.91 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 16200 |
| time_elapsed | 1052 |
| total_timesteps | 81000 |
| train/ | |
| entropy_loss | -46.3 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 16199 |
| policy_loss | 46.5 |
| std | 1.13 |
| value_loss | 3.81 |
------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 16300 |
| time_elapsed | 1058 |
| total_timesteps | 81500 |
| train/ | |
| entropy_loss | -46.3 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 16299 |
| policy_loss | 18.1 |
| std | 1.13 |
| value_loss | 0.592 |
------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 16400 |
| time_elapsed | 1065 |
| total_timesteps | 82000 |
| train/ | |
| entropy_loss | -46.3 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 16399 |
| policy_loss | 151 |
| std | 1.14 |
| value_loss | 11.9 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 76 |
| iterations | 16500 |
| time_elapsed | 1071 |
| total_timesteps | 82500 |
| train/ | |
| entropy_loss | -46.3 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 16499 |
| policy_loss | -151 |
| std | 1.13 |
| value_loss | 18.1 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 16600 |
| time_elapsed | 1078 |
| total_timesteps | 83000 |
| train/ | |
| entropy_loss | -46.3 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 16599 |
| policy_loss | -409 |
| std | 1.14 |
| value_loss | 79 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 77 |
| iterations | 16700 |
| time_elapsed | 1084 |
| total_timesteps | 83500 |
| train/ | |
| entropy_loss | -46.3 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 16699 |
| policy_loss | 44.8 |
| std | 1.14 |
| value_loss | 7.51 |
-------------------------------------
------------------------------------
| environment/ | |
| portfolio_value | 4.12e+06 |
| total_cost | 3.41e+03 |
| total_reward | 3.12e+06 |
| total_reward_pct | 312 |
| total_trades | 61475 |
| time/ | |
| fps | 77 |
| iterations | 16800 |
| time_elapsed | 1090 |
| total_timesteps | 84000 |
| train/ | |
| entropy_loss | -46.4 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 16799 |
| policy_loss | 11 |
| std | 1.14 |
| value_loss | 0.286 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 16900 |
| time_elapsed | 1097 |
| total_timesteps | 84500 |
| train/ | |
| entropy_loss | -46.4 |
| explained_variance | 1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 16899 |
| policy_loss | -24.2 |
| std | 1.14 |
| value_loss | 5.16 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 17000 |
| time_elapsed | 1103 |
| total_timesteps | 85000 |
| train/ | |
| entropy_loss | -46.4 |
| explained_variance | 1.79e-07 |
| learning_rate | 0.0007 |
| n_updates | 16999 |
| policy_loss | 38.8 |
| std | 1.14 |
| value_loss | 2.14 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 17100 |
| time_elapsed | 1110 |
| total_timesteps | 85500 |
| train/ | |
| entropy_loss | -46.4 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 17099 |
| policy_loss | 1.28 |
| std | 1.14 |
| value_loss | 0.161 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 17200 |
| time_elapsed | 1116 |
| total_timesteps | 86000 |
| train/ | |
| entropy_loss | -46.3 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 17199 |
| policy_loss | -175 |
| std | 1.14 |
| value_loss | 14.5 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 17300 |
| time_elapsed | 1123 |
| total_timesteps | 86500 |
| train/ | |
| entropy_loss | -46.3 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 17299 |
| policy_loss | -126 |
| std | 1.14 |
| value_loss | 11.5 |
------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 17400 |
| time_elapsed | 1129 |
| total_timesteps | 87000 |
| train/ | |
| entropy_loss | -46.4 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 17399 |
| policy_loss | -48.4 |
| std | 1.14 |
| value_loss | 1.55 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 76 |
| iterations | 17500 |
| time_elapsed | 1136 |
| total_timesteps | 87500 |
| train/ | |
| entropy_loss | -46.4 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 17499 |
| policy_loss | 139 |
| std | 1.14 |
| value_loss | 10.4 |
-------------------------------------
-------------------------------------
| environment/ | |
| portfolio_value | 4.17e+06 |
| total_cost | 6.22e+03 |
| total_reward | 3.17e+06 |
| total_reward_pct | 317 |
| total_trades | 58146 |
| time/ | |
| fps | 76 |
| iterations | 17600 |
| time_elapsed | 1142 |
| total_timesteps | 88000 |
| train/ | |
| entropy_loss | -46.4 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 17599 |
| policy_loss | 10.5 |
| std | 1.14 |
| value_loss | 0.0937 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 17700 |
| time_elapsed | 1149 |
| total_timesteps | 88500 |
| train/ | |
| entropy_loss | -46.3 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 17699 |
| policy_loss | -62.6 |
| std | 1.14 |
| value_loss | 2.89 |
------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 17800 |
| time_elapsed | 1156 |
| total_timesteps | 89000 |
| train/ | |
| entropy_loss | -46.4 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 17799 |
| policy_loss | 64.3 |
| std | 1.14 |
| value_loss | 1.99 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 76 |
| iterations | 17900 |
| time_elapsed | 1162 |
| total_timesteps | 89500 |
| train/ | |
| entropy_loss | -46.4 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 17899 |
| policy_loss | 36.1 |
| std | 1.14 |
| value_loss | 1.18 |
-------------------------------------
-------------------------------------
| time/ | |
| fps | 76 |
| iterations | 18000 |
| time_elapsed | 1169 |
| total_timesteps | 90000 |
| train/ | |
| entropy_loss | -46.4 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 17999 |
| policy_loss | 117 |
| std | 1.14 |
| value_loss | 13.6 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 18100 |
| time_elapsed | 1176 |
| total_timesteps | 90500 |
| train/ | |
| entropy_loss | -46.5 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 18099 |
| policy_loss | 138 |
| std | 1.14 |
| value_loss | 25.8 |
------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 18200 |
| time_elapsed | 1183 |
| total_timesteps | 91000 |
| train/ | |
| entropy_loss | -46.5 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 18199 |
| policy_loss | -109 |
| std | 1.14 |
| value_loss | 19.1 |
------------------------------------
------------------------------------
| environment/ | |
| portfolio_value | 4.4e+06 |
| total_cost | 8.75e+03 |
| total_reward | 3.4e+06 |
| total_reward_pct | 340 |
| total_trades | 64975 |
| time/ | |
| fps | 76 |
| iterations | 18300 |
| time_elapsed | 1189 |
| total_timesteps | 91500 |
| train/ | |
| entropy_loss | -46.5 |
| explained_variance | -0.0014 |
| learning_rate | 0.0007 |
| n_updates | 18299 |
| policy_loss | 22 |
| std | 1.14 |
| value_loss | 0.829 |
------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 18400 |
| time_elapsed | 1196 |
| total_timesteps | 92000 |
| train/ | |
| entropy_loss | -46.7 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 18399 |
| policy_loss | 12.7 |
| std | 1.15 |
| value_loss | 0.192 |
------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 18500 |
| time_elapsed | 1202 |
| total_timesteps | 92500 |
| train/ | |
| entropy_loss | -46.6 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 18499 |
| policy_loss | -80.5 |
| std | 1.15 |
| value_loss | 5.62 |
------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 18600 |
| time_elapsed | 1209 |
| total_timesteps | 93000 |
| train/ | |
| entropy_loss | -46.6 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 18599 |
| policy_loss | 127 |
| std | 1.15 |
| value_loss | 8.09 |
------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 18700 |
| time_elapsed | 1215 |
| total_timesteps | 93500 |
| train/ | |
| entropy_loss | -46.6 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 18699 |
| policy_loss | -108 |
| std | 1.15 |
| value_loss | 17.2 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 76 |
| iterations | 18800 |
| time_elapsed | 1222 |
| total_timesteps | 94000 |
| train/ | |
| entropy_loss | -46.7 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 18799 |
| policy_loss | -145 |
| std | 1.15 |
| value_loss | 11.8 |
-------------------------------------
-------------------------------------
| time/ | |
| fps | 76 |
| iterations | 18900 |
| time_elapsed | 1229 |
| total_timesteps | 94500 |
| train/ | |
| entropy_loss | -46.6 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 18899 |
| policy_loss | 150 |
| std | 1.15 |
| value_loss | 14.4 |
-------------------------------------
------------------------------------
| environment/ | |
| portfolio_value | 4.16e+06 |
| total_cost | 7.62e+03 |
| total_reward | 3.16e+06 |
| total_reward_pct | 316 |
| total_trades | 66603 |
| time/ | |
| fps | 76 |
| iterations | 19000 |
| time_elapsed | 1235 |
| total_timesteps | 95000 |
| train/ | |
| entropy_loss | -46.6 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 18999 |
| policy_loss | 260 |
| std | 1.15 |
| value_loss | 30.2 |
------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 19100 |
| time_elapsed | 1242 |
| total_timesteps | 95500 |
| train/ | |
| entropy_loss | -46.6 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 19099 |
| policy_loss | 97.7 |
| std | 1.15 |
| value_loss | 7.94 |
------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 19200 |
| time_elapsed | 1248 |
| total_timesteps | 96000 |
| train/ | |
| entropy_loss | -46.6 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 19199 |
| policy_loss | 53.5 |
| std | 1.15 |
| value_loss | 1.59 |
------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 19300 |
| time_elapsed | 1255 |
| total_timesteps | 96500 |
| train/ | |
| entropy_loss | -46.6 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 19299 |
| policy_loss | 165 |
| std | 1.15 |
| value_loss | 15.8 |
------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 19400 |
| time_elapsed | 1262 |
| total_timesteps | 97000 |
| train/ | |
| entropy_loss | -46.6 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 19399 |
| policy_loss | 1.48 |
| std | 1.15 |
| value_loss | 0.168 |
------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 19500 |
| time_elapsed | 1268 |
| total_timesteps | 97500 |
| train/ | |
| entropy_loss | -46.7 |
| explained_variance | 5.96e-08 |
| learning_rate | 0.0007 |
| n_updates | 19499 |
| policy_loss | -463 |
| std | 1.15 |
| value_loss | 104 |
------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 19600 |
| time_elapsed | 1275 |
| total_timesteps | 98000 |
| train/ | |
| entropy_loss | -46.7 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 19599 |
| policy_loss | -39.8 |
| std | 1.15 |
| value_loss | 1.29 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 76 |
| iterations | 19700 |
| time_elapsed | 1281 |
| total_timesteps | 98500 |
| train/ | |
| entropy_loss | -46.8 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 19699 |
| policy_loss | -1.11e+03 |
| std | 1.15 |
| value_loss | 583 |
-------------------------------------
-------------------------------------
| environment/ | |
| portfolio_value | 4.42e+06 |
| total_cost | 5.67e+03 |
| total_reward | 3.42e+06 |
| total_reward_pct | 342 |
| total_trades | 57577 |
| time/ | |
| fps | 76 |
| iterations | 19800 |
| time_elapsed | 1288 |
| total_timesteps | 99000 |
| train/ | |
| entropy_loss | -46.7 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 19799 |
| policy_loss | -3.03 |
| std | 1.15 |
| value_loss | 0.427 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 19900 |
| time_elapsed | 1295 |
| total_timesteps | 99500 |
| train/ | |
| entropy_loss | -46.8 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 19899 |
| policy_loss | -127 |
| std | 1.15 |
| value_loss | 6.54 |
------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 20000 |
| time_elapsed | 1301 |
| total_timesteps | 100000 |
| train/ | |
| entropy_loss | -46.8 |
| explained_variance | 1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 19999 |
| policy_loss | 79.1 |
| std | 1.15 |
| value_loss | 4.91 |
------------------------------------
###Markdown
Model 2: DDPG
###Code
agent = DRLAgent(env = env_train)
model_ddpg = agent.get_model("ddpg")
trained_ddpg = agent.train_model(model=model_ddpg,
tb_log_name='ddpg',
total_timesteps=50000)
###Output
Logging to tensorboard_log/ddpg/ddpg_3
---------------------------------
| time/ | |
| episodes | 4 |
| fps | 66 |
| time_elapsed | 218 |
| total timesteps | 14604 |
| train/ | |
| actor_loss | -40.1 |
| critic_loss | 213 |
| learning_rate | 0.001 |
| n_updates | 10953 |
---------------------------------
---------------------------------
| time/ | |
| episodes | 8 |
| fps | 62 |
| time_elapsed | 463 |
| total timesteps | 29208 |
| train/ | |
| actor_loss | -14.9 |
| critic_loss | 2.92 |
| learning_rate | 0.001 |
| n_updates | 25557 |
---------------------------------
day: 3650, episode: 40
begin_total_asset: 1000000.00
end_total_asset: 3024712.17
total_reward: 2024712.17
total_cost: 999.00
total_trades: 72983
Sharpe: 0.626
=================================
---------------------------------
| time/ | |
| episodes | 12 |
| fps | 61 |
| time_elapsed | 710 |
| total timesteps | 43812 |
| train/ | |
| actor_loss | -10.4 |
| critic_loss | 2.28 |
| learning_rate | 0.001 |
| n_updates | 40161 |
---------------------------------
###Markdown
Model 3: PPO
###Code
agent = DRLAgent(env = env_train)
PPO_PARAMS = {
"n_steps": 2048,
"ent_coef": 0.01,
"learning_rate": 0.00025,
"batch_size": 128,
}
model_ppo = agent.get_model("ppo",model_kwargs = PPO_PARAMS)
trained_ppo = agent.train_model(model=model_ppo,
tb_log_name='ppo',
total_timesteps=50000)
###Output
Logging to tensorboard_log/ppo/ppo_1
-----------------------------
| time/ | |
| fps | 76 |
| iterations | 1 |
| time_elapsed | 26 |
| total_timesteps | 2048 |
-----------------------------
-----------------------------------------
| time/ | |
| fps | 75 |
| iterations | 2 |
| time_elapsed | 54 |
| total_timesteps | 4096 |
| train/ | |
| approx_kl | 0.018077655 |
| clip_fraction | 0.231 |
| clip_range | 0.2 |
| entropy_loss | -42.6 |
| explained_variance | -0.0123 |
| learning_rate | 0.00025 |
| loss | 3.1 |
| n_updates | 10 |
| policy_gradient_loss | -0.0292 |
| std | 1 |
| value_loss | 7.21 |
-----------------------------------------
-----------------------------------------
| time/ | |
| fps | 75 |
| iterations | 3 |
| time_elapsed | 81 |
| total_timesteps | 6144 |
| train/ | |
| approx_kl | 0.013950874 |
| clip_fraction | 0.17 |
| clip_range | 0.2 |
| entropy_loss | -42.6 |
| explained_variance | -0.00143 |
| learning_rate | 0.00025 |
| loss | 5.92 |
| n_updates | 20 |
| policy_gradient_loss | -0.0229 |
| std | 1 |
| value_loss | 13.6 |
-----------------------------------------
----------------------------------------
| time/ | |
| fps | 74 |
| iterations | 4 |
| time_elapsed | 109 |
| total_timesteps | 8192 |
| train/ | |
| approx_kl | 0.01641549 |
| clip_fraction | 0.183 |
| clip_range | 0.2 |
| entropy_loss | -42.6 |
| explained_variance | -0.0118 |
| learning_rate | 0.00025 |
| loss | 6.06 |
| n_updates | 30 |
| policy_gradient_loss | -0.0282 |
| std | 1 |
| value_loss | 11.9 |
----------------------------------------
-----------------------------------------
| time/ | |
| fps | 74 |
| iterations | 5 |
| time_elapsed | 136 |
| total_timesteps | 10240 |
| train/ | |
| approx_kl | 0.025979618 |
| clip_fraction | 0.241 |
| clip_range | 0.2 |
| entropy_loss | -42.7 |
| explained_variance | -0.00485 |
| learning_rate | 0.00025 |
| loss | 13 |
| n_updates | 40 |
| policy_gradient_loss | -0.0157 |
| std | 1 |
| value_loss | 19.3 |
-----------------------------------------
-----------------------------------------
| time/ | |
| fps | 74 |
| iterations | 6 |
| time_elapsed | 163 |
| total_timesteps | 12288 |
| train/ | |
| approx_kl | 0.016590398 |
| clip_fraction | 0.21 |
| clip_range | 0.2 |
| entropy_loss | -42.7 |
| explained_variance | -0.0153 |
| learning_rate | 0.00025 |
| loss | 3.53 |
| n_updates | 50 |
| policy_gradient_loss | -0.0251 |
| std | 1.01 |
| value_loss | 11 |
-----------------------------------------
-----------------------------------------
| time/ | |
| fps | 74 |
| iterations | 7 |
| time_elapsed | 191 |
| total_timesteps | 14336 |
| train/ | |
| approx_kl | 0.020591479 |
| clip_fraction | 0.229 |
| clip_range | 0.2 |
| entropy_loss | -42.8 |
| explained_variance | 0.0132 |
| learning_rate | 0.00025 |
| loss | 6.55 |
| n_updates | 60 |
| policy_gradient_loss | -0.0197 |
| std | 1.01 |
| value_loss | 14.2 |
-----------------------------------------
day: 3650, episode: 20
begin_total_asset: 1000000.00
end_total_asset: 2689089.43
total_reward: 1689089.43
total_cost: 380034.51
total_trades: 104033
Sharpe: 0.638
=================================
-----------------------------------------
| time/ | |
| fps | 74 |
| iterations | 8 |
| time_elapsed | 218 |
| total_timesteps | 16384 |
| train/ | |
| approx_kl | 0.020969098 |
| clip_fraction | 0.268 |
| clip_range | 0.2 |
| entropy_loss | -42.9 |
| explained_variance | -0.000622 |
| learning_rate | 0.00025 |
| loss | 7 |
| n_updates | 70 |
| policy_gradient_loss | -0.0173 |
| std | 1.01 |
| value_loss | 12.7 |
-----------------------------------------
----------------------------------------
| time/ | |
| fps | 74 |
| iterations | 9 |
| time_elapsed | 246 |
| total_timesteps | 18432 |
| train/ | |
| approx_kl | 0.02511882 |
| clip_fraction | 0.28 |
| clip_range | 0.2 |
| entropy_loss | -43 |
| explained_variance | -0.0182 |
| learning_rate | 0.00025 |
| loss | 5.87 |
| n_updates | 80 |
| policy_gradient_loss | -0.0152 |
| std | 1.02 |
| value_loss | 11.4 |
----------------------------------------
----------------------------------------
| time/ | |
| fps | 74 |
| iterations | 10 |
| time_elapsed | 273 |
| total_timesteps | 20480 |
| train/ | |
| approx_kl | 0.02978786 |
| clip_fraction | 0.276 |
| clip_range | 0.2 |
| entropy_loss | -43.1 |
| explained_variance | 0.00553 |
| learning_rate | 0.00025 |
| loss | 7.83 |
| n_updates | 90 |
| policy_gradient_loss | -0.0169 |
| std | 1.02 |
| value_loss | 18 |
----------------------------------------
----------------------------------------
| time/ | |
| fps | 74 |
| iterations | 11 |
| time_elapsed | 301 |
| total_timesteps | 22528 |
| train/ | |
| approx_kl | 0.02986148 |
| clip_fraction | 0.263 |
| clip_range | 0.2 |
| entropy_loss | -43.1 |
| explained_variance | -0.0465 |
| learning_rate | 0.00025 |
| loss | 4.94 |
| n_updates | 100 |
| policy_gradient_loss | -0.0156 |
| std | 1.02 |
| value_loss | 9.13 |
----------------------------------------
---------------------------------------
| time/ | |
| fps | 74 |
| iterations | 12 |
| time_elapsed | 328 |
| total_timesteps | 24576 |
| train/ | |
| approx_kl | 0.0287299 |
| clip_fraction | 0.267 |
| clip_range | 0.2 |
| entropy_loss | -43.2 |
| explained_variance | -0.00762 |
| learning_rate | 0.00025 |
| loss | 9.6 |
| n_updates | 110 |
| policy_gradient_loss | -0.0165 |
| std | 1.02 |
| value_loss | 20.9 |
---------------------------------------
-----------------------------------------
| time/ | |
| fps | 74 |
| iterations | 13 |
| time_elapsed | 355 |
| total_timesteps | 26624 |
| train/ | |
| approx_kl | 0.023247771 |
| clip_fraction | 0.264 |
| clip_range | 0.2 |
| entropy_loss | -43.2 |
| explained_variance | -0.0257 |
| learning_rate | 0.00025 |
| loss | 2.04 |
| n_updates | 120 |
| policy_gradient_loss | -0.0105 |
| std | 1.02 |
| value_loss | 6.91 |
-----------------------------------------
-----------------------------------------
| time/ | |
| fps | 74 |
| iterations | 14 |
| time_elapsed | 382 |
| total_timesteps | 28672 |
| train/ | |
| approx_kl | 0.020957708 |
| clip_fraction | 0.243 |
| clip_range | 0.2 |
| entropy_loss | -43.3 |
| explained_variance | -0.00506 |
| learning_rate | 0.00025 |
| loss | 3.57 |
| n_updates | 130 |
| policy_gradient_loss | -0.0166 |
| std | 1.02 |
| value_loss | 11.4 |
-----------------------------------------
-----------------------------------------
| time/ | |
| fps | 74 |
| iterations | 15 |
| time_elapsed | 410 |
| total_timesteps | 30720 |
| train/ | |
| approx_kl | 0.032833345 |
| clip_fraction | 0.296 |
| clip_range | 0.2 |
| entropy_loss | -43.4 |
| explained_variance | -0.0181 |
| learning_rate | 0.00025 |
| loss | 2.71 |
| n_updates | 140 |
| policy_gradient_loss | -0.0192 |
| std | 1.03 |
| value_loss | 7.09 |
-----------------------------------------
----------------------------------------
| time/ | |
| fps | 74 |
| iterations | 16 |
| time_elapsed | 437 |
| total_timesteps | 32768 |
| train/ | |
| approx_kl | 0.02443498 |
| clip_fraction | 0.241 |
| clip_range | 0.2 |
| entropy_loss | -43.5 |
| explained_variance | -0.0293 |
| learning_rate | 0.00025 |
| loss | 4.9 |
| n_updates | 150 |
| policy_gradient_loss | -0.0277 |
| std | 1.03 |
| value_loss | 8.48 |
----------------------------------------
-----------------------------------------
| time/ | |
| fps | 74 |
| iterations | 17 |
| time_elapsed | 464 |
| total_timesteps | 34816 |
| train/ | |
| approx_kl | 0.016761096 |
| clip_fraction | 0.233 |
| clip_range | 0.2 |
| entropy_loss | -43.5 |
| explained_variance | -0.0188 |
| learning_rate | 0.00025 |
| loss | 3 |
| n_updates | 160 |
| policy_gradient_loss | -0.0162 |
| std | 1.03 |
| value_loss | 9.8 |
-----------------------------------------
----------------------------------------
| time/ | |
| fps | 74 |
| iterations | 18 |
| time_elapsed | 491 |
| total_timesteps | 36864 |
| train/ | |
| approx_kl | 0.03664797 |
| clip_fraction | 0.34 |
| clip_range | 0.2 |
| entropy_loss | -43.6 |
| explained_variance | 0.00438 |
| learning_rate | 0.00025 |
| loss | 4.71 |
| n_updates | 170 |
| policy_gradient_loss | -0.0206 |
| std | 1.04 |
| value_loss | 6.72 |
----------------------------------------
-----------------------------------------
| time/ | |
| fps | 74 |
| iterations | 19 |
| time_elapsed | 518 |
| total_timesteps | 38912 |
| train/ | |
| approx_kl | 0.030327313 |
| clip_fraction | 0.308 |
| clip_range | 0.2 |
| entropy_loss | -43.6 |
| explained_variance | 0.0309 |
| learning_rate | 0.00025 |
| loss | 6 |
| n_updates | 180 |
| policy_gradient_loss | -0.00991 |
| std | 1.04 |
| value_loss | 11.2 |
-----------------------------------------
-----------------------------------------
| time/ | |
| fps | 75 |
| iterations | 20 |
| time_elapsed | 545 |
| total_timesteps | 40960 |
| train/ | |
| approx_kl | 0.028725432 |
| clip_fraction | 0.244 |
| clip_range | 0.2 |
| entropy_loss | -43.7 |
| explained_variance | 0.0224 |
| learning_rate | 0.00025 |
| loss | 1.66 |
| n_updates | 190 |
| policy_gradient_loss | -0.00988 |
| std | 1.04 |
| value_loss | 6.45 |
-----------------------------------------
-----------------------------------------
| time/ | |
| fps | 75 |
| iterations | 21 |
| time_elapsed | 573 |
| total_timesteps | 43008 |
| train/ | |
| approx_kl | 0.035785355 |
| clip_fraction | 0.252 |
| clip_range | 0.2 |
| entropy_loss | -43.8 |
| explained_variance | -0.00199 |
| learning_rate | 0.00025 |
| loss | 7.69 |
| n_updates | 200 |
| policy_gradient_loss | -0.00915 |
| std | 1.04 |
| value_loss | 14.2 |
-----------------------------------------
----------------------------------------
| time/ | |
| fps | 75 |
| iterations | 22 |
| time_elapsed | 600 |
| total_timesteps | 45056 |
| train/ | |
| approx_kl | 0.02488321 |
| clip_fraction | 0.259 |
| clip_range | 0.2 |
| entropy_loss | -43.8 |
| explained_variance | 0.0224 |
| learning_rate | 0.00025 |
| loss | 3.55 |
| n_updates | 210 |
| policy_gradient_loss | -0.00496 |
| std | 1.04 |
| value_loss | 8.94 |
----------------------------------------
-----------------------------------------
| time/ | |
| fps | 75 |
| iterations | 23 |
| time_elapsed | 627 |
| total_timesteps | 47104 |
| train/ | |
| approx_kl | 0.024153344 |
| clip_fraction | 0.272 |
| clip_range | 0.2 |
| entropy_loss | -43.9 |
| explained_variance | -0.0405 |
| learning_rate | 0.00025 |
| loss | 5.38 |
| n_updates | 220 |
| policy_gradient_loss | -0.0153 |
| std | 1.05 |
| value_loss | 14.4 |
-----------------------------------------
-----------------------------------------
| time/ | |
| fps | 75 |
| iterations | 24 |
| time_elapsed | 654 |
| total_timesteps | 49152 |
| train/ | |
| approx_kl | 0.037768982 |
| clip_fraction | 0.309 |
| clip_range | 0.2 |
| entropy_loss | -44 |
| explained_variance | -0.00958 |
| learning_rate | 0.00025 |
| loss | 4.37 |
| n_updates | 230 |
| policy_gradient_loss | 0.00366 |
| std | 1.05 |
| value_loss | 12.4 |
-----------------------------------------
day: 3650, episode: 30
begin_total_asset: 1000000.00
end_total_asset: 3250700.91
total_reward: 2250700.91
total_cost: 329606.76
total_trades: 98701
Sharpe: 0.750
=================================
-----------------------------------------
| time/ | |
| fps | 75 |
| iterations | 25 |
| time_elapsed | 681 |
| total_timesteps | 51200 |
| train/ | |
| approx_kl | 0.034196474 |
| clip_fraction | 0.301 |
| clip_range | 0.2 |
| entropy_loss | -44.1 |
| explained_variance | -0.00227 |
| learning_rate | 0.00025 |
| loss | 3.84 |
| n_updates | 240 |
| policy_gradient_loss | -0.0192 |
| std | 1.05 |
| value_loss | 11.4 |
-----------------------------------------
###Markdown
Model 4: TD3
###Code
agent = DRLAgent(env = env_train)
TD3_PARAMS = {"batch_size": 100,
"buffer_size": 1000000,
"learning_rate": 0.001}
model_td3 = agent.get_model("td3",model_kwargs = TD3_PARAMS)
trained_td3 = agent.train_model(model=model_td3,
tb_log_name='td3',
total_timesteps=30000)
###Output
Logging to tensorboard_log/td3/td3_1
---------------------------------
| time/ | |
| episodes | 4 |
| fps | 26 |
| time_elapsed | 559 |
| total timesteps | 14604 |
| train/ | |
| actor_loss | 4.64 |
| critic_loss | 720 |
| learning_rate | 0.001 |
| n_updates | 10953 |
---------------------------------
---------------------------------
| time/ | |
| episodes | 8 |
| fps | 22 |
| time_elapsed | 1289 |
| total timesteps | 29208 |
| train/ | |
| actor_loss | 10.6 |
| critic_loss | 14.2 |
| learning_rate | 0.001 |
| n_updates | 25557 |
---------------------------------
day: 3650, episode: 40
begin_total_asset: 1000000.00
end_total_asset: 3319811.55
total_reward: 2319811.55
total_cost: 998.99
total_trades: 51100
Sharpe: 0.649
=================================
###Markdown
Model 5: SAC
###Code
agent = DRLAgent(env = env_train)
SAC_PARAMS = {
"batch_size": 128,
"buffer_size": 1000000,
"learning_rate": 0.0001,
"learning_starts": 100,
"ent_coef": "auto_0.1",
}
model_sac = agent.get_model("sac",model_kwargs = SAC_PARAMS)
trained_sac = agent.train_model(model=model_sac,
tb_log_name='sac',
total_timesteps=80000)
###Output
Logging to tensorboard_log/sac/sac_2
---------------------------------
| time/ | |
| episodes | 4 |
| fps | 21 |
| time_elapsed | 685 |
| total timesteps | 14604 |
| train/ | |
| actor_loss | 172 |
| critic_loss | 28.6 |
| ent_coef | 0.0742 |
| ent_coef_loss | -126 |
| learning_rate | 0.0001 |
| n_updates | 14503 |
---------------------------------
---------------------------------
| time/ | |
| episodes | 8 |
| fps | 20 |
| time_elapsed | 1401 |
| total timesteps | 29208 |
| train/ | |
| actor_loss | 9.68 |
| critic_loss | 9.81 |
| ent_coef | 0.0174 |
| ent_coef_loss | -173 |
| learning_rate | 0.0001 |
| n_updates | 29107 |
---------------------------------
day: 3650, episode: 10
begin_total_asset: 1000000.00
end_total_asset: 4889674.97
total_reward: 3889674.97
total_cost: 7706.97
total_trades: 70158
Sharpe: 0.752
=================================
---------------------------------
| time/ | |
| episodes | 12 |
| fps | 20 |
| time_elapsed | 2114 |
| total timesteps | 43812 |
| train/ | |
| actor_loss | -13.3 |
| critic_loss | 14 |
| ent_coef | 0.00427 |
| ent_coef_loss | -128 |
| learning_rate | 0.0001 |
| n_updates | 43711 |
---------------------------------
---------------------------------
| time/ | |
| episodes | 16 |
| fps | 20 |
| time_elapsed | 2842 |
| total timesteps | 58416 |
| train/ | |
| actor_loss | -7 |
| critic_loss | 8.71 |
| ent_coef | 0.00148 |
| ent_coef_loss | -3.87 |
| learning_rate | 0.0001 |
| n_updates | 58315 |
---------------------------------
day: 3650, episode: 20
begin_total_asset: 1000000.00
end_total_asset: 3389166.27
total_reward: 2389166.27
total_cost: 1895.61
total_trades: 62481
Sharpe: 0.623
=================================
---------------------------------
| time/ | |
| episodes | 20 |
| fps | 20 |
| time_elapsed | 3585 |
| total timesteps | 73020 |
| train/ | |
| actor_loss | -4.82 |
| critic_loss | 12.4 |
| ent_coef | 0.00159 |
| ent_coef_loss | -4.38 |
| learning_rate | 0.0001 |
| n_updates | 72919 |
---------------------------------
###Markdown
TradingAssume that we have $1,000,000 initial capital at 2019-01-01. We use the DDPG model to trade Dow jones 30 stocks. TradeDRL model needs to update periodically in order to take full advantage of the data, ideally we need to retrain our model yearly, quarterly, or monthly. We also need to tune the parameters along the way, in this notebook I only use the in-sample data from 2009-01 to 2018-12 to tune the parameters once, so there is some alpha decay here as the length of trade date extends. Numerous hyperparameters – e.g. the learning rate, the total number of samples to train on – influence the learning process and are usually determined by testing some variations.
###Code
trade = data_split(processed_full, '2019-01-01','2021-01-01')
e_trade_gym = StockTradingEnv(df = trade, **env_kwargs)
# env_trade, obs_trade = e_trade_gym.get_sb_env()
trade.head()
df_account_value, df_actions = DRLAgent.DRL_prediction(
model=trained_ddpg,
environment = e_trade_gym)
df_account_value.shape
df_account_value.tail()
df_actions.head()
###Output
_____no_output_____
###Markdown
Part 7: Backtest Our StrategyBacktesting plays a key role in evaluating the performance of a trading strategy. Automated backtesting tool is preferred because it reduces the human error. We usually use the Quantopian pyfolio package to backtest our trading strategies. It is easy to use and consists of various individual plots that provide a comprehensive image of the performance of a trading strategy. 7.1 BackTestStatspass in df_account_value, this information is stored in env class
###Code
print("==============Get Backtest Results===========")
now = datetime.datetime.now().strftime('%Y%m%d-%Hh%M')
perf_stats_all = backtest_stats(account_value=df_account_value)
perf_stats_all = pd.DataFrame(perf_stats_all)
perf_stats_all.to_csv("./"+config.RESULTS_DIR+"/perf_stats_all_"+now+'.csv')
#baseline stats
print("==============Get Baseline Stats===========")
baseline_df = get_baseline(
ticker="^DJI",
start = '2019-01-01',
end = '2021-01-01')
stats = backtest_stats(baseline_df, value_col_name = 'close')
###Output
==============Get Baseline Stats===========
[*********************100%***********************] 1 of 1 completed
Shape of DataFrame: (505, 8)
Annual return 0.144674
Cumulative returns 0.310981
Annual volatility 0.274619
Sharpe ratio 0.631418
Calmar ratio 0.390102
Stability 0.116677
Max drawdown -0.370862
Omega ratio 1.149365
Sortino ratio 0.870084
Skew NaN
Kurtosis NaN
Tail ratio 0.860710
Daily value at risk -0.033911
dtype: float64
###Markdown
7.2 BackTestPlot
###Code
print("==============Compare to DJIA===========")
%matplotlib inline
# S&P 500: ^GSPC
# Dow Jones Index: ^DJI
# NASDAQ 100: ^NDX
backtest_plot(df_account_value,
baseline_ticker = '^DJI',
baseline_start = '2019-01-01',
baseline_end = '2021-01-01')
###Output
_____no_output_____
###Markdown
Automated stock trading using FinRL with financial dataTrained a Deep Reinforcement Learning model using FinRL and companies' financial ratio, and then backtested the model to examine how well-trained the model is* This Google Colabolatory notebook is based on the tutorial of FinRL: https://towardsdatascience.com/finrl-for-quantitative-finance-tutorial-for-multiple-stock-trading-7b00763b7530* This project is a final project of the almuni-mentored research project at Columbia University, Application of Reinforcement Learning to Finance, mentored by Bruce Yang from AI4Finance.* For more detailed explanation, please check out my Medium post: https://medium.com/@mariko.sawada1/automated-stock-trading-with-deep-reinforcement-learning-and-financial-data-a63286ccbe2b Content * [1. Problem Definition](0)* [2. Getting Started - Load Python packages](1) * [2.1. Install Packages](1.1) * [2.2. Check Additional Packages](1.2) * [2.3. Import Packages](1.3) * [2.4. Create Folders](1.4)* [3. Download Data](2)* [4. Preprocess fundamental Data](3) * [4-1 Import financial data](3.1) * [4-2 Specify items needed to calculate financial ratios](3.2) * [4-3 Calculate financial ratios](3.3) * [4-4 Deal with NAs and infinite values](3.4) * [4-5 Merge stock price data and ratios into one dataframe](3.5) * [4-6 Calculate market valuation ratios using daily stock price data](3.6)* [5.Build Environment](4) * [5.1. Training & Trade Data Split](4.1) * [5.2. User-defined Environment](4.2) * [5.3. Initialize Environment](4.3) * [6.Implement DRL Algorithms](5) * [7.Backtesting Performance](6) * [7.1. BackTestStats](6.1) * [7.2. BackTestPlot](6.2) * [7.3. Baseline Stats](6.3) * [7.3. Compare to Stock Market Index](6.4) Part 1. Problem Definition This problem is to design an automated trading solution for single stock trading. We model the stock trading process as a Markov Decision Process (MDP). We then formulate our trading goal as a maximization problem.The algorithm is trained using Deep Reinforcement Learning (DRL) algorithms and the components of the reinforcement learning environment are:* Action: The action space describes the allowed actions that the agent interacts with theenvironment. Normally, a ∈ A includes three actions: a ∈ {−1, 0, 1}, where −1, 0, 1 representselling, holding, and buying one stock. Also, an action can be carried upon multiple shares. We usean action space {−k, ..., −1, 0, 1, ..., k}, where k denotes the number of shares. For example, "Buy10 shares of AAPL" or "Sell 10 shares of AAPL" are 10 or −10, respectively* Reward function: r(s, a, s′) is the incentive mechanism for an agent to learn a better action. The change of the portfolio value when action a is taken at state s and arriving at new state s', i.e., r(s, a, s′) = v′ − v, where v′ and v represent the portfoliovalues at state s′ and s, respectively* State: The state space describes the observations that the agent receives from the environment. Just as a human trader needs to analyze various information before executing a trade, soour trading agent observes many different features to better learn in an interactive environment.* Environment: Dow 30 consituentsThe data of the single stock that we will be using for this case study is obtained from Yahoo Finance API. The data contains Open-High-Low-Close price and volume. Part 2. Load Python Packages 2.1. Install all the packages through FinRL library
###Code
## install finrl library
!pip install git+https://github.com/AI4Finance-LLC/FinRL-Library.git
###Output
Collecting git+https://github.com/AI4Finance-LLC/FinRL-Library.git
Cloning https://github.com/AI4Finance-LLC/FinRL-Library.git to /tmp/pip-req-build-avwct7pb
Running command git clone -q https://github.com/AI4Finance-LLC/FinRL-Library.git /tmp/pip-req-build-avwct7pb
Collecting pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2
Cloning https://github.com/quantopian/pyfolio.git to /tmp/pip-install-sps4f25k/pyfolio_2efe9a99238a42588250d6733a01d260
Running command git clone -q https://github.com/quantopian/pyfolio.git /tmp/pip-install-sps4f25k/pyfolio_2efe9a99238a42588250d6733a01d260
Collecting elegantrl@ git+https://github.com/AI4Finance-Foundation/ElegantRL.git#egg=elegantrl
Cloning https://github.com/AI4Finance-Foundation/ElegantRL.git to /tmp/pip-install-sps4f25k/elegantrl_28233bba5b454d3399006626d813b65b
Running command git clone -q https://github.com/AI4Finance-Foundation/ElegantRL.git /tmp/pip-install-sps4f25k/elegantrl_28233bba5b454d3399006626d813b65b
Requirement already satisfied: numpy>=1.17.3 in /usr/local/lib/python3.7/dist-packages (from finrl==0.3.4) (1.19.5)
Requirement already satisfied: pandas>=1.1.5 in /usr/local/lib/python3.7/dist-packages (from finrl==0.3.4) (1.1.5)
Collecting stockstats>=0.4.0
Downloading stockstats-0.4.1-py2.py3-none-any.whl (19 kB)
Collecting yfinance
Downloading yfinance-0.1.69-py2.py3-none-any.whl (26 kB)
Collecting elegantrl
Downloading elegantrl-0.3.3-py3-none-any.whl (234 kB)
[K |████████████████████████████████| 234 kB 26.4 MB/s
[?25hRequirement already satisfied: matplotlib in /usr/local/lib/python3.7/dist-packages (from finrl==0.3.4) (3.2.2)
Requirement already satisfied: scikit-learn>=0.21.0 in /usr/local/lib/python3.7/dist-packages (from finrl==0.3.4) (1.0.2)
Requirement already satisfied: gym>=0.17 in /usr/local/lib/python3.7/dist-packages (from finrl==0.3.4) (0.17.3)
Collecting stable-baselines3[extra]
Downloading stable_baselines3-1.3.0-py3-none-any.whl (174 kB)
[K |████████████████████████████████| 174 kB 73.9 MB/s
[?25hCollecting ray[default]
Downloading ray-1.9.2-cp37-cp37m-manylinux2014_x86_64.whl (57.6 MB)
[K |████████████████████████████████| 57.6 MB 1.2 MB/s
[?25hCollecting lz4
Downloading lz4-3.1.10-cp37-cp37m-manylinux2010_x86_64.whl (1.8 MB)
[K |████████████████████████████████| 1.8 MB 63.9 MB/s
[?25hCollecting tensorboardX
Downloading tensorboardX-2.4.1-py2.py3-none-any.whl (124 kB)
[K |████████████████████████████████| 124 kB 83.4 MB/s
[?25hCollecting gputil
Downloading GPUtil-1.4.0.tar.gz (5.5 kB)
Collecting exchange_calendars
Downloading exchange_calendars-3.5.tar.gz (147 kB)
[K |████████████████████████████████| 147 kB 68.3 MB/s
[?25hCollecting alpaca_trade_api
Downloading alpaca_trade_api-1.4.3-py3-none-any.whl (36 kB)
Collecting ccxt>=1.66.32
Downloading ccxt-1.67.31-py2.py3-none-any.whl (2.3 MB)
[K |████████████████████████████████| 2.3 MB 61.2 MB/s
[?25hCollecting jqdatasdk
Downloading jqdatasdk-1.8.10-py3-none-any.whl (153 kB)
[K |████████████████████████████████| 153 kB 76.3 MB/s
[?25hCollecting wrds
Downloading wrds-3.1.1-py3-none-any.whl (12 kB)
Requirement already satisfied: pytest in /usr/local/lib/python3.7/dist-packages (from finrl==0.3.4) (3.6.4)
Requirement already satisfied: setuptools>=41.4.0 in /usr/local/lib/python3.7/dist-packages (from finrl==0.3.4) (57.4.0)
Requirement already satisfied: wheel>=0.33.6 in /usr/local/lib/python3.7/dist-packages (from finrl==0.3.4) (0.37.1)
Collecting pre-commit
Downloading pre_commit-2.16.0-py2.py3-none-any.whl (191 kB)
[K |████████████████████████████████| 191 kB 75.1 MB/s
[?25hCollecting pybullet
Downloading pybullet-3.2.1-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.whl (90.8 MB)
[K |████████████████████████████████| 90.8 MB 298 bytes/s
[?25hRequirement already satisfied: torch in /usr/local/lib/python3.7/dist-packages (from elegantrl@ git+https://github.com/AI4Finance-Foundation/ElegantRL.git#egg=elegantrl->finrl==0.3.4) (1.10.0+cu111)
Requirement already satisfied: opencv-python in /usr/local/lib/python3.7/dist-packages (from elegantrl@ git+https://github.com/AI4Finance-Foundation/ElegantRL.git#egg=elegantrl->finrl==0.3.4) (4.1.2.30)
Collecting box2d-py
Downloading box2d_py-2.3.8-cp37-cp37m-manylinux1_x86_64.whl (448 kB)
[K |████████████████████████████████| 448 kB 60.4 MB/s
[?25hRequirement already satisfied: ipython>=3.2.3 in /usr/local/lib/python3.7/dist-packages (from pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.4) (5.5.0)
Requirement already satisfied: pytz>=2014.10 in /usr/local/lib/python3.7/dist-packages (from pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.4) (2018.9)
Requirement already satisfied: scipy>=0.14.0 in /usr/local/lib/python3.7/dist-packages (from pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.4) (1.4.1)
Requirement already satisfied: seaborn>=0.7.1 in /usr/local/lib/python3.7/dist-packages (from pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.4) (0.11.2)
Collecting empyrical>=0.5.0
Downloading empyrical-0.5.5.tar.gz (52 kB)
[K |████████████████████████████████| 52 kB 2.1 MB/s
[?25hRequirement already satisfied: requests>=2.18.4 in /usr/local/lib/python3.7/dist-packages (from ccxt>=1.66.32->finrl==0.3.4) (2.23.0)
Collecting yarl==1.7.2
Downloading yarl-1.7.2-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl (271 kB)
[K |████████████████████████████████| 271 kB 75.7 MB/s
[?25hCollecting aiohttp>=3.8
Downloading aiohttp-3.8.1-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl (1.1 MB)
[K |████████████████████████████████| 1.1 MB 58.7 MB/s
[?25hCollecting cryptography>=2.6.1
Downloading cryptography-36.0.1-cp36-abi3-manylinux_2_24_x86_64.whl (3.6 MB)
[K |████████████████████████████████| 3.6 MB 58.9 MB/s
[?25hRequirement already satisfied: certifi>=2018.1.18 in /usr/local/lib/python3.7/dist-packages (from ccxt>=1.66.32->finrl==0.3.4) (2021.10.8)
Collecting aiodns>=1.1.1
Downloading aiodns-3.0.0-py3-none-any.whl (5.0 kB)
Collecting multidict>=4.0
Downloading multidict-5.2.0-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl (160 kB)
[K |████████████████████████████████| 160 kB 67.6 MB/s
[?25hRequirement already satisfied: idna>=2.0 in /usr/local/lib/python3.7/dist-packages (from yarl==1.7.2->ccxt>=1.66.32->finrl==0.3.4) (2.10)
Requirement already satisfied: typing-extensions>=3.7.4 in /usr/local/lib/python3.7/dist-packages (from yarl==1.7.2->ccxt>=1.66.32->finrl==0.3.4) (3.10.0.2)
Collecting pycares>=4.0.0
Downloading pycares-4.1.2-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl (291 kB)
[K |████████████████████████████████| 291 kB 70.8 MB/s
[?25hRequirement already satisfied: charset-normalizer<3.0,>=2.0 in /usr/local/lib/python3.7/dist-packages (from aiohttp>=3.8->ccxt>=1.66.32->finrl==0.3.4) (2.0.10)
Collecting aiosignal>=1.1.2
Downloading aiosignal-1.2.0-py3-none-any.whl (8.2 kB)
Requirement already satisfied: attrs>=17.3.0 in /usr/local/lib/python3.7/dist-packages (from aiohttp>=3.8->ccxt>=1.66.32->finrl==0.3.4) (21.4.0)
Collecting asynctest==0.13.0
Downloading asynctest-0.13.0-py3-none-any.whl (26 kB)
Collecting async-timeout<5.0,>=4.0.0a3
Downloading async_timeout-4.0.2-py3-none-any.whl (5.8 kB)
Collecting frozenlist>=1.1.1
Downloading frozenlist-1.2.0-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl (192 kB)
[K |████████████████████████████████| 192 kB 73.4 MB/s
[?25hRequirement already satisfied: cffi>=1.12 in /usr/local/lib/python3.7/dist-packages (from cryptography>=2.6.1->ccxt>=1.66.32->finrl==0.3.4) (1.15.0)
Requirement already satisfied: pycparser in /usr/local/lib/python3.7/dist-packages (from cffi>=1.12->cryptography>=2.6.1->ccxt>=1.66.32->finrl==0.3.4) (2.21)
Requirement already satisfied: pandas-datareader>=0.2 in /usr/local/lib/python3.7/dist-packages (from empyrical>=0.5.0->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.4) (0.9.0)
Requirement already satisfied: pyglet<=1.5.0,>=1.4.0 in /usr/local/lib/python3.7/dist-packages (from gym>=0.17->finrl==0.3.4) (1.5.0)
Requirement already satisfied: cloudpickle<1.7.0,>=1.2.0 in /usr/local/lib/python3.7/dist-packages (from gym>=0.17->finrl==0.3.4) (1.3.0)
Requirement already satisfied: pygments in /usr/local/lib/python3.7/dist-packages (from ipython>=3.2.3->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.4) (2.6.1)
Requirement already satisfied: traitlets>=4.2 in /usr/local/lib/python3.7/dist-packages (from ipython>=3.2.3->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.4) (5.1.1)
Requirement already satisfied: pexpect in /usr/local/lib/python3.7/dist-packages (from ipython>=3.2.3->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.4) (4.8.0)
Requirement already satisfied: decorator in /usr/local/lib/python3.7/dist-packages (from ipython>=3.2.3->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.4) (4.4.2)
Requirement already satisfied: pickleshare in /usr/local/lib/python3.7/dist-packages (from ipython>=3.2.3->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.4) (0.7.5)
Requirement already satisfied: simplegeneric>0.8 in /usr/local/lib/python3.7/dist-packages (from ipython>=3.2.3->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.4) (0.8.1)
Requirement already satisfied: prompt-toolkit<2.0.0,>=1.0.4 in /usr/local/lib/python3.7/dist-packages (from ipython>=3.2.3->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.4) (1.0.18)
Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib->finrl==0.3.4) (0.11.0)
Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->finrl==0.3.4) (3.0.6)
Requirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->finrl==0.3.4) (2.8.2)
Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->finrl==0.3.4) (1.3.2)
Requirement already satisfied: lxml in /usr/local/lib/python3.7/dist-packages (from pandas-datareader>=0.2->empyrical>=0.5.0->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.4) (4.2.6)
Requirement already satisfied: six>=1.9.0 in /usr/local/lib/python3.7/dist-packages (from prompt-toolkit<2.0.0,>=1.0.4->ipython>=3.2.3->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.4) (1.15.0)
Requirement already satisfied: wcwidth in /usr/local/lib/python3.7/dist-packages (from prompt-toolkit<2.0.0,>=1.0.4->ipython>=3.2.3->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.4) (0.2.5)
Requirement already satisfied: future in /usr/local/lib/python3.7/dist-packages (from pyglet<=1.5.0,>=1.4.0->gym>=0.17->finrl==0.3.4) (0.16.0)
Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests>=2.18.4->ccxt>=1.66.32->finrl==0.3.4) (3.0.4)
Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests>=2.18.4->ccxt>=1.66.32->finrl==0.3.4) (1.24.3)
Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn>=0.21.0->finrl==0.3.4) (1.1.0)
Requirement already satisfied: threadpoolctl>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from scikit-learn>=0.21.0->finrl==0.3.4) (3.0.0)
Collecting msgpack==1.0.2
Downloading msgpack-1.0.2-cp37-cp37m-manylinux1_x86_64.whl (273 kB)
[K |████████████████████████████████| 273 kB 73.9 MB/s
[?25hCollecting websocket-client<2,>=0.56.0
Downloading websocket_client-1.2.3-py3-none-any.whl (53 kB)
[K |████████████████████████████████| 53 kB 2.8 MB/s
[?25hCollecting alpaca_trade_api
Downloading alpaca_trade_api-1.4.2-py3-none-any.whl (36 kB)
Downloading alpaca_trade_api-1.4.1-py3-none-any.whl (36 kB)
Downloading alpaca_trade_api-1.4.0-py3-none-any.whl (34 kB)
Downloading alpaca_trade_api-1.3.0-py3-none-any.whl (43 kB)
[K |████████████████████████████████| 43 kB 2.3 MB/s
[?25h Downloading alpaca_trade_api-1.2.3-py3-none-any.whl (40 kB)
[K |████████████████████████████████| 40 kB 7.3 MB/s
[?25hCollecting websockets<10,>=8.0
Downloading websockets-9.1-cp37-cp37m-manylinux2010_x86_64.whl (103 kB)
[K |████████████████████████████████| 103 kB 77.3 MB/s
[?25hCollecting pyluach
Downloading pyluach-1.3.0-py3-none-any.whl (17 kB)
Requirement already satisfied: toolz in /usr/local/lib/python3.7/dist-packages (from exchange_calendars->finrl==0.3.4) (0.11.2)
Requirement already satisfied: korean_lunar_calendar in /usr/local/lib/python3.7/dist-packages (from exchange_calendars->finrl==0.3.4) (0.2.1)
Collecting thriftpy2>=0.3.9
Downloading thriftpy2-0.4.14.tar.gz (361 kB)
[K |████████████████████████████████| 361 kB 78.3 MB/s
[?25hCollecting pymysql>=0.7.6
Downloading PyMySQL-1.0.2-py3-none-any.whl (43 kB)
[K |████████████████████████████████| 43 kB 2.7 MB/s
[?25hRequirement already satisfied: SQLAlchemy>=1.2.8 in /usr/local/lib/python3.7/dist-packages (from jqdatasdk->finrl==0.3.4) (1.4.29)
Requirement already satisfied: importlib-metadata in /usr/local/lib/python3.7/dist-packages (from SQLAlchemy>=1.2.8->jqdatasdk->finrl==0.3.4) (4.10.0)
Requirement already satisfied: greenlet!=0.4.17 in /usr/local/lib/python3.7/dist-packages (from SQLAlchemy>=1.2.8->jqdatasdk->finrl==0.3.4) (1.1.2)
Collecting ply<4.0,>=3.4
Downloading ply-3.11-py2.py3-none-any.whl (49 kB)
[K |████████████████████████████████| 49 kB 7.6 MB/s
[?25hRequirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata->SQLAlchemy>=1.2.8->jqdatasdk->finrl==0.3.4) (3.7.0)
Requirement already satisfied: ptyprocess>=0.5 in /usr/local/lib/python3.7/dist-packages (from pexpect->ipython>=3.2.3->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.4) (0.7.0)
Collecting pyyaml>=5.1
Downloading PyYAML-6.0-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl (596 kB)
[K |████████████████████████████████| 596 kB 66.2 MB/s
[?25hCollecting identify>=1.0.0
Downloading identify-2.4.3-py2.py3-none-any.whl (98 kB)
[K |████████████████████████████████| 98 kB 9.6 MB/s
[?25hCollecting nodeenv>=0.11.1
Downloading nodeenv-1.6.0-py2.py3-none-any.whl (21 kB)
Collecting virtualenv>=20.0.8
Downloading virtualenv-20.13.0-py2.py3-none-any.whl (6.5 MB)
[K |████████████████████████████████| 6.5 MB 50.1 MB/s
[?25hRequirement already satisfied: toml in /usr/local/lib/python3.7/dist-packages (from pre-commit->finrl==0.3.4) (0.10.2)
Collecting cfgv>=2.0.0
Downloading cfgv-3.3.1-py2.py3-none-any.whl (7.3 kB)
Collecting platformdirs<3,>=2
Downloading platformdirs-2.4.1-py3-none-any.whl (14 kB)
Collecting distlib<1,>=0.3.1
Downloading distlib-0.3.4-py2.py3-none-any.whl (461 kB)
[K |████████████████████████████████| 461 kB 65.2 MB/s
[?25hRequirement already satisfied: filelock<4,>=3.2 in /usr/local/lib/python3.7/dist-packages (from virtualenv>=20.0.8->pre-commit->finrl==0.3.4) (3.4.2)
Requirement already satisfied: pluggy<0.8,>=0.5 in /usr/local/lib/python3.7/dist-packages (from pytest->finrl==0.3.4) (0.7.1)
Requirement already satisfied: more-itertools>=4.0.0 in /usr/local/lib/python3.7/dist-packages (from pytest->finrl==0.3.4) (8.12.0)
Requirement already satisfied: atomicwrites>=1.0 in /usr/local/lib/python3.7/dist-packages (from pytest->finrl==0.3.4) (1.4.0)
Requirement already satisfied: py>=1.5.0 in /usr/local/lib/python3.7/dist-packages (from pytest->finrl==0.3.4) (1.11.0)
Collecting redis>=3.5.0
Downloading redis-4.1.0-py3-none-any.whl (171 kB)
[K |████████████████████████████████| 171 kB 77.2 MB/s
[?25hRequirement already satisfied: protobuf>=3.15.3 in /usr/local/lib/python3.7/dist-packages (from ray[default]->finrl==0.3.4) (3.17.3)
Requirement already satisfied: grpcio>=1.28.1 in /usr/local/lib/python3.7/dist-packages (from ray[default]->finrl==0.3.4) (1.43.0)
Requirement already satisfied: click>=7.0 in /usr/local/lib/python3.7/dist-packages (from ray[default]->finrl==0.3.4) (7.1.2)
Requirement already satisfied: jsonschema in /usr/local/lib/python3.7/dist-packages (from ray[default]->finrl==0.3.4) (4.3.3)
Requirement already satisfied: smart-open in /usr/local/lib/python3.7/dist-packages (from ray[default]->finrl==0.3.4) (5.2.1)
Collecting opencensus
Downloading opencensus-0.8.0-py2.py3-none-any.whl (128 kB)
[K |████████████████████████████████| 128 kB 80.3 MB/s
[?25hCollecting aiohttp-cors
Downloading aiohttp_cors-0.7.0-py3-none-any.whl (27 kB)
Collecting colorful
Downloading colorful-0.5.4-py2.py3-none-any.whl (201 kB)
[K |████████████████████████████████| 201 kB 79.8 MB/s
[?25hCollecting py-spy>=0.2.0
Downloading py_spy-0.3.11-py2.py3-none-manylinux_2_5_x86_64.manylinux1_x86_64.whl (3.0 MB)
[K |████████████████████████████████| 3.0 MB 61.5 MB/s
[?25hRequirement already satisfied: prometheus-client>=0.7.1 in /usr/local/lib/python3.7/dist-packages (from ray[default]->finrl==0.3.4) (0.12.0)
Collecting gpustat>=1.0.0b1
Downloading gpustat-1.0.0b1.tar.gz (82 kB)
[K |████████████████████████████████| 82 kB 313 kB/s
[?25hCollecting aioredis<2
Downloading aioredis-1.3.1-py3-none-any.whl (65 kB)
[K |████████████████████████████████| 65 kB 4.5 MB/s
[?25hCollecting hiredis
Downloading hiredis-2.0.0-cp37-cp37m-manylinux2010_x86_64.whl (85 kB)
[K |████████████████████████████████| 85 kB 4.7 MB/s
[?25hRequirement already satisfied: nvidia-ml-py3>=7.352.0 in /usr/local/lib/python3.7/dist-packages (from gpustat>=1.0.0b1->ray[default]->finrl==0.3.4) (7.352.0)
Requirement already satisfied: psutil in /usr/local/lib/python3.7/dist-packages (from gpustat>=1.0.0b1->ray[default]->finrl==0.3.4) (5.4.8)
Collecting blessed>=1.17.1
Downloading blessed-1.19.0-py2.py3-none-any.whl (57 kB)
[K |████████████████████████████████| 57 kB 7.1 MB/s
[?25hCollecting deprecated>=1.2.3
Downloading Deprecated-1.2.13-py2.py3-none-any.whl (9.6 kB)
Requirement already satisfied: packaging>=21.3 in /usr/local/lib/python3.7/dist-packages (from redis>=3.5.0->ray[default]->finrl==0.3.4) (21.3)
Requirement already satisfied: wrapt<2,>=1.10 in /usr/local/lib/python3.7/dist-packages (from deprecated>=1.2.3->redis>=3.5.0->ray[default]->finrl==0.3.4) (1.13.3)
Requirement already satisfied: pyrsistent!=0.17.0,!=0.17.1,!=0.17.2,>=0.14.0 in /usr/local/lib/python3.7/dist-packages (from jsonschema->ray[default]->finrl==0.3.4) (0.18.0)
Requirement already satisfied: importlib-resources>=1.4.0 in /usr/local/lib/python3.7/dist-packages (from jsonschema->ray[default]->finrl==0.3.4) (5.4.0)
Requirement already satisfied: google-api-core<3.0.0,>=1.0.0 in /usr/local/lib/python3.7/dist-packages (from opencensus->ray[default]->finrl==0.3.4) (1.26.3)
Collecting opencensus-context==0.1.2
Downloading opencensus_context-0.1.2-py2.py3-none-any.whl (4.4 kB)
Requirement already satisfied: google-auth<2.0dev,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from google-api-core<3.0.0,>=1.0.0->opencensus->ray[default]->finrl==0.3.4) (1.35.0)
Requirement already satisfied: googleapis-common-protos<2.0dev,>=1.6.0 in /usr/local/lib/python3.7/dist-packages (from google-api-core<3.0.0,>=1.0.0->opencensus->ray[default]->finrl==0.3.4) (1.54.0)
Requirement already satisfied: cachetools<5.0,>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from google-auth<2.0dev,>=1.21.1->google-api-core<3.0.0,>=1.0.0->opencensus->ray[default]->finrl==0.3.4) (4.2.4)
Requirement already satisfied: rsa<5,>=3.1.4 in /usr/local/lib/python3.7/dist-packages (from google-auth<2.0dev,>=1.21.1->google-api-core<3.0.0,>=1.0.0->opencensus->ray[default]->finrl==0.3.4) (4.8)
Requirement already satisfied: pyasn1-modules>=0.2.1 in /usr/local/lib/python3.7/dist-packages (from google-auth<2.0dev,>=1.21.1->google-api-core<3.0.0,>=1.0.0->opencensus->ray[default]->finrl==0.3.4) (0.2.8)
Requirement already satisfied: pyasn1<0.5.0,>=0.4.6 in /usr/local/lib/python3.7/dist-packages (from pyasn1-modules>=0.2.1->google-auth<2.0dev,>=1.21.1->google-api-core<3.0.0,>=1.0.0->opencensus->ray[default]->finrl==0.3.4) (0.4.8)
Requirement already satisfied: tabulate in /usr/local/lib/python3.7/dist-packages (from ray[default]->finrl==0.3.4) (0.8.9)
Requirement already satisfied: pillow in /usr/local/lib/python3.7/dist-packages (from stable-baselines3[extra]->finrl==0.3.4) (7.1.2)
Requirement already satisfied: tensorboard>=2.2.0 in /usr/local/lib/python3.7/dist-packages (from stable-baselines3[extra]->finrl==0.3.4) (2.7.0)
Requirement already satisfied: atari-py~=0.2.0 in /usr/local/lib/python3.7/dist-packages (from stable-baselines3[extra]->finrl==0.3.4) (0.2.9)
Requirement already satisfied: werkzeug>=0.11.15 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.4) (1.0.1)
Requirement already satisfied: tensorboard-plugin-wit>=1.6.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.4) (1.8.1)
Requirement already satisfied: tensorboard-data-server<0.7.0,>=0.6.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.4) (0.6.1)
Requirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.4) (0.4.6)
Requirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.4) (3.3.6)
Requirement already satisfied: absl-py>=0.4 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.4) (0.12.0)
Requirement already satisfied: requests-oauthlib>=0.7.0 in /usr/local/lib/python3.7/dist-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.4) (1.3.0)
Requirement already satisfied: oauthlib>=3.0.0 in /usr/local/lib/python3.7/dist-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.4) (3.1.1)
Collecting psycopg2-binary
Downloading psycopg2_binary-2.9.3-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl (3.0 MB)
[K |████████████████████████████████| 3.0 MB 30.7 MB/s
[?25hCollecting mock
Downloading mock-4.0.3-py3-none-any.whl (28 kB)
Requirement already satisfied: multitasking>=0.0.7 in /usr/local/lib/python3.7/dist-packages (from yfinance->finrl==0.3.4) (0.0.10)
Collecting requests>=2.18.4
Downloading requests-2.27.1-py2.py3-none-any.whl (63 kB)
[K |████████████████████████████████| 63 kB 2.1 MB/s
[?25hCollecting lxml
Downloading lxml-4.7.1-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_24_x86_64.whl (6.4 MB)
[K |████████████████████████████████| 6.4 MB 65.9 MB/s
[?25hBuilding wheels for collected packages: finrl, elegantrl, pyfolio, empyrical, exchange-calendars, gputil, thriftpy2, gpustat
Building wheel for finrl (setup.py) ... [?25l[?25hdone
Created wheel for finrl: filename=finrl-0.3.4-py3-none-any.whl size=3885434 sha256=849cbf03841a5a022427fa9f806d06b3e94a6b1b24c083a41ea6f47445b938d8
Stored in directory: /tmp/pip-ephem-wheel-cache-pv4yf2kc/wheels/17/ff/bd/1bc602a0352762b0b24041b88536d803ae343ed0a711fcf55e
Building wheel for elegantrl (setup.py) ... [?25l[?25hdone
Created wheel for elegantrl: filename=elegantrl-0.3.3-py3-none-any.whl size=188472 sha256=8d5083e1d626c2ef812b814b40640e39b5018c862373497d500b55728f0fb8a3
Stored in directory: /tmp/pip-ephem-wheel-cache-pv4yf2kc/wheels/99/85/5e/86cb3a9f47adfca5e248295e93113e1b298d60883126d62c84
Building wheel for pyfolio (setup.py) ... [?25l[?25hdone
Created wheel for pyfolio: filename=pyfolio-0.9.2+75.g4b901f6-py3-none-any.whl size=75774 sha256=c4497ace077e94d44cf5ac597e917a70823257583d7dac76152d009c98bda297
Stored in directory: /tmp/pip-ephem-wheel-cache-pv4yf2kc/wheels/ef/09/e5/2c1bf37c050d22557c080deb1be986d06424627c04aeca19b9
Building wheel for empyrical (setup.py) ... [?25l[?25hdone
Created wheel for empyrical: filename=empyrical-0.5.5-py3-none-any.whl size=39780 sha256=ae4a57d940f20813f523a30c1de536b1f2531cac23a5de0b0bf37a9d3fa12015
Stored in directory: /root/.cache/pip/wheels/d9/91/4b/654fcff57477efcf149eaca236da2fce991526cbab431bf312
Building wheel for exchange-calendars (setup.py) ... [?25l[?25hdone
Created wheel for exchange-calendars: filename=exchange_calendars-3.5-py3-none-any.whl size=179486 sha256=043fd7e4bfa797afe79a9eded1762c9d4543807b9c192f2d0d99df42c3c7b2ce
Stored in directory: /root/.cache/pip/wheels/69/21/43/b6ae2605dd767f6cd5a5b0b70c93a9a75823e44b3ccb92bce7
Building wheel for gputil (setup.py) ... [?25l[?25hdone
Created wheel for gputil: filename=GPUtil-1.4.0-py3-none-any.whl size=7411 sha256=7a9b6d994aaf299e7a3c73dbb8a98ede27aa9199340077bd7571f3f07d6d425b
Stored in directory: /root/.cache/pip/wheels/6e/f8/83/534c52482d6da64622ddbf72cd93c35d2ef2881b78fd08ff0c
Building wheel for thriftpy2 (setup.py) ... [?25l[?25hdone
Created wheel for thriftpy2: filename=thriftpy2-0.4.14-cp37-cp37m-linux_x86_64.whl size=944197 sha256=e3ccabc57c0d1511e6e87f870d8941748f3af10e1e9b00010db3a0692d48165d
Stored in directory: /root/.cache/pip/wheels/2a/f5/49/9c0d851aa64b58db72883cf9393cc824d536bdf13f5c83cff4
Building wheel for gpustat (setup.py) ... [?25l[?25hdone
Created wheel for gpustat: filename=gpustat-1.0.0b1-py3-none-any.whl size=15979 sha256=c470a062e2c777d4121d6f451cf0224bc94b2ac7043e66724f194cc1bed87289
Stored in directory: /root/.cache/pip/wheels/1a/16/e2/3e2437fba4c4b6a97a97bd96fce5d14e66cff5c4966fb1cc8c
Successfully built finrl elegantrl pyfolio empyrical exchange-calendars gputil thriftpy2 gpustat
Installing collected packages: requests, multidict, frozenlist, yarl, lxml, deprecated, asynctest, async-timeout, aiosignal, redis, pyyaml, pycares, ply, platformdirs, opencensus-context, msgpack, hiredis, distlib, blessed, aiohttp, websockets, websocket-client, virtualenv, thriftpy2, tensorboardX, stable-baselines3, ray, pymysql, pyluach, pybullet, py-spy, psycopg2-binary, opencensus, nodeenv, mock, identify, gpustat, empyrical, cryptography, colorful, cfgv, box2d-py, aioredis, aiohttp-cors, aiodns, yfinance, wrds, stockstats, pyfolio, pre-commit, lz4, jqdatasdk, gputil, exchange-calendars, elegantrl, ccxt, alpaca-trade-api, finrl
Attempting uninstall: requests
Found existing installation: requests 2.23.0
Uninstalling requests-2.23.0:
Successfully uninstalled requests-2.23.0
Attempting uninstall: lxml
Found existing installation: lxml 4.2.6
Uninstalling lxml-4.2.6:
Successfully uninstalled lxml-4.2.6
Attempting uninstall: pyyaml
Found existing installation: PyYAML 3.13
Uninstalling PyYAML-3.13:
Successfully uninstalled PyYAML-3.13
Attempting uninstall: msgpack
Found existing installation: msgpack 1.0.3
Uninstalling msgpack-1.0.3:
Successfully uninstalled msgpack-1.0.3
[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.
google-colab 1.0.0 requires requests~=2.23.0, but you have requests 2.27.1 which is incompatible.
datascience 0.10.6 requires folium==0.2.1, but you have folium 0.8.3 which is incompatible.[0m
Successfully installed aiodns-3.0.0 aiohttp-3.8.1 aiohttp-cors-0.7.0 aioredis-1.3.1 aiosignal-1.2.0 alpaca-trade-api-1.2.3 async-timeout-4.0.2 asynctest-0.13.0 blessed-1.19.0 box2d-py-2.3.8 ccxt-1.67.31 cfgv-3.3.1 colorful-0.5.4 cryptography-36.0.1 deprecated-1.2.13 distlib-0.3.4 elegantrl-0.3.3 empyrical-0.5.5 exchange-calendars-3.5 finrl-0.3.4 frozenlist-1.2.0 gpustat-1.0.0b1 gputil-1.4.0 hiredis-2.0.0 identify-2.4.3 jqdatasdk-1.8.10 lxml-4.7.1 lz4-3.1.10 mock-4.0.3 msgpack-1.0.2 multidict-5.2.0 nodeenv-1.6.0 opencensus-0.8.0 opencensus-context-0.1.2 platformdirs-2.4.1 ply-3.11 pre-commit-2.16.0 psycopg2-binary-2.9.3 py-spy-0.3.11 pybullet-3.2.1 pycares-4.1.2 pyfolio-0.9.2+75.g4b901f6 pyluach-1.3.0 pymysql-1.0.2 pyyaml-6.0 ray-1.9.2 redis-4.1.0 requests-2.27.1 stable-baselines3-1.3.0 stockstats-0.4.1 tensorboardX-2.4.1 thriftpy2-0.4.14 virtualenv-20.13.0 websocket-client-1.2.3 websockets-9.1 wrds-3.1.1 yarl-1.7.2 yfinance-0.1.69
###Markdown
2.2. Check if the additional packages needed are present, if not install them. * Yahoo Finance API* pandas* numpy* matplotlib* stockstats* OpenAI gym* stable-baselines* tensorflow* pyfolio 2.3. Import Packages
###Code
import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
# matplotlib.use('Agg')
import datetime
%matplotlib inline
from finrl.apps import config
from finrl.finrl_meta.preprocessor.yahoodownloader import YahooDownloader
from finrl.finrl_meta.preprocessor.preprocessors import FeatureEngineer, data_split
from finrl.finrl_meta.env_stock_trading.env_stocktrading import StockTradingEnv
from finrl.drl_agents.stablebaselines3.models import DRLAgent
from finrl.plot import backtest_stats, backtest_plot, get_daily_return, get_baseline
from pprint import pprint
import sys
sys.path.append("../FinRL-Library")
import itertools
###Output
/usr/local/lib/python3.7/dist-packages/pyfolio/pos.py:27: UserWarning: Module "zipline.assets" not found; multipliers will not be applied to position notionals.
'Module "zipline.assets" not found; multipliers will not be applied'
###Markdown
2.4. Create Folders
###Code
import os
if not os.path.exists("./" + config.DATA_SAVE_DIR):
os.makedirs("./" + config.DATA_SAVE_DIR)
if not os.path.exists("./" + config.TRAINED_MODEL_DIR):
os.makedirs("./" + config.TRAINED_MODEL_DIR)
if not os.path.exists("./" + config.TENSORBOARD_LOG_DIR):
os.makedirs("./" + config.TENSORBOARD_LOG_DIR)
if not os.path.exists("./" + config.RESULTS_DIR):
os.makedirs("./" + config.RESULTS_DIR)
###Output
_____no_output_____
###Markdown
Part 3. Download Stock Data from Yahoo FinanceYahoo Finance is a website that provides stock data, financial news, financial reports, etc. All the data provided by Yahoo Finance is free.* FinRL uses a class **YahooDownloader** to fetch data from Yahoo Finance API* Call Limit: Using the Public API (without authentication), you are limited to 2,000 requests per hour per IP (or up to a total of 48,000 requests a day). -----class YahooDownloader: Provides methods for retrieving daily stock data from Yahoo Finance API Attributes ---------- start_date : str start date of the data (modified from config.py) end_date : str end date of the data (modified from config.py) ticker_list : list a list of stock tickers (modified from config.py) Methods ------- fetch_data() Fetches data from yahoo API
###Code
# from config.py start_date is a string
config.START_DATE
# from config.py end_date is a string
config.END_DATE
print(config.DOW_30_TICKER)
df = YahooDownloader(start_date = '2009-01-01',
end_date = '2021-01-01',
ticker_list = config.DOW_30_TICKER).fetch_data()
df.shape
df.head()
df['date'] = pd.to_datetime(df['date'],format='%Y-%m-%d')
df.sort_values(['date','tic'],ignore_index=True).head()
###Output
_____no_output_____
###Markdown
Part 4: Preprocess fundamental data- Import finanical data downloaded from Compustat via WRDS(Wharton Research Data Service)- Preprocess the dataset and calculate financial ratios- Add those ratios to the price data preprocessed in Part 3- Calculate price-related ratios such as P/E and P/B 4-1 Import the financial data
###Code
# Import fundamental data from my GitHub repository
url = 'https://raw.githubusercontent.com/mariko-sawada/FinRL_with_fundamental_data/main/dow_30_fundamental_wrds.csv'
fund = pd.read_csv(url)
# Check the imported dataset
fund.head()
###Output
_____no_output_____
###Markdown
4-2 Specify items needed to calculate financial ratios- To know more about the data description of the dataset, please check WRDS's website(https://wrds-www.wharton.upenn.edu/). Login will be required.
###Code
# List items that are used to calculate financial ratios
items = [
'datadate', # Date
'tic', # Ticker
'oiadpq', # Quarterly operating income
'revtq', # Quartely revenue
'niq', # Quartely net income
'atq', # Total asset
'teqq', # Shareholder's equity
'epspiy', # EPS(Basic) incl. Extraordinary items
'ceqq', # Common Equity
'cshoq', # Common Shares Outstanding
'dvpspq', # Dividends per share
'actq', # Current assets
'lctq', # Current liabilities
'cheq', # Cash & Equivalent
'rectq', # Recievalbles
'cogsq', # Cost of Goods Sold
'invtq', # Inventories
'apq',# Account payable
'dlttq', # Long term debt
'dlcq', # Debt in current liabilites
'ltq' # Liabilities
]
# Omit items that will not be used
fund_data = fund[items]
# Rename column names for the sake of readability
fund_data = fund_data.rename(columns={
'datadate':'date', # Date
'oiadpq':'op_inc_q', # Quarterly operating income
'revtq':'rev_q', # Quartely revenue
'niq':'net_inc_q', # Quartely net income
'atq':'tot_assets', # Assets
'teqq':'sh_equity', # Shareholder's equity
'epspiy':'eps_incl_ex', # EPS(Basic) incl. Extraordinary items
'ceqq':'com_eq', # Common Equity
'cshoq':'sh_outstanding', # Common Shares Outstanding
'dvpspq':'div_per_sh', # Dividends per share
'actq':'cur_assets', # Current assets
'lctq':'cur_liabilities', # Current liabilities
'cheq':'cash_eq', # Cash & Equivalent
'rectq':'receivables', # Receivalbles
'cogsq':'cogs_q', # Cost of Goods Sold
'invtq':'inventories', # Inventories
'apq': 'payables',# Account payable
'dlttq':'long_debt', # Long term debt
'dlcq':'short_debt', # Debt in current liabilites
'ltq':'tot_liabilities' # Liabilities
})
# Check the data
fund_data.head()
###Output
_____no_output_____
###Markdown
4-3 Calculate financial ratios- For items from Profit/Loss statements, we calculate LTM (Last Twelve Months) and use them to derive profitability related ratios such as Operating Maring and ROE. For items from balance sheets, we use the numbers on the day.- To check the definitions of the financial ratios calculated here, please refer to CFI's website: https://corporatefinanceinstitute.com/resources/knowledge/finance/financial-ratios/
###Code
# Calculate financial ratios
date = pd.to_datetime(fund_data['date'],format='%Y%m%d')
tic = fund_data['tic'].to_frame('tic')
# Profitability ratios
# Operating Margin
OPM = pd.Series(np.empty(fund_data.shape[0],dtype=object),name='OPM')
for i in range(0, fund_data.shape[0]):
if i-3 < 0:
OPM[i] = np.nan
elif fund_data.iloc[i,1] != fund_data.iloc[i-3,1]:
OPM.iloc[i] = np.nan
else:
OPM.iloc[i] = np.sum(fund_data['op_inc_q'].iloc[i-3:i])/np.sum(fund_data['rev_q'].iloc[i-3:i])
# Net Profit Margin
NPM = pd.Series(np.empty(fund_data.shape[0],dtype=object),name='NPM')
for i in range(0, fund_data.shape[0]):
if i-3 < 0:
NPM[i] = np.nan
elif fund_data.iloc[i,1] != fund_data.iloc[i-3,1]:
NPM.iloc[i] = np.nan
else:
NPM.iloc[i] = np.sum(fund_data['net_inc_q'].iloc[i-3:i])/np.sum(fund_data['rev_q'].iloc[i-3:i])
# Return On Assets
ROA = pd.Series(np.empty(fund_data.shape[0],dtype=object),name='ROA')
for i in range(0, fund_data.shape[0]):
if i-3 < 0:
ROA[i] = np.nan
elif fund_data.iloc[i,1] != fund_data.iloc[i-3,1]:
ROA.iloc[i] = np.nan
else:
ROA.iloc[i] = np.sum(fund_data['net_inc_q'].iloc[i-3:i])/fund_data['tot_assets'].iloc[i]
# Return on Equity
ROE = pd.Series(np.empty(fund_data.shape[0],dtype=object),name='ROE')
for i in range(0, fund_data.shape[0]):
if i-3 < 0:
ROE[i] = np.nan
elif fund_data.iloc[i,1] != fund_data.iloc[i-3,1]:
ROE.iloc[i] = np.nan
else:
ROE.iloc[i] = np.sum(fund_data['net_inc_q'].iloc[i-3:i])/fund_data['sh_equity'].iloc[i]
# For calculating valuation ratios in the next subpart, calculate per share items in advance
# Earnings Per Share
EPS = fund_data['eps_incl_ex'].to_frame('EPS')
# Book Per Share
BPS = (fund_data['com_eq']/fund_data['sh_outstanding']).to_frame('BPS') # Need to check units
#Dividend Per Share
DPS = fund_data['div_per_sh'].to_frame('DPS')
# Liquidity ratios
# Current ratio
cur_ratio = (fund_data['cur_assets']/fund_data['cur_liabilities']).to_frame('cur_ratio')
# Quick ratio
quick_ratio = ((fund_data['cash_eq'] + fund_data['receivables'] )/fund_data['cur_liabilities']).to_frame('quick_ratio')
# Cash ratio
cash_ratio = (fund_data['cash_eq']/fund_data['cur_liabilities']).to_frame('cash_ratio')
# Efficiency ratios
# Inventory turnover ratio
inv_turnover = pd.Series(np.empty(fund_data.shape[0],dtype=object),name='inv_turnover')
for i in range(0, fund_data.shape[0]):
if i-3 < 0:
inv_turnover[i] = np.nan
elif fund_data.iloc[i,1] != fund_data.iloc[i-3,1]:
inv_turnover.iloc[i] = np.nan
else:
inv_turnover.iloc[i] = np.sum(fund_data['cogs_q'].iloc[i-3:i])/fund_data['inventories'].iloc[i]
# Receivables turnover ratio
acc_rec_turnover = pd.Series(np.empty(fund_data.shape[0],dtype=object),name='acc_rec_turnover')
for i in range(0, fund_data.shape[0]):
if i-3 < 0:
acc_rec_turnover[i] = np.nan
elif fund_data.iloc[i,1] != fund_data.iloc[i-3,1]:
acc_rec_turnover.iloc[i] = np.nan
else:
acc_rec_turnover.iloc[i] = np.sum(fund_data['rev_q'].iloc[i-3:i])/fund_data['receivables'].iloc[i]
# Payable turnover ratio
acc_pay_turnover = pd.Series(np.empty(fund_data.shape[0],dtype=object),name='acc_pay_turnover')
for i in range(0, fund_data.shape[0]):
if i-3 < 0:
acc_pay_turnover[i] = np.nan
elif fund_data.iloc[i,1] != fund_data.iloc[i-3,1]:
acc_pay_turnover.iloc[i] = np.nan
else:
acc_pay_turnover.iloc[i] = np.sum(fund_data['cogs_q'].iloc[i-3:i])/fund_data['payables'].iloc[i]
## Leverage financial ratios
# Debt ratio
debt_ratio = (fund_data['tot_liabilities']/fund_data['tot_assets']).to_frame('debt_ratio')
# Debt to Equity ratio
debt_to_equity = (fund_data['tot_liabilities']/fund_data['sh_equity']).to_frame('debt_to_equity')
# Create a dataframe that merges all the ratios
ratios = pd.concat([date,tic,OPM,NPM,ROA,ROE,EPS,BPS,DPS,
cur_ratio,quick_ratio,cash_ratio,inv_turnover,acc_rec_turnover,acc_pay_turnover,
debt_ratio,debt_to_equity], axis=1)
# Check the ratio data
ratios.head()
ratios.tail()
###Output
_____no_output_____
###Markdown
4-4 Deal with NAs and infinite values- We replace N/A and infinite values with zero so that they can be recognized as a state
###Code
# Replace NAs infinite values with zero
final_ratios = ratios.copy()
final_ratios = final_ratios.fillna(0)
final_ratios = final_ratios.replace(np.inf,0)
final_ratios.head()
final_ratios.tail()
###Output
_____no_output_____
###Markdown
4-5 Merge stock price data and ratios into one dataframe- Merge the price dataframe preprocessed in Part 3 and the ratio dataframe created in this part- Since the prices are daily and ratios are quartely, we have NAs in the ratio columns after merging the two dataframes. We deal with this by backfilling the ratios.
###Code
list_ticker = df["tic"].unique().tolist()
list_date = list(pd.date_range(df['date'].min(),df['date'].max()))
combination = list(itertools.product(list_date,list_ticker))
# Merge stock price data and ratios into one dataframe
processed_full = pd.DataFrame(combination,columns=["date","tic"]).merge(df,on=["date","tic"],how="left")
processed_full = processed_full.merge(final_ratios,how='left',on=['date','tic'])
processed_full = processed_full.sort_values(['tic','date'])
# Backfill the ratio data to make them daily
processed_full = processed_full.bfill(axis='rows')
###Output
_____no_output_____
###Markdown
4-6 Calculate market valuation ratios using daily stock price data
###Code
# Calculate P/E, P/B and dividend yield using daily closing price
processed_full['PE'] = processed_full['close']/processed_full['EPS']
processed_full['PB'] = processed_full['close']/processed_full['BPS']
processed_full['Div_yield'] = processed_full['DPS']/processed_full['close']
# Drop per share items used for the above calculation
processed_full = processed_full.drop(columns=['day','EPS','BPS','DPS'])
# Replace NAs infinite values with zero
processed_full = processed_full.copy()
processed_full = processed_full.fillna(0)
processed_full = processed_full.replace(np.inf,0)
# Check the final data
processed_full.sort_values(['date','tic'],ignore_index=True).head(10)
###Output
_____no_output_____
###Markdown
Part 5. Design EnvironmentConsidering the stochastic and interactive nature of the automated stock trading tasks, a financial task is modeled as a **Markov Decision Process (MDP)** problem. The training process involves observing stock price change, taking an action and reward's calculation to have the agent adjusting its strategy accordingly. By interacting with the environment, the trading agent will derive a trading strategy with the maximized rewards as time proceeds.Our trading environments, based on OpenAI Gym framework, simulate live stock markets with real market data according to the principle of time-driven simulation.The action space describes the allowed actions that the agent interacts with the environment. Normally, action a includes three actions: {-1, 0, 1}, where -1, 0, 1 represent selling, holding, and buying one share. Also, an action can be carried upon multiple shares. We use an action space {-k,…,-1, 0, 1, …, k}, where k denotes the number of shares to buy and -k denotes the number of shares to sell. For example, "Buy 10 shares of AAPL" or "Sell 10 shares of AAPL" are 10 or -10, respectively. The continuous action space needs to be normalized to [-1, 1], since the policy is defined on a Gaussian distribution, which needs to be normalized and symmetric. 5-1 Split data into training and trade dataset- Training data split: 2009-01-01 to 2018-12-31- Trade data split: 2019-01-01 to 2020-09-30
###Code
train = data_split(processed_full, '2009-01-01','2019-01-01')
trade = data_split(processed_full, '2019-01-01','2021-01-01')
# Check the length of the two datasets
print(len(train))
print(len(trade))
train.head()
trade.head()
###Output
_____no_output_____
###Markdown
5-2 Set up the training environment
###Code
import gym
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from gym import spaces
from gym.utils import seeding
from stable_baselines3.common.vec_env import DummyVecEnv
matplotlib.use("Agg")
# from stable_baselines3.common import logger
class StockTradingEnv(gym.Env):
"""A stock trading environment for OpenAI gym"""
metadata = {"render.modes": ["human"]}
def __init__(
self,
df,
stock_dim,
hmax,
initial_amount,
buy_cost_pct,
sell_cost_pct,
reward_scaling,
state_space,
action_space,
tech_indicator_list,
turbulence_threshold=None,
risk_indicator_col="turbulence",
make_plots=False,
print_verbosity=10,
day=0,
initial=True,
previous_state=[],
model_name="",
mode="",
iteration="",
):
self.day = day
self.df = df
self.stock_dim = stock_dim
self.hmax = hmax
self.initial_amount = initial_amount
self.buy_cost_pct = buy_cost_pct
self.sell_cost_pct = sell_cost_pct
self.reward_scaling = reward_scaling
self.state_space = state_space
self.action_space = action_space
self.tech_indicator_list = tech_indicator_list
self.action_space = spaces.Box(low=-1, high=1, shape=(self.action_space,))
self.observation_space = spaces.Box(
low=-np.inf, high=np.inf, shape=(self.state_space,)
)
self.data = self.df.loc[self.day, :]
self.terminal = False
self.make_plots = make_plots
self.print_verbosity = print_verbosity
self.turbulence_threshold = turbulence_threshold
self.risk_indicator_col = risk_indicator_col
self.initial = initial
self.previous_state = previous_state
self.model_name = model_name
self.mode = mode
self.iteration = iteration
# initalize state
self.state = self._initiate_state()
# initialize reward
self.reward = 0
self.turbulence = 0
self.cost = 0
self.trades = 0
self.episode = 0
# memorize all the total balance change
self.asset_memory = [self.initial_amount]
self.rewards_memory = []
self.actions_memory = []
self.date_memory = [self._get_date()]
# self.reset()
self._seed()
def _sell_stock(self, index, action):
def _do_sell_normal():
if self.state[index + 1] > 0:
# Sell only if the price is > 0 (no missing data in this particular date)
# perform sell action based on the sign of the action
if self.state[index + self.stock_dim + 1] > 0:
# Sell only if current asset is > 0
sell_num_shares = min(
abs(action), self.state[index + self.stock_dim + 1]
)
sell_amount = (
self.state[index + 1]
* sell_num_shares
* (1 - self.sell_cost_pct)
)
# update balance
self.state[0] += sell_amount
self.state[index + self.stock_dim + 1] -= sell_num_shares
self.cost += (
self.state[index + 1] * sell_num_shares * self.sell_cost_pct
)
self.trades += 1
else:
sell_num_shares = 0
else:
sell_num_shares = 0
return sell_num_shares
# perform sell action based on the sign of the action
if self.turbulence_threshold is not None:
if self.turbulence >= self.turbulence_threshold:
if self.state[index + 1] > 0:
# Sell only if the price is > 0 (no missing data in this particular date)
# if turbulence goes over threshold, just clear out all positions
if self.state[index + self.stock_dim + 1] > 0:
# Sell only if current asset is > 0
sell_num_shares = self.state[index + self.stock_dim + 1]
sell_amount = (
self.state[index + 1]
* sell_num_shares
* (1 - self.sell_cost_pct)
)
# update balance
self.state[0] += sell_amount
self.state[index + self.stock_dim + 1] = 0
self.cost += (
self.state[index + 1] * sell_num_shares * self.sell_cost_pct
)
self.trades += 1
else:
sell_num_shares = 0
else:
sell_num_shares = 0
else:
sell_num_shares = _do_sell_normal()
else:
sell_num_shares = _do_sell_normal()
return sell_num_shares
def _buy_stock(self, index, action):
def _do_buy():
if self.state[index + 1] > 0:
# Buy only if the price is > 0 (no missing data in this particular date)
available_amount = self.state[0] // self.state[index + 1]
# print('available_amount:{}'.format(available_amount))
# update balance
buy_num_shares = min(available_amount, action)
buy_amount = (
self.state[index + 1] * buy_num_shares * (1 + self.buy_cost_pct)
)
self.state[0] -= buy_amount
self.state[index + self.stock_dim + 1] += buy_num_shares
self.cost += self.state[index + 1] * buy_num_shares * self.buy_cost_pct
self.trades += 1
else:
buy_num_shares = 0
return buy_num_shares
# perform buy action based on the sign of the action
if self.turbulence_threshold is None:
buy_num_shares = _do_buy()
else:
if self.turbulence < self.turbulence_threshold:
buy_num_shares = _do_buy()
else:
buy_num_shares = 0
pass
return buy_num_shares
def _make_plot(self):
plt.plot(self.asset_memory, "r")
plt.savefig("results/account_value_trade_{}.png".format(self.episode))
plt.close()
def step(self, actions):
self.terminal = self.day >= len(self.df.index.unique()) - 1
if self.terminal:
# print(f"Episode: {self.episode}")
if self.make_plots:
self._make_plot()
end_total_asset = self.state[0] + sum(
np.array(self.state[1 : (self.stock_dim + 1)])
* np.array(self.state[(self.stock_dim + 1) : (self.stock_dim * 2 + 1)])
)
df_total_value = pd.DataFrame(self.asset_memory)
tot_reward = (
self.state[0]
+ sum(
np.array(self.state[1 : (self.stock_dim + 1)])
* np.array(
self.state[(self.stock_dim + 1) : (self.stock_dim * 2 + 1)]
)
)
- self.initial_amount
)
df_total_value.columns = ["account_value"]
df_total_value["date"] = self.date_memory
df_total_value["daily_return"] = df_total_value["account_value"].pct_change(
1
)
if df_total_value["daily_return"].std() != 0:
sharpe = (
(252 ** 0.5)
* df_total_value["daily_return"].mean()
/ df_total_value["daily_return"].std()
)
df_rewards = pd.DataFrame(self.rewards_memory)
df_rewards.columns = ["account_rewards"]
df_rewards["date"] = self.date_memory[:-1]
if self.episode % self.print_verbosity == 0:
print(f"day: {self.day}, episode: {self.episode}")
print(f"begin_total_asset: {self.asset_memory[0]:0.2f}")
print(f"end_total_asset: {end_total_asset:0.2f}")
print(f"total_reward: {tot_reward:0.2f}")
print(f"total_cost: {self.cost:0.2f}")
print(f"total_trades: {self.trades}")
if df_total_value["daily_return"].std() != 0:
print(f"Sharpe: {sharpe:0.3f}")
print("=================================")
if (self.model_name != "") and (self.mode != ""):
df_actions = self.save_action_memory()
df_actions.to_csv(
"results/actions_{}_{}_{}.csv".format(
self.mode, self.model_name, self.iteration
)
)
df_total_value.to_csv(
"results/account_value_{}_{}_{}.csv".format(
self.mode, self.model_name, self.iteration
),
index=False,
)
df_rewards.to_csv(
"results/account_rewards_{}_{}_{}.csv".format(
self.mode, self.model_name, self.iteration
),
index=False,
)
plt.plot(self.asset_memory, "r")
plt.savefig(
"results/account_value_{}_{}_{}.png".format(
self.mode, self.model_name, self.iteration
),
index=False,
)
plt.close()
# Add outputs to logger interface
# logger.record("environment/portfolio_value", end_total_asset)
# logger.record("environment/total_reward", tot_reward)
# logger.record("environment/total_reward_pct", (tot_reward / (end_total_asset - tot_reward)) * 100)
# logger.record("environment/total_cost", self.cost)
# logger.record("environment/total_trades", self.trades)
return self.state, self.reward, self.terminal, {}
else:
actions = actions * self.hmax # actions initially is scaled between 0 to 1
actions = actions.astype(
int
) # convert into integer because we can't by fraction of shares
if self.turbulence_threshold is not None:
if self.turbulence >= self.turbulence_threshold:
actions = np.array([-self.hmax] * self.stock_dim)
begin_total_asset = self.state[0] + sum(
np.array(self.state[1 : (self.stock_dim + 1)])
* np.array(self.state[(self.stock_dim + 1) : (self.stock_dim * 2 + 1)])
)
# print("begin_total_asset:{}".format(begin_total_asset))
argsort_actions = np.argsort(actions)
sell_index = argsort_actions[: np.where(actions < 0)[0].shape[0]]
buy_index = argsort_actions[::-1][: np.where(actions > 0)[0].shape[0]]
for index in sell_index:
# print(f"Num shares before: {self.state[index+self.stock_dim+1]}")
# print(f'take sell action before : {actions[index]}')
actions[index] = self._sell_stock(index, actions[index]) * (-1)
# print(f'take sell action after : {actions[index]}')
# print(f"Num shares after: {self.state[index+self.stock_dim+1]}")
for index in buy_index:
# print('take buy action: {}'.format(actions[index]))
actions[index] = self._buy_stock(index, actions[index])
self.actions_memory.append(actions)
# state: s -> s+1
self.day += 1
self.data = self.df.loc[self.day, :]
if self.turbulence_threshold is not None:
if len(self.df.tic.unique()) == 1:
self.turbulence = self.data[self.risk_indicator_col]
elif len(self.df.tic.unique()) > 1:
self.turbulence = self.data[self.risk_indicator_col].values[0]
self.state = self._update_state()
end_total_asset = self.state[0] + sum(
np.array(self.state[1 : (self.stock_dim + 1)])
* np.array(self.state[(self.stock_dim + 1) : (self.stock_dim * 2 + 1)])
)
self.asset_memory.append(end_total_asset)
self.date_memory.append(self._get_date())
self.reward = end_total_asset - begin_total_asset
self.rewards_memory.append(self.reward)
self.reward = self.reward * self.reward_scaling
return self.state, self.reward, self.terminal, {}
def reset(self):
# initiate state
self.state = self._initiate_state()
if self.initial:
self.asset_memory = [self.initial_amount]
else:
previous_total_asset = self.previous_state[0] + sum(
np.array(self.state[1 : (self.stock_dim + 1)])
* np.array(
self.previous_state[(self.stock_dim + 1) : (self.stock_dim * 2 + 1)]
)
)
self.asset_memory = [previous_total_asset]
self.day = 0
self.data = self.df.loc[self.day, :]
self.turbulence = 0
self.cost = 0
self.trades = 0
self.terminal = False
# self.iteration=self.iteration
self.rewards_memory = []
self.actions_memory = []
self.date_memory = [self._get_date()]
self.episode += 1
return self.state
def render(self, mode="human", close=False):
return self.state
def _initiate_state(self):
if self.initial:
# For Initial State
if len(self.df.tic.unique()) > 1:
# for multiple stock
state = (
[self.initial_amount]
+ self.data.close.values.tolist()
+ [0] * self.stock_dim
+ sum(
[
self.data[tech].values.tolist()
for tech in self.tech_indicator_list
],
[],
)
)
else:
# for single stock
state = (
[self.initial_amount]
+ [self.data.close]
+ [0] * self.stock_dim
+ sum([[self.data[tech]] for tech in self.tech_indicator_list], [])
)
else:
# Using Previous State
if len(self.df.tic.unique()) > 1:
# for multiple stock
state = (
[self.previous_state[0]]
+ self.data.close.values.tolist()
+ self.previous_state[
(self.stock_dim + 1) : (self.stock_dim * 2 + 1)
]
+ sum(
[
self.data[tech].values.tolist()
for tech in self.tech_indicator_list
],
[],
)
)
else:
# for single stock
state = (
[self.previous_state[0]]
+ [self.data.close]
+ self.previous_state[
(self.stock_dim + 1) : (self.stock_dim * 2 + 1)
]
+ sum([[self.data[tech]] for tech in self.tech_indicator_list], [])
)
return state
def _update_state(self):
if len(self.df.tic.unique()) > 1:
# for multiple stock
state = (
[self.state[0]]
+ self.data.close.values.tolist()
+ list(self.state[(self.stock_dim + 1) : (self.stock_dim * 2 + 1)])
+ sum(
[
self.data[tech].values.tolist()
for tech in self.tech_indicator_list
],
[],
)
)
else:
# for single stock
state = (
[self.state[0]]
+ [self.data.close]
+ list(self.state[(self.stock_dim + 1) : (self.stock_dim * 2 + 1)])
+ sum([[self.data[tech]] for tech in self.tech_indicator_list], [])
)
return state
def _get_date(self):
if len(self.df.tic.unique()) > 1:
date = self.data.date.unique()[0]
else:
date = self.data.date
return date
def save_asset_memory(self):
date_list = self.date_memory
asset_list = self.asset_memory
# print(len(date_list))
# print(len(asset_list))
df_account_value = pd.DataFrame(
{"date": date_list, "account_value": asset_list}
)
return df_account_value
def save_action_memory(self):
if len(self.df.tic.unique()) > 1:
# date and close price length must match actions length
date_list = self.date_memory[:-1]
df_date = pd.DataFrame(date_list)
df_date.columns = ["date"]
action_list = self.actions_memory
df_actions = pd.DataFrame(action_list)
df_actions.columns = self.data.tic.values
df_actions.index = df_date.date
# df_actions = pd.DataFrame({'date':date_list,'actions':action_list})
else:
date_list = self.date_memory[:-1]
action_list = self.actions_memory
df_actions = pd.DataFrame({"date": date_list, "actions": action_list})
return df_actions
def _seed(self, seed=None):
self.np_random, seed = seeding.np_random(seed)
return [seed]
def get_sb_env(self):
e = DummyVecEnv([lambda: self])
obs = e.reset()
return e, obs
ratio_list = ['OPM', 'NPM','ROA', 'ROE', 'cur_ratio', 'quick_ratio', 'cash_ratio', 'inv_turnover','acc_rec_turnover', 'acc_pay_turnover', 'debt_ratio', 'debt_to_equity',
'PE', 'PB', 'Div_yield']
stock_dimension = len(train.tic.unique())
state_space = 1 + 2*stock_dimension + len(ratio_list)*stock_dimension
print(f"Stock Dimension: {stock_dimension}, State Space: {state_space}")
# Parameters for the environment
env_kwargs = {
"hmax": 100,
"initial_amount": 1000000,
"buy_cost_pct": 0.001,
"sell_cost_pct": 0.001,
"state_space": state_space,
"stock_dim": stock_dimension,
"tech_indicator_list": ratio_list,
"action_space": stock_dimension,
"reward_scaling": 1e-4
}
#Establish the training environment using StockTradingEnv() class
e_train_gym = StockTradingEnv(df = train, **env_kwargs)
###Output
_____no_output_____
###Markdown
Environment for Training
###Code
env_train, _ = e_train_gym.get_sb_env()
print(type(env_train))
###Output
<class 'stable_baselines3.common.vec_env.dummy_vec_env.DummyVecEnv'>
###Markdown
Part 6: Implement DRL Algorithms* The implementation of the DRL algorithms are based on **OpenAI Baselines** and **Stable Baselines**. Stable Baselines is a fork of OpenAI Baselines, with a major structural refactoring, and code cleanups.* FinRL library includes fine-tuned standard DRL algorithms, such as DQN, DDPG,Multi-Agent DDPG, PPO, SAC, A2C and TD3. We also allow users todesign their own DRL algorithms by adapting these DRL algorithms.
###Code
# Set up the agent using DRLAgent() class using the environment created in the previous part
agent = DRLAgent(env = env_train)
###Output
_____no_output_____
###Markdown
Model Training: 5 models, A2C DDPG, PPO, TD3, SAC Model 1: A2C
###Code
agent = DRLAgent(env = env_train)
model_a2c = agent.get_model("a2c")
trained_a2c = agent.train_model(model=model_a2c,
tb_log_name='a2c',
total_timesteps=100000)
###Output
-----------------------------------------
| time/ | |
| fps | 85 |
| iterations | 100 |
| time_elapsed | 5 |
| total_timesteps | 500 |
| train/ | |
| entropy_loss | -42.7 |
| explained_variance | 0.00025 |
| learning_rate | 0.0007 |
| n_updates | 99 |
| policy_loss | 72.9 |
| reward | -0.0017323004 |
| std | 1 |
| value_loss | 5 |
-----------------------------------------
-------------------------------------
| time/ | |
| fps | 86 |
| iterations | 200 |
| time_elapsed | 11 |
| total_timesteps | 1000 |
| train/ | |
| entropy_loss | -42.7 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 199 |
| policy_loss | 33.4 |
| reward | 1.0503633 |
| std | 1 |
| value_loss | 4.55 |
-------------------------------------
-----------------------------------------
| time/ | |
| fps | 87 |
| iterations | 300 |
| time_elapsed | 17 |
| total_timesteps | 1500 |
| train/ | |
| entropy_loss | -42.7 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 299 |
| policy_loss | 19.1 |
| reward | -0.0030366322 |
| std | 1.01 |
| value_loss | 0.988 |
-----------------------------------------
-------------------------------------
| time/ | |
| fps | 87 |
| iterations | 400 |
| time_elapsed | 22 |
| total_timesteps | 2000 |
| train/ | |
| entropy_loss | -42.8 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 399 |
| policy_loss | 29.4 |
| reward | 1.5995015 |
| std | 1.01 |
| value_loss | 1.41 |
-------------------------------------
###Markdown
Model 2: DDPG
###Code
agent = DRLAgent(env = env_train)
model_ddpg = agent.get_model("ddpg")
trained_ddpg = agent.train_model(model=model_ddpg,
tb_log_name='ddpg',
total_timesteps=50000)
###Output
_____no_output_____
###Markdown
Model 3: PPO
###Code
agent = DRLAgent(env = env_train)
PPO_PARAMS = {
"n_steps": 2048,
"ent_coef": 0.01,
"learning_rate": 0.00025,
"batch_size": 128,
}
model_ppo = agent.get_model("ppo",model_kwargs = PPO_PARAMS)
trained_ppo = agent.train_model(model=model_ppo,
tb_log_name='ppo',
total_timesteps=50000)
###Output
_____no_output_____
###Markdown
Model 4: TD3
###Code
agent = DRLAgent(env = env_train)
TD3_PARAMS = {"batch_size": 100,
"buffer_size": 1000000,
"learning_rate": 0.001}
model_td3 = agent.get_model("td3",model_kwargs = TD3_PARAMS)
trained_td3 = agent.train_model(model=model_td3,
tb_log_name='td3',
total_timesteps=30000)
###Output
_____no_output_____
###Markdown
Model 5: SAC
###Code
agent = DRLAgent(env = env_train)
SAC_PARAMS = {
"batch_size": 128,
"buffer_size": 1000000,
"learning_rate": 0.0001,
"learning_starts": 100,
"ent_coef": "auto_0.1",
}
model_sac = agent.get_model("sac",model_kwargs = SAC_PARAMS)
trained_sac = agent.train_model(model=model_sac,
tb_log_name='sac',
total_timesteps=80000)
###Output
_____no_output_____
###Markdown
TradingAssume that we have $1,000,000 initial capital at 2019-01-01. We use the DDPG model to trade Dow jones 30 stocks. TradeDRL model needs to update periodically in order to take full advantage of the data, ideally we need to retrain our model yearly, quarterly, or monthly. We also need to tune the parameters along the way, in this notebook I only use the in-sample data from 2009-01 to 2018-12 to tune the parameters once, so there is some alpha decay here as the length of trade date extends. Numerous hyperparameters – e.g. the learning rate, the total number of samples to train on – influence the learning process and are usually determined by testing some variations.
###Code
trade = data_split(processed_full, '2019-01-01','2021-01-01')
e_trade_gym = StockTradingEnv(df = trade, **env_kwargs)
# env_trade, obs_trade = e_trade_gym.get_sb_env()
trade.head()
df_account_value, df_actions = DRLAgent.DRL_prediction(
model=trained_ddpg,
environment = e_trade_gym)
df_account_value.shape
df_account_value.tail()
df_actions.head()
###Output
_____no_output_____
###Markdown
Part 7: Backtest Our StrategyBacktesting plays a key role in evaluating the performance of a trading strategy. Automated backtesting tool is preferred because it reduces the human error. We usually use the Quantopian pyfolio package to backtest our trading strategies. It is easy to use and consists of various individual plots that provide a comprehensive image of the performance of a trading strategy. 7.1 BackTestStatspass in df_account_value, this information is stored in env class
###Code
print("==============Get Backtest Results===========")
now = datetime.datetime.now().strftime('%Y%m%d-%Hh%M')
perf_stats_all = backtest_stats(account_value=df_account_value)
perf_stats_all = pd.DataFrame(perf_stats_all)
perf_stats_all.to_csv("./"+config.RESULTS_DIR+"/perf_stats_all_"+now+'.csv')
#baseline stats
print("==============Get Baseline Stats===========")
baseline_df = get_baseline(
ticker="^DJI",
start = '2019-01-01',
end = '2021-01-01')
stats = backtest_stats(baseline_df, value_col_name = 'close')
###Output
_____no_output_____
###Markdown
7.2 BackTestPlot
###Code
print("==============Compare to DJIA===========")
%matplotlib inline
# S&P 500: ^GSPC
# Dow Jones Index: ^DJI
# NASDAQ 100: ^NDX
backtest_plot(df_account_value,
baseline_ticker = '^DJI',
baseline_start = '2019-01-01',
baseline_end = '2021-01-01')
###Output
_____no_output_____
###Markdown
Automated stock trading using FinRL with financial dataTrained a Deep Reinforcement Learning model using FinRL and companies' financial ratio, and then backtested the model to examine how well-trained the model is* This Google Colabolatory notebook is based on the tutorial of FinRL: https://towardsdatascience.com/finrl-for-quantitative-finance-tutorial-for-multiple-stock-trading-7b00763b7530* This project is a final project of the almuni-mentored research project at Columbia University, Application of Reinforcement Learning to Finance, mentored by Bruce Yang from AI4Finance.* For more detailed explanation, please check out my Medium post: https://medium.com/@mariko.sawada1/automated-stock-trading-with-deep-reinforcement-learning-and-financial-data-a63286ccbe2b Content * [1. Problem Definition](0)* [2. Getting Started - Load Python packages](1) * [2.1. Install Packages](1.1) * [2.2. Check Additional Packages](1.2) * [2.3. Import Packages](1.3) * [2.4. Create Folders](1.4)* [3. Download Data](2)* [4. Preprocess fundamental Data](3) * [4-1 Import financial data](3.1) * [4-2 Specify items needed to calculate financial ratios](3.2) * [4-3 Calculate financial ratios](3.3) * [4-4 Deal with NAs and infinite values](3.4) * [4-5 Merge stock price data and ratios into one dataframe](3.5) * [4-6 Calculate market valuation ratios using daily stock price data](3.6)* [5.Build Environment](4) * [5.1. Training & Trade Data Split](4.1) * [5.2. User-defined Environment](4.2) * [5.3. Initialize Environment](4.3) * [6.Implement DRL Algorithms](5) * [7.Backtesting Performance](6) * [7.1. BackTestStats](6.1) * [7.2. BackTestPlot](6.2) * [7.3. Baseline Stats](6.3) * [7.3. Compare to Stock Market Index](6.4) Part 1. Problem Definition This problem is to design an automated trading solution for single stock trading. We model the stock trading process as a Markov Decision Process (MDP). We then formulate our trading goal as a maximization problem.The algorithm is trained using Deep Reinforcement Learning (DRL) algorithms and the components of the reinforcement learning environment are:* Action: The action space describes the allowed actions that the agent interacts with theenvironment. Normally, a ∈ A includes three actions: a ∈ {−1, 0, 1}, where −1, 0, 1 representselling, holding, and buying one stock. Also, an action can be carried upon multiple shares. We usean action space {−k, ..., −1, 0, 1, ..., k}, where k denotes the number of shares. For example, "Buy10 shares of AAPL" or "Sell 10 shares of AAPL" are 10 or −10, respectively* Reward function: r(s, a, s′) is the incentive mechanism for an agent to learn a better action. The change of the portfolio value when action a is taken at state s and arriving at new state s', i.e., r(s, a, s′) = v′ − v, where v′ and v represent the portfoliovalues at state s′ and s, respectively* State: The state space describes the observations that the agent receives from the environment. Just as a human trader needs to analyze various information before executing a trade, soour trading agent observes many different features to better learn in an interactive environment.* Environment: Dow 30 consituentsThe data of the single stock that we will be using for this case study is obtained from Yahoo Finance API. The data contains Open-High-Low-Close price and volume. Part 2. Load Python Packages 2.1. Install all the packages through FinRL library
###Code
## install finrl library
!pip install git+https://github.com/AI4Finance-LLC/FinRL-Library.git
###Output
Collecting git+https://github.com/AI4Finance-LLC/FinRL-Library.git
Cloning https://github.com/AI4Finance-LLC/FinRL-Library.git to /tmp/pip-req-build-sh40mnb8
Running command git clone -q https://github.com/AI4Finance-LLC/FinRL-Library.git /tmp/pip-req-build-sh40mnb8
Collecting pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2
Cloning https://github.com/quantopian/pyfolio.git to /tmp/pip-install-djvoe7ii/pyfolio_43f26b0cfe004ec394108e8d73166b45
Running command git clone -q https://github.com/quantopian/pyfolio.git /tmp/pip-install-djvoe7ii/pyfolio_43f26b0cfe004ec394108e8d73166b45
Requirement already satisfied: numpy>=1.17.3 in /usr/local/lib/python3.7/dist-packages (from finrl==0.3.0) (1.19.5)
Requirement already satisfied: pandas>=1.1.5 in /usr/local/lib/python3.7/dist-packages (from finrl==0.3.0) (1.1.5)
Requirement already satisfied: stockstats in /usr/local/lib/python3.7/dist-packages (from finrl==0.3.0) (0.3.2)
Requirement already satisfied: yfinance in /usr/local/lib/python3.7/dist-packages (from finrl==0.3.0) (0.1.63)
Requirement already satisfied: matplotlib in /usr/local/lib/python3.7/dist-packages (from finrl==0.3.0) (3.2.2)
Requirement already satisfied: scikit-learn>=0.21.0 in /usr/local/lib/python3.7/dist-packages (from finrl==0.3.0) (0.22.2.post1)
Requirement already satisfied: gym>=0.17 in /usr/local/lib/python3.7/dist-packages (from finrl==0.3.0) (0.17.3)
Requirement already satisfied: stable-baselines3[extra] in /usr/local/lib/python3.7/dist-packages (from finrl==0.3.0) (1.1.0)
Requirement already satisfied: pytest in /usr/local/lib/python3.7/dist-packages (from finrl==0.3.0) (3.6.4)
Requirement already satisfied: setuptools>=41.4.0 in /usr/local/lib/python3.7/dist-packages (from finrl==0.3.0) (57.4.0)
Requirement already satisfied: wheel>=0.33.6 in /usr/local/lib/python3.7/dist-packages (from finrl==0.3.0) (0.37.0)
Requirement already satisfied: ipython>=3.2.3 in /usr/local/lib/python3.7/dist-packages (from pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (5.5.0)
Requirement already satisfied: pytz>=2014.10 in /usr/local/lib/python3.7/dist-packages (from pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (2018.9)
Requirement already satisfied: scipy>=0.14.0 in /usr/local/lib/python3.7/dist-packages (from pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (1.4.1)
Requirement already satisfied: seaborn>=0.7.1 in /usr/local/lib/python3.7/dist-packages (from pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (0.11.1)
Requirement already satisfied: empyrical>=0.5.0 in /usr/local/lib/python3.7/dist-packages (from pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (0.5.5)
Requirement already satisfied: pandas-datareader>=0.2 in /usr/local/lib/python3.7/dist-packages (from empyrical>=0.5.0->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (0.9.0)
Requirement already satisfied: cloudpickle<1.7.0,>=1.2.0 in /usr/local/lib/python3.7/dist-packages (from gym>=0.17->finrl==0.3.0) (1.3.0)
Requirement already satisfied: pyglet<=1.5.0,>=1.4.0 in /usr/local/lib/python3.7/dist-packages (from gym>=0.17->finrl==0.3.0) (1.5.0)
Requirement already satisfied: decorator in /usr/local/lib/python3.7/dist-packages (from ipython>=3.2.3->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (4.4.2)
Requirement already satisfied: pexpect in /usr/local/lib/python3.7/dist-packages (from ipython>=3.2.3->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (4.8.0)
Requirement already satisfied: simplegeneric>0.8 in /usr/local/lib/python3.7/dist-packages (from ipython>=3.2.3->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (0.8.1)
Requirement already satisfied: prompt-toolkit<2.0.0,>=1.0.4 in /usr/local/lib/python3.7/dist-packages (from ipython>=3.2.3->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (1.0.18)
Requirement already satisfied: pygments in /usr/local/lib/python3.7/dist-packages (from ipython>=3.2.3->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (2.6.1)
Requirement already satisfied: traitlets>=4.2 in /usr/local/lib/python3.7/dist-packages (from ipython>=3.2.3->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (5.0.5)
Requirement already satisfied: pickleshare in /usr/local/lib/python3.7/dist-packages (from ipython>=3.2.3->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (0.7.5)
Requirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->finrl==0.3.0) (2.8.2)
Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->finrl==0.3.0) (1.3.1)
Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.7/dist-packages (from matplotlib->finrl==0.3.0) (0.10.0)
Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.7/dist-packages (from matplotlib->finrl==0.3.0) (2.4.7)
Requirement already satisfied: six in /usr/local/lib/python3.7/dist-packages (from cycler>=0.10->matplotlib->finrl==0.3.0) (1.15.0)
Requirement already satisfied: requests>=2.19.0 in /usr/local/lib/python3.7/dist-packages (from pandas-datareader>=0.2->empyrical>=0.5.0->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (2.23.0)
Requirement already satisfied: lxml in /usr/local/lib/python3.7/dist-packages (from pandas-datareader>=0.2->empyrical>=0.5.0->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (4.6.3)
Requirement already satisfied: wcwidth in /usr/local/lib/python3.7/dist-packages (from prompt-toolkit<2.0.0,>=1.0.4->ipython>=3.2.3->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (0.2.5)
Requirement already satisfied: future in /usr/local/lib/python3.7/dist-packages (from pyglet<=1.5.0,>=1.4.0->gym>=0.17->finrl==0.3.0) (0.16.0)
Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19.0->pandas-datareader>=0.2->empyrical>=0.5.0->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (2.10)
Requirement already satisfied: certifi>=2017.4.17 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19.0->pandas-datareader>=0.2->empyrical>=0.5.0->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (2021.5.30)
Requirement already satisfied: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19.0->pandas-datareader>=0.2->empyrical>=0.5.0->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (1.24.3)
Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.7/dist-packages (from requests>=2.19.0->pandas-datareader>=0.2->empyrical>=0.5.0->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (3.0.4)
Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.7/dist-packages (from scikit-learn>=0.21.0->finrl==0.3.0) (1.0.1)
Requirement already satisfied: ipython-genutils in /usr/local/lib/python3.7/dist-packages (from traitlets>=4.2->ipython>=3.2.3->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (0.2.0)
Requirement already satisfied: ptyprocess>=0.5 in /usr/local/lib/python3.7/dist-packages (from pexpect->ipython>=3.2.3->pyfolio@ git+https://github.com/quantopian/pyfolio.git#egg=pyfolio-0.9.2->finrl==0.3.0) (0.7.0)
Requirement already satisfied: more-itertools>=4.0.0 in /usr/local/lib/python3.7/dist-packages (from pytest->finrl==0.3.0) (8.8.0)
Requirement already satisfied: attrs>=17.4.0 in /usr/local/lib/python3.7/dist-packages (from pytest->finrl==0.3.0) (21.2.0)
Requirement already satisfied: atomicwrites>=1.0 in /usr/local/lib/python3.7/dist-packages (from pytest->finrl==0.3.0) (1.4.0)
Requirement already satisfied: py>=1.5.0 in /usr/local/lib/python3.7/dist-packages (from pytest->finrl==0.3.0) (1.10.0)
Requirement already satisfied: pluggy<0.8,>=0.5 in /usr/local/lib/python3.7/dist-packages (from pytest->finrl==0.3.0) (0.7.1)
Requirement already satisfied: torch>=1.4.0 in /usr/local/lib/python3.7/dist-packages (from stable-baselines3[extra]->finrl==0.3.0) (1.9.0+cu102)
Requirement already satisfied: pillow in /usr/local/lib/python3.7/dist-packages (from stable-baselines3[extra]->finrl==0.3.0) (7.1.2)
Requirement already satisfied: opencv-python in /usr/local/lib/python3.7/dist-packages (from stable-baselines3[extra]->finrl==0.3.0) (4.1.2.30)
Requirement already satisfied: atari-py~=0.2.0 in /usr/local/lib/python3.7/dist-packages (from stable-baselines3[extra]->finrl==0.3.0) (0.2.9)
Requirement already satisfied: psutil in /usr/local/lib/python3.7/dist-packages (from stable-baselines3[extra]->finrl==0.3.0) (5.4.8)
Requirement already satisfied: tensorboard>=2.2.0 in /usr/local/lib/python3.7/dist-packages (from stable-baselines3[extra]->finrl==0.3.0) (2.5.0)
Requirement already satisfied: protobuf>=3.6.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.0) (3.17.3)
Requirement already satisfied: grpcio>=1.24.3 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.0) (1.34.1)
Requirement already satisfied: werkzeug>=0.11.15 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.0) (1.0.1)
Requirement already satisfied: absl-py>=0.4 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.0) (0.12.0)
Requirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.0) (3.3.4)
Requirement already satisfied: tensorboard-data-server<0.7.0,>=0.6.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.0) (0.6.1)
Requirement already satisfied: google-auth<2,>=1.6.3 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.0) (1.34.0)
Requirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.0) (0.4.5)
Requirement already satisfied: tensorboard-plugin-wit>=1.6.0 in /usr/local/lib/python3.7/dist-packages (from tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.0) (1.8.0)
Requirement already satisfied: rsa<5,>=3.1.4 in /usr/local/lib/python3.7/dist-packages (from google-auth<2,>=1.6.3->tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.0) (4.7.2)
Requirement already satisfied: cachetools<5.0,>=2.0.0 in /usr/local/lib/python3.7/dist-packages (from google-auth<2,>=1.6.3->tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.0) (4.2.2)
Requirement already satisfied: pyasn1-modules>=0.2.1 in /usr/local/lib/python3.7/dist-packages (from google-auth<2,>=1.6.3->tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.0) (0.2.8)
Requirement already satisfied: requests-oauthlib>=0.7.0 in /usr/local/lib/python3.7/dist-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.0) (1.3.0)
Requirement already satisfied: importlib-metadata in /usr/local/lib/python3.7/dist-packages (from markdown>=2.6.8->tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.0) (4.6.3)
Requirement already satisfied: pyasn1<0.5.0,>=0.4.6 in /usr/local/lib/python3.7/dist-packages (from pyasn1-modules>=0.2.1->google-auth<2,>=1.6.3->tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.0) (0.4.8)
Requirement already satisfied: oauthlib>=3.0.0 in /usr/local/lib/python3.7/dist-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.0) (3.1.1)
Requirement already satisfied: typing-extensions in /usr/local/lib/python3.7/dist-packages (from torch>=1.4.0->stable-baselines3[extra]->finrl==0.3.0) (3.7.4.3)
Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.7/dist-packages (from importlib-metadata->markdown>=2.6.8->tensorboard>=2.2.0->stable-baselines3[extra]->finrl==0.3.0) (3.5.0)
Requirement already satisfied: int-date>=0.1.7 in /usr/local/lib/python3.7/dist-packages (from stockstats->finrl==0.3.0) (0.1.8)
Requirement already satisfied: multitasking>=0.0.7 in /usr/local/lib/python3.7/dist-packages (from yfinance->finrl==0.3.0) (0.0.9)
###Markdown
2.2. Check if the additional packages needed are present, if not install them. * Yahoo Finance API* pandas* numpy* matplotlib* stockstats* OpenAI gym* stable-baselines* tensorflow* pyfolio 2.3. Import Packages
###Code
import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
# matplotlib.use('Agg')
import datetime
%matplotlib inline
from finrl.apps import config
from finrl.neo_finrl.preprocessor.yahoodownloader import YahooDownloader
from finrl.neo_finrl.preprocessor.preprocessors import FeatureEngineer, data_split
from finrl.neo_finrl.env_stock_trading.env_stocktrading import StockTradingEnv
from finrl.drl_agents.stablebaselines3.models import DRLAgent
from finrl.plot import backtest_stats, backtest_plot, get_daily_return, get_baseline
from pprint import pprint
import sys
sys.path.append("../FinRL-Library")
import itertools
###Output
_____no_output_____
###Markdown
2.4. Create Folders
###Code
import os
if not os.path.exists("./" + config.DATA_SAVE_DIR):
os.makedirs("./" + config.DATA_SAVE_DIR)
if not os.path.exists("./" + config.TRAINED_MODEL_DIR):
os.makedirs("./" + config.TRAINED_MODEL_DIR)
if not os.path.exists("./" + config.TENSORBOARD_LOG_DIR):
os.makedirs("./" + config.TENSORBOARD_LOG_DIR)
if not os.path.exists("./" + config.RESULTS_DIR):
os.makedirs("./" + config.RESULTS_DIR)
###Output
_____no_output_____
###Markdown
Part 3. Download Stock Data from Yahoo FinanceYahoo Finance is a website that provides stock data, financial news, financial reports, etc. All the data provided by Yahoo Finance is free.* FinRL uses a class **YahooDownloader** to fetch data from Yahoo Finance API* Call Limit: Using the Public API (without authentication), you are limited to 2,000 requests per hour per IP (or up to a total of 48,000 requests a day). -----class YahooDownloader: Provides methods for retrieving daily stock data from Yahoo Finance API Attributes ---------- start_date : str start date of the data (modified from config.py) end_date : str end date of the data (modified from config.py) ticker_list : list a list of stock tickers (modified from config.py) Methods ------- fetch_data() Fetches data from yahoo API
###Code
# from config.py start_date is a string
config.START_DATE
# from config.py end_date is a string
config.END_DATE
print(config.DOW_30_TICKER)
df = YahooDownloader(start_date = '2009-01-01',
end_date = '2021-01-01',
ticker_list = config.DOW_30_TICKER).fetch_data()
df.shape
df.head()
df['date'] = pd.to_datetime(df['date'],format='%Y-%m-%d')
df.sort_values(['date','tic'],ignore_index=True).head()
###Output
_____no_output_____
###Markdown
Part 4: Preprocess fundamental data- Import finanical data downloaded from Compustat via WRDS(Wharton Research Data Service)- Preprocess the dataset and calculate financial ratios- Add those ratios to the price data preprocessed in Part 3- Calculate price-related ratios such as P/E and P/B 4-1 Import the financial data
###Code
# Import fundamental data from my GitHub repository
url = 'https://raw.githubusercontent.com/mariko-sawada/FinRL_with_fundamental_data/main/dow_30_fundamental_wrds.csv'
fund = pd.read_csv(url)
# Check the imported dataset
fund.head()
###Output
_____no_output_____
###Markdown
4-2 Specify items needed to calculate financial ratios- To know more about the data description of the dataset, please check WRDS's website(https://wrds-www.wharton.upenn.edu/). Login will be required.
###Code
# List items that are used to calculate financial ratios
items = [
'datadate', # Date
'tic', # Ticker
'oiadpq', # Quarterly operating income
'revtq', # Quartely revenue
'niq', # Quartely net income
'atq', # Total asset
'teqq', # Shareholder's equity
'epspiy', # EPS(Basic) incl. Extraordinary items
'ceqq', # Common Equity
'cshoq', # Common Shares Outstanding
'dvpspq', # Dividends per share
'actq', # Current assets
'lctq', # Current liabilities
'cheq', # Cash & Equivalent
'rectq', # Recievalbles
'cogsq', # Cost of Goods Sold
'invtq', # Inventories
'apq',# Account payable
'dlttq', # Long term debt
'dlcq', # Debt in current liabilites
'ltq' # Liabilities
]
# Omit items that will not be used
fund_data = fund[items]
# Rename column names for the sake of readability
fund_data = fund_data.rename(columns={
'datadate':'date', # Date
'oiadpq':'op_inc_q', # Quarterly operating income
'revtq':'rev_q', # Quartely revenue
'niq':'net_inc_q', # Quartely net income
'atq':'tot_assets', # Assets
'teqq':'sh_equity', # Shareholder's equity
'epspiy':'eps_incl_ex', # EPS(Basic) incl. Extraordinary items
'ceqq':'com_eq', # Common Equity
'cshoq':'sh_outstanding', # Common Shares Outstanding
'dvpspq':'div_per_sh', # Dividends per share
'actq':'cur_assets', # Current assets
'lctq':'cur_liabilities', # Current liabilities
'cheq':'cash_eq', # Cash & Equivalent
'rectq':'receivables', # Receivalbles
'cogsq':'cogs_q', # Cost of Goods Sold
'invtq':'inventories', # Inventories
'apq': 'payables',# Account payable
'dlttq':'long_debt', # Long term debt
'dlcq':'short_debt', # Debt in current liabilites
'ltq':'tot_liabilities' # Liabilities
})
# Check the data
fund_data.head()
###Output
_____no_output_____
###Markdown
4-3 Calculate financial ratios- For items from Profit/Loss statements, we calculate LTM (Last Twelve Months) and use them to derive profitability related ratios such as Operating Maring and ROE. For items from balance sheets, we use the numbers on the day.- To check the definitions of the financial ratios calculated here, please refer to CFI's website: https://corporatefinanceinstitute.com/resources/knowledge/finance/financial-ratios/
###Code
# Calculate financial ratios
date = pd.to_datetime(fund_data['date'],format='%Y%m%d')
tic = fund_data['tic'].to_frame('tic')
# Profitability ratios
# Operating Margin
OPM = pd.Series(np.empty(fund_data.shape[0],dtype=object),name='OPM')
for i in range(0, fund_data.shape[0]):
if i-3 < 0:
OPM[i] = np.nan
elif fund_data.iloc[i,1] != fund_data.iloc[i-3,1]:
OPM.iloc[i] = np.nan
else:
OPM.iloc[i] = np.sum(fund_data['op_inc_q'].iloc[i-3:i])/np.sum(fund_data['rev_q'].iloc[i-3:i])
# Net Profit Margin
NPM = pd.Series(np.empty(fund_data.shape[0],dtype=object),name='NPM')
for i in range(0, fund_data.shape[0]):
if i-3 < 0:
NPM[i] = np.nan
elif fund_data.iloc[i,1] != fund_data.iloc[i-3,1]:
NPM.iloc[i] = np.nan
else:
NPM.iloc[i] = np.sum(fund_data['net_inc_q'].iloc[i-3:i])/np.sum(fund_data['rev_q'].iloc[i-3:i])
# Return On Assets
ROA = pd.Series(np.empty(fund_data.shape[0],dtype=object),name='ROA')
for i in range(0, fund_data.shape[0]):
if i-3 < 0:
ROA[i] = np.nan
elif fund_data.iloc[i,1] != fund_data.iloc[i-3,1]:
ROA.iloc[i] = np.nan
else:
ROA.iloc[i] = np.sum(fund_data['net_inc_q'].iloc[i-3:i])/fund_data['tot_assets'].iloc[i]
# Return on Equity
ROE = pd.Series(np.empty(fund_data.shape[0],dtype=object),name='ROE')
for i in range(0, fund_data.shape[0]):
if i-3 < 0:
ROE[i] = np.nan
elif fund_data.iloc[i,1] != fund_data.iloc[i-3,1]:
ROE.iloc[i] = np.nan
else:
ROE.iloc[i] = np.sum(fund_data['net_inc_q'].iloc[i-3:i])/fund_data['sh_equity'].iloc[i]
# For calculating valuation ratios in the next subpart, calculate per share items in advance
# Earnings Per Share
EPS = fund_data['eps_incl_ex'].to_frame('EPS')
# Book Per Share
BPS = (fund_data['com_eq']/fund_data['sh_outstanding']).to_frame('BPS') # Need to check units
#Dividend Per Share
DPS = fund_data['div_per_sh'].to_frame('DPS')
# Liquidity ratios
# Current ratio
cur_ratio = (fund_data['cur_assets']/fund_data['cur_liabilities']).to_frame('cur_ratio')
# Quick ratio
quick_ratio = ((fund_data['cash_eq'] + fund_data['receivables'] )/fund_data['cur_liabilities']).to_frame('quick_ratio')
# Cash ratio
cash_ratio = (fund_data['cash_eq']/fund_data['cur_liabilities']).to_frame('cash_ratio')
# Efficiency ratios
# Inventory turnover ratio
inv_turnover = pd.Series(np.empty(fund_data.shape[0],dtype=object),name='inv_turnover')
for i in range(0, fund_data.shape[0]):
if i-3 < 0:
inv_turnover[i] = np.nan
elif fund_data.iloc[i,1] != fund_data.iloc[i-3,1]:
inv_turnover.iloc[i] = np.nan
else:
inv_turnover.iloc[i] = np.sum(fund_data['cogs_q'].iloc[i-3:i])/fund_data['inventories'].iloc[i]
# Receivables turnover ratio
acc_rec_turnover = pd.Series(np.empty(fund_data.shape[0],dtype=object),name='acc_rec_turnover')
for i in range(0, fund_data.shape[0]):
if i-3 < 0:
acc_rec_turnover[i] = np.nan
elif fund_data.iloc[i,1] != fund_data.iloc[i-3,1]:
acc_rec_turnover.iloc[i] = np.nan
else:
acc_rec_turnover.iloc[i] = np.sum(fund_data['rev_q'].iloc[i-3:i])/fund_data['receivables'].iloc[i]
# Payable turnover ratio
acc_pay_turnover = pd.Series(np.empty(fund_data.shape[0],dtype=object),name='acc_pay_turnover')
for i in range(0, fund_data.shape[0]):
if i-3 < 0:
acc_pay_turnover[i] = np.nan
elif fund_data.iloc[i,1] != fund_data.iloc[i-3,1]:
acc_pay_turnover.iloc[i] = np.nan
else:
acc_pay_turnover.iloc[i] = np.sum(fund_data['cogs_q'].iloc[i-3:i])/fund_data['payables'].iloc[i]
## Leverage financial ratios
# Debt ratio
debt_ratio = (fund_data['tot_liabilities']/fund_data['tot_assets']).to_frame('debt_ratio')
# Debt to Equity ratio
debt_to_equity = (fund_data['tot_liabilities']/fund_data['sh_equity']).to_frame('debt_to_equity')
# Create a dataframe that merges all the ratios
ratios = pd.concat([date,tic,OPM,NPM,ROA,ROE,EPS,BPS,DPS,
cur_ratio,quick_ratio,cash_ratio,inv_turnover,acc_rec_turnover,acc_pay_turnover,
debt_ratio,debt_to_equity], axis=1)
# Check the ratio data
ratios.head()
ratios.tail()
###Output
_____no_output_____
###Markdown
4-4 Deal with NAs and infinite values- We replace N/A and infinite values with zero so that they can be recognized as a state
###Code
# Replace NAs infinite values with zero
final_ratios = ratios.copy()
final_ratios = final_ratios.fillna(0)
final_ratios = final_ratios.replace(np.inf,0)
final_ratios.head()
final_ratios.tail()
###Output
_____no_output_____
###Markdown
4-5 Merge stock price data and ratios into one dataframe- Merge the price dataframe preprocessed in Part 3 and the ratio dataframe created in this part- Since the prices are daily and ratios are quartely, we have NAs in the ratio columns after merging the two dataframes. We deal with this by backfilling the ratios.
###Code
list_ticker = df["tic"].unique().tolist()
list_date = list(pd.date_range(df['date'].min(),df['date'].max()))
combination = list(itertools.product(list_date,list_ticker))
# Merge stock price data and ratios into one dataframe
processed_full = pd.DataFrame(combination,columns=["date","tic"]).merge(df,on=["date","tic"],how="left")
processed_full = processed_full.merge(final_ratios,how='left',on=['date','tic'])
processed_full = processed_full.sort_values(['tic','date'])
# Backfill the ratio data to make them daily
processed_full = processed_full.bfill(axis='rows')
###Output
_____no_output_____
###Markdown
4-6 Calculate market valuation ratios using daily stock price data
###Code
# Calculate P/E, P/B and dividend yield using daily closing price
processed_full['PE'] = processed_full['close']/processed_full['EPS']
processed_full['PB'] = processed_full['close']/processed_full['BPS']
processed_full['Div_yield'] = processed_full['DPS']/processed_full['close']
# Drop per share items used for the above calculation
processed_full = processed_full.drop(columns=['day','EPS','BPS','DPS'])
# Check the final data
processed_full.sort_values(['date','tic'],ignore_index=True).head(10)
###Output
_____no_output_____
###Markdown
Part 5. Design EnvironmentConsidering the stochastic and interactive nature of the automated stock trading tasks, a financial task is modeled as a **Markov Decision Process (MDP)** problem. The training process involves observing stock price change, taking an action and reward's calculation to have the agent adjusting its strategy accordingly. By interacting with the environment, the trading agent will derive a trading strategy with the maximized rewards as time proceeds.Our trading environments, based on OpenAI Gym framework, simulate live stock markets with real market data according to the principle of time-driven simulation.The action space describes the allowed actions that the agent interacts with the environment. Normally, action a includes three actions: {-1, 0, 1}, where -1, 0, 1 represent selling, holding, and buying one share. Also, an action can be carried upon multiple shares. We use an action space {-k,…,-1, 0, 1, …, k}, where k denotes the number of shares to buy and -k denotes the number of shares to sell. For example, "Buy 10 shares of AAPL" or "Sell 10 shares of AAPL" are 10 or -10, respectively. The continuous action space needs to be normalized to [-1, 1], since the policy is defined on a Gaussian distribution, which needs to be normalized and symmetric. 5-1 Split data into training and trade dataset- Training data split: 2009-01-01 to 2018-12-31- Trade data split: 2019-01-01 to 2020-09-30
###Code
train = data_split(processed_full, '2009-01-01','2019-01-01')
trade = data_split(processed_full, '2019-01-01','2021-01-01')
# Check the length of the two datasets
print(len(train))
print(len(trade))
train.head()
trade.head()
###Output
_____no_output_____
###Markdown
5-2 Set up the training environment
###Code
ratio_list = ['OPM', 'NPM','ROA', 'ROE', 'cur_ratio', 'quick_ratio', 'cash_ratio', 'inv_turnover','acc_rec_turnover', 'acc_pay_turnover', 'debt_ratio', 'debt_to_equity',
'PE', 'PB', 'Div_yield']
stock_dimension = len(train.tic.unique())
state_space = 1 + 2*stock_dimension + len(ratio_list)*stock_dimension
print(f"Stock Dimension: {stock_dimension}, State Space: {state_space}")
# Parameters for the environment
env_kwargs = {
"hmax": 100,
"initial_amount": 1000000,
"buy_cost_pct": 0.001,
"sell_cost_pct": 0.001,
"state_space": state_space,
"stock_dim": stock_dimension,
"tech_indicator_list": ratio_list,
"action_space": stock_dimension,
"reward_scaling": 1e-4
}
#Establish the training environment using StockTradingEnv() class
e_train_gym = StockTradingEnv(df = train, **env_kwargs)
###Output
_____no_output_____
###Markdown
Environment for Training
###Code
env_train, _ = e_train_gym.get_sb_env()
print(type(env_train))
###Output
<class 'stable_baselines3.common.vec_env.dummy_vec_env.DummyVecEnv'>
###Markdown
Part 6: Implement DRL Algorithms* The implementation of the DRL algorithms are based on **OpenAI Baselines** and **Stable Baselines**. Stable Baselines is a fork of OpenAI Baselines, with a major structural refactoring, and code cleanups.* FinRL library includes fine-tuned standard DRL algorithms, such as DQN, DDPG,Multi-Agent DDPG, PPO, SAC, A2C and TD3. We also allow users todesign their own DRL algorithms by adapting these DRL algorithms.
###Code
# Set up the agent using DRLAgent() class using the environment created in the previous part
agent = DRLAgent(env = env_train)
###Output
_____no_output_____
###Markdown
Model Training: 5 models, A2C DDPG, PPO, TD3, SAC Model 1: A2C
###Code
agent = DRLAgent(env = env_train)
model_a2c = agent.get_model("a2c")
trained_a2c = agent.train_model(model=model_a2c,
tb_log_name='a2c',
total_timesteps=100000)
###Output
Logging to tensorboard_log/a2c/a2c_1
------------------------------------
| time/ | |
| fps | 60 |
| iterations | 100 |
| time_elapsed | 8 |
| total_timesteps | 500 |
| train/ | |
| entropy_loss | -42.9 |
| explained_variance | 0.157 |
| learning_rate | 0.0007 |
| n_updates | 99 |
| policy_loss | 165 |
| std | 1.01 |
| value_loss | 18.3 |
------------------------------------
------------------------------------
| time/ | |
| fps | 68 |
| iterations | 200 |
| time_elapsed | 14 |
| total_timesteps | 1000 |
| train/ | |
| entropy_loss | -43 |
| explained_variance | 0.0513 |
| learning_rate | 0.0007 |
| n_updates | 199 |
| policy_loss | 51.6 |
| std | 1.01 |
| value_loss | 17.2 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 71 |
| iterations | 300 |
| time_elapsed | 20 |
| total_timesteps | 1500 |
| train/ | |
| entropy_loss | -42.9 |
| explained_variance | -1.19e-06 |
| learning_rate | 0.0007 |
| n_updates | 299 |
| policy_loss | -1.03 |
| std | 1.01 |
| value_loss | 0.541 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 73 |
| iterations | 400 |
| time_elapsed | 27 |
| total_timesteps | 2000 |
| train/ | |
| entropy_loss | -43 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 399 |
| policy_loss | 103 |
| std | 1.01 |
| value_loss | 5.78 |
------------------------------------
------------------------------------
| time/ | |
| fps | 74 |
| iterations | 500 |
| time_elapsed | 33 |
| total_timesteps | 2500 |
| train/ | |
| entropy_loss | -43.1 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 499 |
| policy_loss | 158 |
| std | 1.02 |
| value_loss | 23.9 |
------------------------------------
------------------------------------
| time/ | |
| fps | 74 |
| iterations | 600 |
| time_elapsed | 40 |
| total_timesteps | 3000 |
| train/ | |
| entropy_loss | -43.1 |
| explained_variance | 5.96e-08 |
| learning_rate | 0.0007 |
| n_updates | 599 |
| policy_loss | 62.7 |
| std | 1.02 |
| value_loss | 2.76 |
------------------------------------
------------------------------------
| time/ | |
| fps | 75 |
| iterations | 700 |
| time_elapsed | 46 |
| total_timesteps | 3500 |
| train/ | |
| entropy_loss | -43.1 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 699 |
| policy_loss | -136 |
| std | 1.02 |
| value_loss | 17.3 |
------------------------------------
------------------------------------
| environment/ | |
| portfolio_value | 1.91e+06 |
| total_cost | 7.56e+04 |
| total_reward | 9.14e+05 |
| total_reward_pct | 91.4 |
| total_trades | 73316 |
| time/ | |
| fps | 75 |
| iterations | 800 |
| time_elapsed | 52 |
| total_timesteps | 4000 |
| train/ | |
| entropy_loss | -43.1 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 799 |
| policy_loss | -50.6 |
| std | 1.02 |
| value_loss | 1.55 |
------------------------------------
------------------------------------
| time/ | |
| fps | 75 |
| iterations | 900 |
| time_elapsed | 59 |
| total_timesteps | 4500 |
| train/ | |
| entropy_loss | -43.2 |
| explained_variance | 1.79e-07 |
| learning_rate | 0.0007 |
| n_updates | 899 |
| policy_loss | 76.5 |
| std | 1.02 |
| value_loss | 2.69 |
------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 1000 |
| time_elapsed | 65 |
| total_timesteps | 5000 |
| train/ | |
| entropy_loss | -43.2 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 999 |
| policy_loss | 175 |
| std | 1.02 |
| value_loss | 17.4 |
------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 1100 |
| time_elapsed | 72 |
| total_timesteps | 5500 |
| train/ | |
| entropy_loss | -43.2 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 1099 |
| policy_loss | -14.7 |
| std | 1.02 |
| value_loss | 0.158 |
------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 1200 |
| time_elapsed | 78 |
| total_timesteps | 6000 |
| train/ | |
| entropy_loss | -43.2 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 1199 |
| policy_loss | -84.2 |
| std | 1.02 |
| value_loss | 3.71 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 76 |
| iterations | 1300 |
| time_elapsed | 84 |
| total_timesteps | 6500 |
| train/ | |
| entropy_loss | -43.3 |
| explained_variance | -4.77e-07 |
| learning_rate | 0.0007 |
| n_updates | 1299 |
| policy_loss | -63.5 |
| std | 1.02 |
| value_loss | 3.31 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 1400 |
| time_elapsed | 91 |
| total_timesteps | 7000 |
| train/ | |
| entropy_loss | -43.3 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 1399 |
| policy_loss | -309 |
| std | 1.03 |
| value_loss | 60.1 |
------------------------------------
------------------------------------
| environment/ | |
| portfolio_value | 2.29e+06 |
| total_cost | 2.63e+04 |
| total_reward | 1.29e+06 |
| total_reward_pct | 129 |
| total_trades | 60684 |
| time/ | |
| fps | 76 |
| iterations | 1500 |
| time_elapsed | 97 |
| total_timesteps | 7500 |
| train/ | |
| entropy_loss | -43.4 |
| explained_variance | -0.33 |
| learning_rate | 0.0007 |
| n_updates | 1499 |
| policy_loss | 61.1 |
| std | 1.03 |
| value_loss | 3.06 |
------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 1600 |
| time_elapsed | 103 |
| total_timesteps | 8000 |
| train/ | |
| entropy_loss | -43.5 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 1599 |
| policy_loss | -19.4 |
| std | 1.03 |
| value_loss | 0.955 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 77 |
| iterations | 1700 |
| time_elapsed | 110 |
| total_timesteps | 8500 |
| train/ | |
| entropy_loss | -43.5 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 1699 |
| policy_loss | -50.8 |
| std | 1.03 |
| value_loss | 2.76 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 1800 |
| time_elapsed | 116 |
| total_timesteps | 9000 |
| train/ | |
| entropy_loss | -43.5 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 1799 |
| policy_loss | 19.4 |
| std | 1.03 |
| value_loss | 0.647 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 1900 |
| time_elapsed | 123 |
| total_timesteps | 9500 |
| train/ | |
| entropy_loss | -43.5 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 1899 |
| policy_loss | -187 |
| std | 1.03 |
| value_loss | 22.8 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 77 |
| iterations | 2000 |
| time_elapsed | 129 |
| total_timesteps | 10000 |
| train/ | |
| entropy_loss | -43.5 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 1999 |
| policy_loss | -71.4 |
| std | 1.03 |
| value_loss | 4.75 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 2100 |
| time_elapsed | 135 |
| total_timesteps | 10500 |
| train/ | |
| entropy_loss | -43.5 |
| explained_variance | 5.96e-08 |
| learning_rate | 0.0007 |
| n_updates | 2099 |
| policy_loss | 73.2 |
| std | 1.03 |
| value_loss | 4.46 |
------------------------------------
------------------------------------
| environment/ | |
| portfolio_value | 4.38e+06 |
| total_cost | 3.17e+04 |
| total_reward | 3.38e+06 |
| total_reward_pct | 338 |
| total_trades | 65214 |
| time/ | |
| fps | 77 |
| iterations | 2200 |
| time_elapsed | 142 |
| total_timesteps | 11000 |
| train/ | |
| entropy_loss | -43.7 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 2199 |
| policy_loss | -37.4 |
| std | 1.04 |
| value_loss | 1.05 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 2300 |
| time_elapsed | 148 |
| total_timesteps | 11500 |
| train/ | |
| entropy_loss | -43.7 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 2299 |
| policy_loss | -52.1 |
| std | 1.04 |
| value_loss | 2.56 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 2400 |
| time_elapsed | 155 |
| total_timesteps | 12000 |
| train/ | |
| entropy_loss | -43.7 |
| explained_variance | 5.96e-08 |
| learning_rate | 0.0007 |
| n_updates | 2399 |
| policy_loss | -91.9 |
| std | 1.04 |
| value_loss | 6.52 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 2500 |
| time_elapsed | 161 |
| total_timesteps | 12500 |
| train/ | |
| entropy_loss | -43.7 |
| explained_variance | 1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 2499 |
| policy_loss | 19.6 |
| std | 1.04 |
| value_loss | 0.766 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 2600 |
| time_elapsed | 167 |
| total_timesteps | 13000 |
| train/ | |
| entropy_loss | -43.7 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 2599 |
| policy_loss | -58.4 |
| std | 1.04 |
| value_loss | 2.59 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 2700 |
| time_elapsed | 174 |
| total_timesteps | 13500 |
| train/ | |
| entropy_loss | -43.8 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 2699 |
| policy_loss | -177 |
| std | 1.04 |
| value_loss | 24.6 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 2800 |
| time_elapsed | 180 |
| total_timesteps | 14000 |
| train/ | |
| entropy_loss | -43.8 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 2799 |
| policy_loss | 54.1 |
| std | 1.04 |
| value_loss | 1.96 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 2900 |
| time_elapsed | 187 |
| total_timesteps | 14500 |
| train/ | |
| entropy_loss | -43.8 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 2899 |
| policy_loss | 127 |
| std | 1.04 |
| value_loss | 15.7 |
------------------------------------
------------------------------------
| environment/ | |
| portfolio_value | 2.92e+06 |
| total_cost | 1.85e+04 |
| total_reward | 1.92e+06 |
| total_reward_pct | 192 |
| total_trades | 67453 |
| time/ | |
| fps | 77 |
| iterations | 3000 |
| time_elapsed | 193 |
| total_timesteps | 15000 |
| train/ | |
| entropy_loss | -43.8 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 2999 |
| policy_loss | -97.9 |
| std | 1.04 |
| value_loss | 5.52 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 3100 |
| time_elapsed | 199 |
| total_timesteps | 15500 |
| train/ | |
| entropy_loss | -43.9 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 3099 |
| policy_loss | -87.5 |
| std | 1.05 |
| value_loss | 4.94 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 3200 |
| time_elapsed | 206 |
| total_timesteps | 16000 |
| train/ | |
| entropy_loss | -44 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 3199 |
| policy_loss | -199 |
| std | 1.05 |
| value_loss | 21.3 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 77 |
| iterations | 3300 |
| time_elapsed | 212 |
| total_timesteps | 16500 |
| train/ | |
| entropy_loss | -44 |
| explained_variance | -3.58e-07 |
| learning_rate | 0.0007 |
| n_updates | 3299 |
| policy_loss | 59.4 |
| std | 1.05 |
| value_loss | 4.14 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 3400 |
| time_elapsed | 219 |
| total_timesteps | 17000 |
| train/ | |
| entropy_loss | -44 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 3399 |
| policy_loss | -32.7 |
| std | 1.05 |
| value_loss | 1.65 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 3500 |
| time_elapsed | 225 |
| total_timesteps | 17500 |
| train/ | |
| entropy_loss | -44 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 3499 |
| policy_loss | -85.8 |
| std | 1.05 |
| value_loss | 4.92 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 77 |
| iterations | 3600 |
| time_elapsed | 231 |
| total_timesteps | 18000 |
| train/ | |
| entropy_loss | -44 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 3599 |
| policy_loss | 118 |
| std | 1.05 |
| value_loss | 14.3 |
-------------------------------------
------------------------------------
| environment/ | |
| portfolio_value | 3.75e+06 |
| total_cost | 2.33e+04 |
| total_reward | 2.75e+06 |
| total_reward_pct | 275 |
| total_trades | 65849 |
| time/ | |
| fps | 77 |
| iterations | 3700 |
| time_elapsed | 238 |
| total_timesteps | 18500 |
| train/ | |
| entropy_loss | -43.9 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 3699 |
| policy_loss | -44.2 |
| std | 1.05 |
| value_loss | 1.43 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 77 |
| iterations | 3800 |
| time_elapsed | 244 |
| total_timesteps | 19000 |
| train/ | |
| entropy_loss | -43.9 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 3799 |
| policy_loss | 59.3 |
| std | 1.05 |
| value_loss | 1.79 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 3900 |
| time_elapsed | 251 |
| total_timesteps | 19500 |
| train/ | |
| entropy_loss | -43.9 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 3899 |
| policy_loss | 82.2 |
| std | 1.05 |
| value_loss | 3.91 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 4000 |
| time_elapsed | 257 |
| total_timesteps | 20000 |
| train/ | |
| entropy_loss | -43.9 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 3999 |
| policy_loss | -153 |
| std | 1.05 |
| value_loss | 13.7 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 4100 |
| time_elapsed | 263 |
| total_timesteps | 20500 |
| train/ | |
| entropy_loss | -44 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 4099 |
| policy_loss | 88 |
| std | 1.05 |
| value_loss | 4.7 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 4200 |
| time_elapsed | 270 |
| total_timesteps | 21000 |
| train/ | |
| entropy_loss | -44 |
| explained_variance | -0.0553 |
| learning_rate | 0.0007 |
| n_updates | 4199 |
| policy_loss | -65 |
| std | 1.05 |
| value_loss | 5.44 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 4300 |
| time_elapsed | 276 |
| total_timesteps | 21500 |
| train/ | |
| entropy_loss | -44 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 4299 |
| policy_loss | -55.7 |
| std | 1.05 |
| value_loss | 2.66 |
------------------------------------
------------------------------------
| environment/ | |
| portfolio_value | 3.83e+06 |
| total_cost | 8.83e+04 |
| total_reward | 2.83e+06 |
| total_reward_pct | 283 |
| total_trades | 71634 |
| time/ | |
| fps | 77 |
| iterations | 4400 |
| time_elapsed | 283 |
| total_timesteps | 22000 |
| train/ | |
| entropy_loss | -44 |
| explained_variance | -0.0125 |
| learning_rate | 0.0007 |
| n_updates | 4399 |
| policy_loss | 94.9 |
| std | 1.05 |
| value_loss | 5.92 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 4500 |
| time_elapsed | 289 |
| total_timesteps | 22500 |
| train/ | |
| entropy_loss | -44 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 4499 |
| policy_loss | -95.7 |
| std | 1.05 |
| value_loss | 6.98 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 4600 |
| time_elapsed | 296 |
| total_timesteps | 23000 |
| train/ | |
| entropy_loss | -44 |
| explained_variance | 1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 4599 |
| policy_loss | 0.903 |
| std | 1.05 |
| value_loss | 0.28 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 4700 |
| time_elapsed | 302 |
| total_timesteps | 23500 |
| train/ | |
| entropy_loss | -44 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 4699 |
| policy_loss | -79.2 |
| std | 1.05 |
| value_loss | 2.97 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 4800 |
| time_elapsed | 308 |
| total_timesteps | 24000 |
| train/ | |
| entropy_loss | -44 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 4799 |
| policy_loss | -23.5 |
| std | 1.05 |
| value_loss | 0.842 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 4900 |
| time_elapsed | 315 |
| total_timesteps | 24500 |
| train/ | |
| entropy_loss | -44 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 4899 |
| policy_loss | 54.6 |
| std | 1.05 |
| value_loss | 7.28 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 5000 |
| time_elapsed | 321 |
| total_timesteps | 25000 |
| train/ | |
| entropy_loss | -44.2 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 4999 |
| policy_loss | 34.9 |
| std | 1.06 |
| value_loss | 1.99 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 5100 |
| time_elapsed | 327 |
| total_timesteps | 25500 |
| train/ | |
| entropy_loss | -44.1 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 5099 |
| policy_loss | 352 |
| std | 1.05 |
| value_loss | 72.6 |
------------------------------------
------------------------------------
| environment/ | |
| portfolio_value | 3.24e+06 |
| total_cost | 1.66e+04 |
| total_reward | 2.24e+06 |
| total_reward_pct | 224 |
| total_trades | 61666 |
| time/ | |
| fps | 77 |
| iterations | 5200 |
| time_elapsed | 334 |
| total_timesteps | 26000 |
| train/ | |
| entropy_loss | -44.1 |
| explained_variance | 1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 5199 |
| policy_loss | 2.88 |
| std | 1.06 |
| value_loss | 0.137 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 5300 |
| time_elapsed | 340 |
| total_timesteps | 26500 |
| train/ | |
| entropy_loss | -44.2 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 5299 |
| policy_loss | -222 |
| std | 1.06 |
| value_loss | 30.4 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 5400 |
| time_elapsed | 347 |
| total_timesteps | 27000 |
| train/ | |
| entropy_loss | -44.2 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 5399 |
| policy_loss | -11.7 |
| std | 1.06 |
| value_loss | 0.156 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 5500 |
| time_elapsed | 353 |
| total_timesteps | 27500 |
| train/ | |
| entropy_loss | -44.2 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 5499 |
| policy_loss | 165 |
| std | 1.06 |
| value_loss | 13.7 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 5600 |
| time_elapsed | 359 |
| total_timesteps | 28000 |
| train/ | |
| entropy_loss | -44.2 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 5599 |
| policy_loss | 127 |
| std | 1.06 |
| value_loss | 15.9 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 77 |
| iterations | 5700 |
| time_elapsed | 366 |
| total_timesteps | 28500 |
| train/ | |
| entropy_loss | -44.2 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 5699 |
| policy_loss | 26.7 |
| std | 1.06 |
| value_loss | 0.48 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 5800 |
| time_elapsed | 372 |
| total_timesteps | 29000 |
| train/ | |
| entropy_loss | -44.2 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 5799 |
| policy_loss | 242 |
| std | 1.06 |
| value_loss | 37 |
------------------------------------
------------------------------------
| environment/ | |
| portfolio_value | 3.16e+06 |
| total_cost | 1.22e+04 |
| total_reward | 2.16e+06 |
| total_reward_pct | 216 |
| total_trades | 60801 |
| time/ | |
| fps | 77 |
| iterations | 5900 |
| time_elapsed | 379 |
| total_timesteps | 29500 |
| train/ | |
| entropy_loss | -44.2 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 5899 |
| policy_loss | 72.7 |
| std | 1.06 |
| value_loss | 4.37 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 6000 |
| time_elapsed | 385 |
| total_timesteps | 30000 |
| train/ | |
| entropy_loss | -44.2 |
| explained_variance | 1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 5999 |
| policy_loss | 58 |
| std | 1.06 |
| value_loss | 4.2 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 6100 |
| time_elapsed | 392 |
| total_timesteps | 30500 |
| train/ | |
| entropy_loss | -44.2 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 6099 |
| policy_loss | -132 |
| std | 1.06 |
| value_loss | 9.64 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 6200 |
| time_elapsed | 398 |
| total_timesteps | 31000 |
| train/ | |
| entropy_loss | -44.2 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 6199 |
| policy_loss | 25.9 |
| std | 1.06 |
| value_loss | 1.75 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 77 |
| iterations | 6300 |
| time_elapsed | 404 |
| total_timesteps | 31500 |
| train/ | |
| entropy_loss | -44.2 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 6299 |
| policy_loss | -84.4 |
| std | 1.06 |
| value_loss | 5.68 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 6400 |
| time_elapsed | 411 |
| total_timesteps | 32000 |
| train/ | |
| entropy_loss | -44.2 |
| explained_variance | 1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 6399 |
| policy_loss | -74.6 |
| std | 1.06 |
| value_loss | 3.73 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 6500 |
| time_elapsed | 417 |
| total_timesteps | 32500 |
| train/ | |
| entropy_loss | -44.2 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 6499 |
| policy_loss | 120 |
| std | 1.06 |
| value_loss | 21.8 |
------------------------------------
day: 3650, episode: 10
begin_total_asset: 1000000.00
end_total_asset: 4297821.94
total_reward: 3297821.94
total_cost: 12437.82
total_trades: 58594
Sharpe: 0.695
=================================
------------------------------------
| environment/ | |
| portfolio_value | 4.3e+06 |
| total_cost | 1.24e+04 |
| total_reward | 3.3e+06 |
| total_reward_pct | 330 |
| total_trades | 58594 |
| time/ | |
| fps | 77 |
| iterations | 6600 |
| time_elapsed | 424 |
| total_timesteps | 33000 |
| train/ | |
| entropy_loss | -44.2 |
| explained_variance | -0.112 |
| learning_rate | 0.0007 |
| n_updates | 6599 |
| policy_loss | 63.4 |
| std | 1.06 |
| value_loss | 4.21 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 6700 |
| time_elapsed | 430 |
| total_timesteps | 33500 |
| train/ | |
| entropy_loss | -44.2 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 6699 |
| policy_loss | 31.2 |
| std | 1.06 |
| value_loss | 3.92 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 77 |
| iterations | 6800 |
| time_elapsed | 437 |
| total_timesteps | 34000 |
| train/ | |
| entropy_loss | -44.3 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 6799 |
| policy_loss | 141 |
| std | 1.06 |
| value_loss | 16.5 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 6900 |
| time_elapsed | 443 |
| total_timesteps | 34500 |
| train/ | |
| entropy_loss | -44.3 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 6899 |
| policy_loss | -198 |
| std | 1.06 |
| value_loss | 23.1 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 7000 |
| time_elapsed | 450 |
| total_timesteps | 35000 |
| train/ | |
| entropy_loss | -44.3 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 6999 |
| policy_loss | 132 |
| std | 1.06 |
| value_loss | 12.7 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 7100 |
| time_elapsed | 456 |
| total_timesteps | 35500 |
| train/ | |
| entropy_loss | -44.2 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 7099 |
| policy_loss | -99.9 |
| std | 1.06 |
| value_loss | 5.45 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 77 |
| iterations | 7200 |
| time_elapsed | 462 |
| total_timesteps | 36000 |
| train/ | |
| entropy_loss | -44.2 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 7199 |
| policy_loss | 210 |
| std | 1.06 |
| value_loss | 32.8 |
-------------------------------------
-------------------------------------
| time/ | |
| fps | 77 |
| iterations | 7300 |
| time_elapsed | 469 |
| total_timesteps | 36500 |
| train/ | |
| entropy_loss | -44.2 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 7299 |
| policy_loss | -476 |
| std | 1.06 |
| value_loss | 271 |
-------------------------------------
------------------------------------
| environment/ | |
| portfolio_value | 4.94e+06 |
| total_cost | 8.73e+03 |
| total_reward | 3.94e+06 |
| total_reward_pct | 394 |
| total_trades | 58374 |
| time/ | |
| fps | 77 |
| iterations | 7400 |
| time_elapsed | 475 |
| total_timesteps | 37000 |
| train/ | |
| entropy_loss | -44.2 |
| explained_variance | 5.96e-08 |
| learning_rate | 0.0007 |
| n_updates | 7399 |
| policy_loss | 42.2 |
| std | 1.06 |
| value_loss | 2.51 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 7500 |
| time_elapsed | 482 |
| total_timesteps | 37500 |
| train/ | |
| entropy_loss | -44.1 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 7499 |
| policy_loss | 140 |
| std | 1.06 |
| value_loss | 10.6 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 7600 |
| time_elapsed | 488 |
| total_timesteps | 38000 |
| train/ | |
| entropy_loss | -44.2 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 7599 |
| policy_loss | -201 |
| std | 1.06 |
| value_loss | 45.9 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 7700 |
| time_elapsed | 495 |
| total_timesteps | 38500 |
| train/ | |
| entropy_loss | -44.2 |
| explained_variance | 5.96e-08 |
| learning_rate | 0.0007 |
| n_updates | 7699 |
| policy_loss | 28.5 |
| std | 1.06 |
| value_loss | 1.14 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 7800 |
| time_elapsed | 501 |
| total_timesteps | 39000 |
| train/ | |
| entropy_loss | -44.2 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 7799 |
| policy_loss | 520 |
| std | 1.06 |
| value_loss | 162 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 7900 |
| time_elapsed | 508 |
| total_timesteps | 39500 |
| train/ | |
| entropy_loss | -44.2 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 7899 |
| policy_loss | -54.3 |
| std | 1.06 |
| value_loss | 2.66 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 8000 |
| time_elapsed | 514 |
| total_timesteps | 40000 |
| train/ | |
| entropy_loss | -44.3 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 7999 |
| policy_loss | 58.2 |
| std | 1.06 |
| value_loss | 2.26 |
------------------------------------
-------------------------------------
| environment/ | |
| portfolio_value | 4.63e+06 |
| total_cost | 8.6e+03 |
| total_reward | 3.63e+06 |
| total_reward_pct | 363 |
| total_trades | 58469 |
| time/ | |
| fps | 77 |
| iterations | 8100 |
| time_elapsed | 520 |
| total_timesteps | 40500 |
| train/ | |
| entropy_loss | -44.3 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 8099 |
| policy_loss | -20.9 |
| std | 1.06 |
| value_loss | 0.355 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 8200 |
| time_elapsed | 527 |
| total_timesteps | 41000 |
| train/ | |
| entropy_loss | -44.3 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 8199 |
| policy_loss | -38.6 |
| std | 1.06 |
| value_loss | 0.935 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 8300 |
| time_elapsed | 533 |
| total_timesteps | 41500 |
| train/ | |
| entropy_loss | -44.3 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 8299 |
| policy_loss | 11.9 |
| std | 1.06 |
| value_loss | 0.774 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 8400 |
| time_elapsed | 540 |
| total_timesteps | 42000 |
| train/ | |
| entropy_loss | -44.3 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 8399 |
| policy_loss | -39.8 |
| std | 1.06 |
| value_loss | 1.31 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 8500 |
| time_elapsed | 546 |
| total_timesteps | 42500 |
| train/ | |
| entropy_loss | -44.2 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 8499 |
| policy_loss | -128 |
| std | 1.06 |
| value_loss | 16.3 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 8600 |
| time_elapsed | 553 |
| total_timesteps | 43000 |
| train/ | |
| entropy_loss | -44.3 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 8599 |
| policy_loss | 70.4 |
| std | 1.06 |
| value_loss | 2.69 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 8700 |
| time_elapsed | 559 |
| total_timesteps | 43500 |
| train/ | |
| entropy_loss | -44.3 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 8699 |
| policy_loss | 170 |
| std | 1.06 |
| value_loss | 57.3 |
------------------------------------
------------------------------------
| environment/ | |
| portfolio_value | 4.48e+06 |
| total_cost | 5.81e+03 |
| total_reward | 3.48e+06 |
| total_reward_pct | 348 |
| total_trades | 57804 |
| time/ | |
| fps | 77 |
| iterations | 8800 |
| time_elapsed | 565 |
| total_timesteps | 44000 |
| train/ | |
| entropy_loss | -44.3 |
| explained_variance | 0.00216 |
| learning_rate | 0.0007 |
| n_updates | 8799 |
| policy_loss | -63 |
| std | 1.06 |
| value_loss | 3.26 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 8900 |
| time_elapsed | 572 |
| total_timesteps | 44500 |
| train/ | |
| entropy_loss | -44.3 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 8899 |
| policy_loss | -111 |
| std | 1.06 |
| value_loss | 7.1 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 9000 |
| time_elapsed | 579 |
| total_timesteps | 45000 |
| train/ | |
| entropy_loss | -44.3 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 8999 |
| policy_loss | -72.9 |
| std | 1.06 |
| value_loss | 3.48 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 77 |
| iterations | 9100 |
| time_elapsed | 585 |
| total_timesteps | 45500 |
| train/ | |
| entropy_loss | -44.4 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 9099 |
| policy_loss | -18.6 |
| std | 1.06 |
| value_loss | 0.765 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 9200 |
| time_elapsed | 592 |
| total_timesteps | 46000 |
| train/ | |
| entropy_loss | -44.4 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 9199 |
| policy_loss | 71.5 |
| std | 1.07 |
| value_loss | 2.94 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 9300 |
| time_elapsed | 598 |
| total_timesteps | 46500 |
| train/ | |
| entropy_loss | -44.5 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 9299 |
| policy_loss | -8.18 |
| std | 1.07 |
| value_loss | 0.324 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 9400 |
| time_elapsed | 605 |
| total_timesteps | 47000 |
| train/ | |
| entropy_loss | -44.6 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 9399 |
| policy_loss | -262 |
| std | 1.07 |
| value_loss | 34.3 |
------------------------------------
------------------------------------
| environment/ | |
| portfolio_value | 3.96e+06 |
| total_cost | 4.92e+03 |
| total_reward | 2.96e+06 |
| total_reward_pct | 296 |
| total_trades | 58228 |
| time/ | |
| fps | 77 |
| iterations | 9500 |
| time_elapsed | 611 |
| total_timesteps | 47500 |
| train/ | |
| entropy_loss | -44.6 |
| explained_variance | 0.111 |
| learning_rate | 0.0007 |
| n_updates | 9499 |
| policy_loss | 58.7 |
| std | 1.07 |
| value_loss | 2.02 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 9600 |
| time_elapsed | 618 |
| total_timesteps | 48000 |
| train/ | |
| entropy_loss | -44.6 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 9599 |
| policy_loss | 103 |
| std | 1.07 |
| value_loss | 7.2 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 77 |
| iterations | 9700 |
| time_elapsed | 624 |
| total_timesteps | 48500 |
| train/ | |
| entropy_loss | -44.6 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 9699 |
| policy_loss | -62 |
| std | 1.07 |
| value_loss | 4.3 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 9800 |
| time_elapsed | 631 |
| total_timesteps | 49000 |
| train/ | |
| entropy_loss | -44.6 |
| explained_variance | 5.96e-08 |
| learning_rate | 0.0007 |
| n_updates | 9799 |
| policy_loss | 25.5 |
| std | 1.07 |
| value_loss | 1.05 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 77 |
| iterations | 9900 |
| time_elapsed | 637 |
| total_timesteps | 49500 |
| train/ | |
| entropy_loss | -44.6 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 9899 |
| policy_loss | 34.8 |
| std | 1.07 |
| value_loss | 1.79 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 10000 |
| time_elapsed | 644 |
| total_timesteps | 50000 |
| train/ | |
| entropy_loss | -44.6 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 9999 |
| policy_loss | -288 |
| std | 1.07 |
| value_loss | 45.4 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 77 |
| iterations | 10100 |
| time_elapsed | 650 |
| total_timesteps | 50500 |
| train/ | |
| entropy_loss | -44.7 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 10099 |
| policy_loss | 176 |
| std | 1.07 |
| value_loss | 17.8 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 10200 |
| time_elapsed | 657 |
| total_timesteps | 51000 |
| train/ | |
| entropy_loss | -44.7 |
| explained_variance | 5.96e-08 |
| learning_rate | 0.0007 |
| n_updates | 10199 |
| policy_loss | -22.3 |
| std | 1.08 |
| value_loss | 1.66 |
------------------------------------
------------------------------------
| environment/ | |
| portfolio_value | 4.38e+06 |
| total_cost | 5.66e+03 |
| total_reward | 3.38e+06 |
| total_reward_pct | 338 |
| total_trades | 61155 |
| time/ | |
| fps | 77 |
| iterations | 10300 |
| time_elapsed | 664 |
| total_timesteps | 51500 |
| train/ | |
| entropy_loss | -44.8 |
| explained_variance | 3.46e-06 |
| learning_rate | 0.0007 |
| n_updates | 10299 |
| policy_loss | -18.2 |
| std | 1.08 |
| value_loss | 0.59 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 10400 |
| time_elapsed | 670 |
| total_timesteps | 52000 |
| train/ | |
| entropy_loss | -44.8 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 10399 |
| policy_loss | -166 |
| std | 1.08 |
| value_loss | 15.3 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 10500 |
| time_elapsed | 677 |
| total_timesteps | 52500 |
| train/ | |
| entropy_loss | -44.8 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 10499 |
| policy_loss | -1.79 |
| std | 1.08 |
| value_loss | 0.733 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 10600 |
| time_elapsed | 683 |
| total_timesteps | 53000 |
| train/ | |
| entropy_loss | -44.9 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 10599 |
| policy_loss | -46.4 |
| std | 1.08 |
| value_loss | 1.3 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 10700 |
| time_elapsed | 690 |
| total_timesteps | 53500 |
| train/ | |
| entropy_loss | -44.9 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 10699 |
| policy_loss | 358 |
| std | 1.08 |
| value_loss | 72.7 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 10800 |
| time_elapsed | 696 |
| total_timesteps | 54000 |
| train/ | |
| entropy_loss | -45 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 10799 |
| policy_loss | 26.8 |
| std | 1.08 |
| value_loss | 0.888 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 10900 |
| time_elapsed | 703 |
| total_timesteps | 54500 |
| train/ | |
| entropy_loss | -45 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 10899 |
| policy_loss | -124 |
| std | 1.09 |
| value_loss | 34.6 |
------------------------------------
------------------------------------
| environment/ | |
| portfolio_value | 3.93e+06 |
| total_cost | 7.95e+03 |
| total_reward | 2.93e+06 |
| total_reward_pct | 293 |
| total_trades | 62120 |
| time/ | |
| fps | 77 |
| iterations | 11000 |
| time_elapsed | 710 |
| total_timesteps | 55000 |
| train/ | |
| entropy_loss | -45.1 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 10999 |
| policy_loss | 88.9 |
| std | 1.09 |
| value_loss | 4.3 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 11100 |
| time_elapsed | 716 |
| total_timesteps | 55500 |
| train/ | |
| entropy_loss | -45 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 11099 |
| policy_loss | 25.5 |
| std | 1.09 |
| value_loss | 0.656 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 11200 |
| time_elapsed | 723 |
| total_timesteps | 56000 |
| train/ | |
| entropy_loss | -45 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 11199 |
| policy_loss | -91.8 |
| std | 1.09 |
| value_loss | 5 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 11300 |
| time_elapsed | 729 |
| total_timesteps | 56500 |
| train/ | |
| entropy_loss | -45.1 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 11299 |
| policy_loss | -168 |
| std | 1.09 |
| value_loss | 18 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 11400 |
| time_elapsed | 736 |
| total_timesteps | 57000 |
| train/ | |
| entropy_loss | -45.1 |
| explained_variance | 5.96e-08 |
| learning_rate | 0.0007 |
| n_updates | 11399 |
| policy_loss | 163 |
| std | 1.09 |
| value_loss | 11.3 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 11500 |
| time_elapsed | 742 |
| total_timesteps | 57500 |
| train/ | |
| entropy_loss | -45.1 |
| explained_variance | 1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 11499 |
| policy_loss | -269 |
| std | 1.09 |
| value_loss | 35.7 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 11600 |
| time_elapsed | 749 |
| total_timesteps | 58000 |
| train/ | |
| entropy_loss | -45.1 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 11599 |
| policy_loss | 117 |
| std | 1.09 |
| value_loss | 19.2 |
------------------------------------
------------------------------------
| environment/ | |
| portfolio_value | 3.86e+06 |
| total_cost | 9.73e+03 |
| total_reward | 2.86e+06 |
| total_reward_pct | 286 |
| total_trades | 59593 |
| time/ | |
| fps | 77 |
| iterations | 11700 |
| time_elapsed | 756 |
| total_timesteps | 58500 |
| train/ | |
| entropy_loss | -45.1 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 11699 |
| policy_loss | 146 |
| std | 1.09 |
| value_loss | 15 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 77 |
| iterations | 11800 |
| time_elapsed | 762 |
| total_timesteps | 59000 |
| train/ | |
| entropy_loss | -45.1 |
| explained_variance | -2.38e-07 |
| learning_rate | 0.0007 |
| n_updates | 11799 |
| policy_loss | -6.42 |
| std | 1.09 |
| value_loss | 0.452 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 11900 |
| time_elapsed | 769 |
| total_timesteps | 59500 |
| train/ | |
| entropy_loss | -45.1 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 11899 |
| policy_loss | -116 |
| std | 1.09 |
| value_loss | 8.42 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 12000 |
| time_elapsed | 775 |
| total_timesteps | 60000 |
| train/ | |
| entropy_loss | -45.2 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 11999 |
| policy_loss | 115 |
| std | 1.09 |
| value_loss | 7.46 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 12100 |
| time_elapsed | 782 |
| total_timesteps | 60500 |
| train/ | |
| entropy_loss | -45.2 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 12099 |
| policy_loss | 27.9 |
| std | 1.09 |
| value_loss | 2.52 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 12200 |
| time_elapsed | 788 |
| total_timesteps | 61000 |
| train/ | |
| entropy_loss | -45.2 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 12199 |
| policy_loss | -49.7 |
| std | 1.09 |
| value_loss | 4.56 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 77 |
| iterations | 12300 |
| time_elapsed | 795 |
| total_timesteps | 61500 |
| train/ | |
| entropy_loss | -45.2 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 12299 |
| policy_loss | -61.2 |
| std | 1.09 |
| value_loss | 2.91 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 12400 |
| time_elapsed | 801 |
| total_timesteps | 62000 |
| train/ | |
| entropy_loss | -45.3 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 12399 |
| policy_loss | 74.6 |
| std | 1.1 |
| value_loss | 15.6 |
------------------------------------
-------------------------------------
| environment/ | |
| portfolio_value | 4.12e+06 |
| total_cost | 5.9e+03 |
| total_reward | 3.12e+06 |
| total_reward_pct | 312 |
| total_trades | 61004 |
| time/ | |
| fps | 77 |
| iterations | 12500 |
| time_elapsed | 808 |
| total_timesteps | 62500 |
| train/ | |
| entropy_loss | -45.4 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 12499 |
| policy_loss | 61 |
| std | 1.1 |
| value_loss | 3.23 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 12600 |
| time_elapsed | 815 |
| total_timesteps | 63000 |
| train/ | |
| entropy_loss | -45.5 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 12599 |
| policy_loss | 74.9 |
| std | 1.1 |
| value_loss | 2.61 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 12700 |
| time_elapsed | 821 |
| total_timesteps | 63500 |
| train/ | |
| entropy_loss | -45.5 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 12699 |
| policy_loss | 77.4 |
| std | 1.1 |
| value_loss | 3.81 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 12800 |
| time_elapsed | 828 |
| total_timesteps | 64000 |
| train/ | |
| entropy_loss | -45.5 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 12799 |
| policy_loss | -14.7 |
| std | 1.1 |
| value_loss | 7.94 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 77 |
| iterations | 12900 |
| time_elapsed | 834 |
| total_timesteps | 64500 |
| train/ | |
| entropy_loss | -45.5 |
| explained_variance | -2.38e-07 |
| learning_rate | 0.0007 |
| n_updates | 12899 |
| policy_loss | 1.03e+03 |
| std | 1.1 |
| value_loss | 505 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 13000 |
| time_elapsed | 841 |
| total_timesteps | 65000 |
| train/ | |
| entropy_loss | -45.6 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 12999 |
| policy_loss | 124 |
| std | 1.11 |
| value_loss | 11.5 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 13100 |
| time_elapsed | 848 |
| total_timesteps | 65500 |
| train/ | |
| entropy_loss | -45.6 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 13099 |
| policy_loss | -15 |
| std | 1.11 |
| value_loss | 1.22 |
------------------------------------
------------------------------------
| environment/ | |
| portfolio_value | 4.65e+06 |
| total_cost | 8.07e+03 |
| total_reward | 3.65e+06 |
| total_reward_pct | 365 |
| total_trades | 62460 |
| time/ | |
| fps | 77 |
| iterations | 13200 |
| time_elapsed | 854 |
| total_timesteps | 66000 |
| train/ | |
| entropy_loss | -45.6 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 13199 |
| policy_loss | 46.3 |
| std | 1.11 |
| value_loss | 0.915 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 13300 |
| time_elapsed | 861 |
| total_timesteps | 66500 |
| train/ | |
| entropy_loss | -45.6 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 13299 |
| policy_loss | -14.1 |
| std | 1.11 |
| value_loss | 0.13 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 13400 |
| time_elapsed | 867 |
| total_timesteps | 67000 |
| train/ | |
| entropy_loss | -45.7 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 13399 |
| policy_loss | 65 |
| std | 1.11 |
| value_loss | 4.92 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 13500 |
| time_elapsed | 874 |
| total_timesteps | 67500 |
| train/ | |
| entropy_loss | -45.7 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 13499 |
| policy_loss | 121 |
| std | 1.11 |
| value_loss | 7.18 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 77 |
| iterations | 13600 |
| time_elapsed | 880 |
| total_timesteps | 68000 |
| train/ | |
| entropy_loss | -45.7 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 13599 |
| policy_loss | 81.3 |
| std | 1.11 |
| value_loss | 14.1 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 13700 |
| time_elapsed | 887 |
| total_timesteps | 68500 |
| train/ | |
| entropy_loss | -45.7 |
| explained_variance | 1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 13699 |
| policy_loss | 104 |
| std | 1.11 |
| value_loss | 5.04 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 13800 |
| time_elapsed | 893 |
| total_timesteps | 69000 |
| train/ | |
| entropy_loss | -45.8 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 13799 |
| policy_loss | -263 |
| std | 1.11 |
| value_loss | 31.9 |
------------------------------------
day: 3650, episode: 20
begin_total_asset: 1000000.00
end_total_asset: 3959377.31
total_reward: 2959377.31
total_cost: 5535.60
total_trades: 64004
Sharpe: 0.755
=================================
------------------------------------
| environment/ | |
| portfolio_value | 3.96e+06 |
| total_cost | 5.54e+03 |
| total_reward | 2.96e+06 |
| total_reward_pct | 296 |
| total_trades | 64004 |
| time/ | |
| fps | 77 |
| iterations | 13900 |
| time_elapsed | 900 |
| total_timesteps | 69500 |
| train/ | |
| entropy_loss | -45.8 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 13899 |
| policy_loss | 25.9 |
| std | 1.11 |
| value_loss | 0.428 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 14000 |
| time_elapsed | 907 |
| total_timesteps | 70000 |
| train/ | |
| entropy_loss | -45.8 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 13999 |
| policy_loss | 40.9 |
| std | 1.12 |
| value_loss | 1.52 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 14100 |
| time_elapsed | 913 |
| total_timesteps | 70500 |
| train/ | |
| entropy_loss | -45.9 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 14099 |
| policy_loss | -0.995 |
| std | 1.12 |
| value_loss | 0.024 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 14200 |
| time_elapsed | 920 |
| total_timesteps | 71000 |
| train/ | |
| entropy_loss | -45.8 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 14199 |
| policy_loss | 21.5 |
| std | 1.12 |
| value_loss | 0.753 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 14300 |
| time_elapsed | 926 |
| total_timesteps | 71500 |
| train/ | |
| entropy_loss | -45.9 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 14299 |
| policy_loss | 96.7 |
| std | 1.12 |
| value_loss | 5.54 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 14400 |
| time_elapsed | 933 |
| total_timesteps | 72000 |
| train/ | |
| entropy_loss | -45.9 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 14399 |
| policy_loss | 99.8 |
| std | 1.12 |
| value_loss | 5.77 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 14500 |
| time_elapsed | 940 |
| total_timesteps | 72500 |
| train/ | |
| entropy_loss | -45.9 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 14499 |
| policy_loss | 43.6 |
| std | 1.12 |
| value_loss | 1.32 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 14600 |
| time_elapsed | 946 |
| total_timesteps | 73000 |
| train/ | |
| entropy_loss | -45.9 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 14599 |
| policy_loss | -874 |
| std | 1.12 |
| value_loss | 365 |
------------------------------------
------------------------------------
| environment/ | |
| portfolio_value | 3.87e+06 |
| total_cost | 5.34e+03 |
| total_reward | 2.87e+06 |
| total_reward_pct | 287 |
| total_trades | 67475 |
| time/ | |
| fps | 77 |
| iterations | 14700 |
| time_elapsed | 953 |
| total_timesteps | 73500 |
| train/ | |
| entropy_loss | -45.9 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 14699 |
| policy_loss | 36.2 |
| std | 1.12 |
| value_loss | 0.616 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 14800 |
| time_elapsed | 960 |
| total_timesteps | 74000 |
| train/ | |
| entropy_loss | -45.9 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 14799 |
| policy_loss | -129 |
| std | 1.12 |
| value_loss | 12.7 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 14900 |
| time_elapsed | 966 |
| total_timesteps | 74500 |
| train/ | |
| entropy_loss | -46 |
| explained_variance | 5.96e-08 |
| learning_rate | 0.0007 |
| n_updates | 14899 |
| policy_loss | 27.7 |
| std | 1.12 |
| value_loss | 1.76 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 15000 |
| time_elapsed | 973 |
| total_timesteps | 75000 |
| train/ | |
| entropy_loss | -46 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 14999 |
| policy_loss | 84 |
| std | 1.12 |
| value_loss | 5.1 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 77 |
| iterations | 15100 |
| time_elapsed | 979 |
| total_timesteps | 75500 |
| train/ | |
| entropy_loss | -45.9 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 15099 |
| policy_loss | -7.35 |
| std | 1.12 |
| value_loss | 1.71 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 15200 |
| time_elapsed | 986 |
| total_timesteps | 76000 |
| train/ | |
| entropy_loss | -45.9 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 15199 |
| policy_loss | 126 |
| std | 1.12 |
| value_loss | 8.75 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 15300 |
| time_elapsed | 993 |
| total_timesteps | 76500 |
| train/ | |
| entropy_loss | -45.9 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 15299 |
| policy_loss | 190 |
| std | 1.12 |
| value_loss | 31.7 |
------------------------------------
------------------------------------
| environment/ | |
| portfolio_value | 4.14e+06 |
| total_cost | 4.28e+03 |
| total_reward | 3.14e+06 |
| total_reward_pct | 314 |
| total_trades | 66224 |
| time/ | |
| fps | 77 |
| iterations | 15400 |
| time_elapsed | 999 |
| total_timesteps | 77000 |
| train/ | |
| entropy_loss | -46 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 15399 |
| policy_loss | 15.4 |
| std | 1.12 |
| value_loss | 0.418 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 77 |
| iterations | 15500 |
| time_elapsed | 1006 |
| total_timesteps | 77500 |
| train/ | |
| entropy_loss | -46.1 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 15499 |
| policy_loss | -1.22 |
| std | 1.13 |
| value_loss | 0.0144 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 15600 |
| time_elapsed | 1012 |
| total_timesteps | 78000 |
| train/ | |
| entropy_loss | -46.1 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 15599 |
| policy_loss | 126 |
| std | 1.13 |
| value_loss | 6.33 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 77 |
| iterations | 15700 |
| time_elapsed | 1019 |
| total_timesteps | 78500 |
| train/ | |
| entropy_loss | -46.2 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 15699 |
| policy_loss | -1.57 |
| std | 1.13 |
| value_loss | 0.0992 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 15800 |
| time_elapsed | 1026 |
| total_timesteps | 79000 |
| train/ | |
| entropy_loss | -46.2 |
| explained_variance | 1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 15799 |
| policy_loss | 177 |
| std | 1.13 |
| value_loss | 15.9 |
------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 15900 |
| time_elapsed | 1032 |
| total_timesteps | 79500 |
| train/ | |
| entropy_loss | -46.2 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 15899 |
| policy_loss | -99.7 |
| std | 1.13 |
| value_loss | 7.94 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 76 |
| iterations | 16000 |
| time_elapsed | 1039 |
| total_timesteps | 80000 |
| train/ | |
| entropy_loss | -46.2 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 15999 |
| policy_loss | -482 |
| std | 1.13 |
| value_loss | 114 |
-------------------------------------
-------------------------------------
| environment/ | |
| portfolio_value | 3.94e+06 |
| total_cost | 3.49e+03 |
| total_reward | 2.94e+06 |
| total_reward_pct | 294 |
| total_trades | 64301 |
| time/ | |
| fps | 76 |
| iterations | 16100 |
| time_elapsed | 1045 |
| total_timesteps | 80500 |
| train/ | |
| entropy_loss | -46.2 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 16099 |
| policy_loss | -23.5 |
| std | 1.13 |
| value_loss | 1.91 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 16200 |
| time_elapsed | 1052 |
| total_timesteps | 81000 |
| train/ | |
| entropy_loss | -46.3 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 16199 |
| policy_loss | 46.5 |
| std | 1.13 |
| value_loss | 3.81 |
------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 16300 |
| time_elapsed | 1058 |
| total_timesteps | 81500 |
| train/ | |
| entropy_loss | -46.3 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 16299 |
| policy_loss | 18.1 |
| std | 1.13 |
| value_loss | 0.592 |
------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 16400 |
| time_elapsed | 1065 |
| total_timesteps | 82000 |
| train/ | |
| entropy_loss | -46.3 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 16399 |
| policy_loss | 151 |
| std | 1.14 |
| value_loss | 11.9 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 76 |
| iterations | 16500 |
| time_elapsed | 1071 |
| total_timesteps | 82500 |
| train/ | |
| entropy_loss | -46.3 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 16499 |
| policy_loss | -151 |
| std | 1.13 |
| value_loss | 18.1 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 16600 |
| time_elapsed | 1078 |
| total_timesteps | 83000 |
| train/ | |
| entropy_loss | -46.3 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 16599 |
| policy_loss | -409 |
| std | 1.14 |
| value_loss | 79 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 77 |
| iterations | 16700 |
| time_elapsed | 1084 |
| total_timesteps | 83500 |
| train/ | |
| entropy_loss | -46.3 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 16699 |
| policy_loss | 44.8 |
| std | 1.14 |
| value_loss | 7.51 |
-------------------------------------
------------------------------------
| environment/ | |
| portfolio_value | 4.12e+06 |
| total_cost | 3.41e+03 |
| total_reward | 3.12e+06 |
| total_reward_pct | 312 |
| total_trades | 61475 |
| time/ | |
| fps | 77 |
| iterations | 16800 |
| time_elapsed | 1090 |
| total_timesteps | 84000 |
| train/ | |
| entropy_loss | -46.4 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 16799 |
| policy_loss | 11 |
| std | 1.14 |
| value_loss | 0.286 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 16900 |
| time_elapsed | 1097 |
| total_timesteps | 84500 |
| train/ | |
| entropy_loss | -46.4 |
| explained_variance | 1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 16899 |
| policy_loss | -24.2 |
| std | 1.14 |
| value_loss | 5.16 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 17000 |
| time_elapsed | 1103 |
| total_timesteps | 85000 |
| train/ | |
| entropy_loss | -46.4 |
| explained_variance | 1.79e-07 |
| learning_rate | 0.0007 |
| n_updates | 16999 |
| policy_loss | 38.8 |
| std | 1.14 |
| value_loss | 2.14 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 17100 |
| time_elapsed | 1110 |
| total_timesteps | 85500 |
| train/ | |
| entropy_loss | -46.4 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 17099 |
| policy_loss | 1.28 |
| std | 1.14 |
| value_loss | 0.161 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 17200 |
| time_elapsed | 1116 |
| total_timesteps | 86000 |
| train/ | |
| entropy_loss | -46.3 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 17199 |
| policy_loss | -175 |
| std | 1.14 |
| value_loss | 14.5 |
------------------------------------
------------------------------------
| time/ | |
| fps | 77 |
| iterations | 17300 |
| time_elapsed | 1123 |
| total_timesteps | 86500 |
| train/ | |
| entropy_loss | -46.3 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 17299 |
| policy_loss | -126 |
| std | 1.14 |
| value_loss | 11.5 |
------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 17400 |
| time_elapsed | 1129 |
| total_timesteps | 87000 |
| train/ | |
| entropy_loss | -46.4 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 17399 |
| policy_loss | -48.4 |
| std | 1.14 |
| value_loss | 1.55 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 76 |
| iterations | 17500 |
| time_elapsed | 1136 |
| total_timesteps | 87500 |
| train/ | |
| entropy_loss | -46.4 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 17499 |
| policy_loss | 139 |
| std | 1.14 |
| value_loss | 10.4 |
-------------------------------------
-------------------------------------
| environment/ | |
| portfolio_value | 4.17e+06 |
| total_cost | 6.22e+03 |
| total_reward | 3.17e+06 |
| total_reward_pct | 317 |
| total_trades | 58146 |
| time/ | |
| fps | 76 |
| iterations | 17600 |
| time_elapsed | 1142 |
| total_timesteps | 88000 |
| train/ | |
| entropy_loss | -46.4 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 17599 |
| policy_loss | 10.5 |
| std | 1.14 |
| value_loss | 0.0937 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 17700 |
| time_elapsed | 1149 |
| total_timesteps | 88500 |
| train/ | |
| entropy_loss | -46.3 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 17699 |
| policy_loss | -62.6 |
| std | 1.14 |
| value_loss | 2.89 |
------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 17800 |
| time_elapsed | 1156 |
| total_timesteps | 89000 |
| train/ | |
| entropy_loss | -46.4 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 17799 |
| policy_loss | 64.3 |
| std | 1.14 |
| value_loss | 1.99 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 76 |
| iterations | 17900 |
| time_elapsed | 1162 |
| total_timesteps | 89500 |
| train/ | |
| entropy_loss | -46.4 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 17899 |
| policy_loss | 36.1 |
| std | 1.14 |
| value_loss | 1.18 |
-------------------------------------
-------------------------------------
| time/ | |
| fps | 76 |
| iterations | 18000 |
| time_elapsed | 1169 |
| total_timesteps | 90000 |
| train/ | |
| entropy_loss | -46.4 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 17999 |
| policy_loss | 117 |
| std | 1.14 |
| value_loss | 13.6 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 18100 |
| time_elapsed | 1176 |
| total_timesteps | 90500 |
| train/ | |
| entropy_loss | -46.5 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 18099 |
| policy_loss | 138 |
| std | 1.14 |
| value_loss | 25.8 |
------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 18200 |
| time_elapsed | 1183 |
| total_timesteps | 91000 |
| train/ | |
| entropy_loss | -46.5 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 18199 |
| policy_loss | -109 |
| std | 1.14 |
| value_loss | 19.1 |
------------------------------------
------------------------------------
| environment/ | |
| portfolio_value | 4.4e+06 |
| total_cost | 8.75e+03 |
| total_reward | 3.4e+06 |
| total_reward_pct | 340 |
| total_trades | 64975 |
| time/ | |
| fps | 76 |
| iterations | 18300 |
| time_elapsed | 1189 |
| total_timesteps | 91500 |
| train/ | |
| entropy_loss | -46.5 |
| explained_variance | -0.0014 |
| learning_rate | 0.0007 |
| n_updates | 18299 |
| policy_loss | 22 |
| std | 1.14 |
| value_loss | 0.829 |
------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 18400 |
| time_elapsed | 1196 |
| total_timesteps | 92000 |
| train/ | |
| entropy_loss | -46.7 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 18399 |
| policy_loss | 12.7 |
| std | 1.15 |
| value_loss | 0.192 |
------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 18500 |
| time_elapsed | 1202 |
| total_timesteps | 92500 |
| train/ | |
| entropy_loss | -46.6 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 18499 |
| policy_loss | -80.5 |
| std | 1.15 |
| value_loss | 5.62 |
------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 18600 |
| time_elapsed | 1209 |
| total_timesteps | 93000 |
| train/ | |
| entropy_loss | -46.6 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 18599 |
| policy_loss | 127 |
| std | 1.15 |
| value_loss | 8.09 |
------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 18700 |
| time_elapsed | 1215 |
| total_timesteps | 93500 |
| train/ | |
| entropy_loss | -46.6 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 18699 |
| policy_loss | -108 |
| std | 1.15 |
| value_loss | 17.2 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 76 |
| iterations | 18800 |
| time_elapsed | 1222 |
| total_timesteps | 94000 |
| train/ | |
| entropy_loss | -46.7 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 18799 |
| policy_loss | -145 |
| std | 1.15 |
| value_loss | 11.8 |
-------------------------------------
-------------------------------------
| time/ | |
| fps | 76 |
| iterations | 18900 |
| time_elapsed | 1229 |
| total_timesteps | 94500 |
| train/ | |
| entropy_loss | -46.6 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 18899 |
| policy_loss | 150 |
| std | 1.15 |
| value_loss | 14.4 |
-------------------------------------
------------------------------------
| environment/ | |
| portfolio_value | 4.16e+06 |
| total_cost | 7.62e+03 |
| total_reward | 3.16e+06 |
| total_reward_pct | 316 |
| total_trades | 66603 |
| time/ | |
| fps | 76 |
| iterations | 19000 |
| time_elapsed | 1235 |
| total_timesteps | 95000 |
| train/ | |
| entropy_loss | -46.6 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 18999 |
| policy_loss | 260 |
| std | 1.15 |
| value_loss | 30.2 |
------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 19100 |
| time_elapsed | 1242 |
| total_timesteps | 95500 |
| train/ | |
| entropy_loss | -46.6 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 19099 |
| policy_loss | 97.7 |
| std | 1.15 |
| value_loss | 7.94 |
------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 19200 |
| time_elapsed | 1248 |
| total_timesteps | 96000 |
| train/ | |
| entropy_loss | -46.6 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 19199 |
| policy_loss | 53.5 |
| std | 1.15 |
| value_loss | 1.59 |
------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 19300 |
| time_elapsed | 1255 |
| total_timesteps | 96500 |
| train/ | |
| entropy_loss | -46.6 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 19299 |
| policy_loss | 165 |
| std | 1.15 |
| value_loss | 15.8 |
------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 19400 |
| time_elapsed | 1262 |
| total_timesteps | 97000 |
| train/ | |
| entropy_loss | -46.6 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 19399 |
| policy_loss | 1.48 |
| std | 1.15 |
| value_loss | 0.168 |
------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 19500 |
| time_elapsed | 1268 |
| total_timesteps | 97500 |
| train/ | |
| entropy_loss | -46.7 |
| explained_variance | 5.96e-08 |
| learning_rate | 0.0007 |
| n_updates | 19499 |
| policy_loss | -463 |
| std | 1.15 |
| value_loss | 104 |
------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 19600 |
| time_elapsed | 1275 |
| total_timesteps | 98000 |
| train/ | |
| entropy_loss | -46.7 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 19599 |
| policy_loss | -39.8 |
| std | 1.15 |
| value_loss | 1.29 |
------------------------------------
-------------------------------------
| time/ | |
| fps | 76 |
| iterations | 19700 |
| time_elapsed | 1281 |
| total_timesteps | 98500 |
| train/ | |
| entropy_loss | -46.8 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 19699 |
| policy_loss | -1.11e+03 |
| std | 1.15 |
| value_loss | 583 |
-------------------------------------
-------------------------------------
| environment/ | |
| portfolio_value | 4.42e+06 |
| total_cost | 5.67e+03 |
| total_reward | 3.42e+06 |
| total_reward_pct | 342 |
| total_trades | 57577 |
| time/ | |
| fps | 76 |
| iterations | 19800 |
| time_elapsed | 1288 |
| total_timesteps | 99000 |
| train/ | |
| entropy_loss | -46.7 |
| explained_variance | -1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 19799 |
| policy_loss | -3.03 |
| std | 1.15 |
| value_loss | 0.427 |
-------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 19900 |
| time_elapsed | 1295 |
| total_timesteps | 99500 |
| train/ | |
| entropy_loss | -46.8 |
| explained_variance | 0 |
| learning_rate | 0.0007 |
| n_updates | 19899 |
| policy_loss | -127 |
| std | 1.15 |
| value_loss | 6.54 |
------------------------------------
------------------------------------
| time/ | |
| fps | 76 |
| iterations | 20000 |
| time_elapsed | 1301 |
| total_timesteps | 100000 |
| train/ | |
| entropy_loss | -46.8 |
| explained_variance | 1.19e-07 |
| learning_rate | 0.0007 |
| n_updates | 19999 |
| policy_loss | 79.1 |
| std | 1.15 |
| value_loss | 4.91 |
------------------------------------
###Markdown
Model 2: DDPG
###Code
agent = DRLAgent(env = env_train)
model_ddpg = agent.get_model("ddpg")
trained_ddpg = agent.train_model(model=model_ddpg,
tb_log_name='ddpg',
total_timesteps=50000)
###Output
Logging to tensorboard_log/ddpg/ddpg_3
---------------------------------
| time/ | |
| episodes | 4 |
| fps | 66 |
| time_elapsed | 218 |
| total timesteps | 14604 |
| train/ | |
| actor_loss | -40.1 |
| critic_loss | 213 |
| learning_rate | 0.001 |
| n_updates | 10953 |
---------------------------------
---------------------------------
| time/ | |
| episodes | 8 |
| fps | 62 |
| time_elapsed | 463 |
| total timesteps | 29208 |
| train/ | |
| actor_loss | -14.9 |
| critic_loss | 2.92 |
| learning_rate | 0.001 |
| n_updates | 25557 |
---------------------------------
day: 3650, episode: 40
begin_total_asset: 1000000.00
end_total_asset: 3024712.17
total_reward: 2024712.17
total_cost: 999.00
total_trades: 72983
Sharpe: 0.626
=================================
---------------------------------
| time/ | |
| episodes | 12 |
| fps | 61 |
| time_elapsed | 710 |
| total timesteps | 43812 |
| train/ | |
| actor_loss | -10.4 |
| critic_loss | 2.28 |
| learning_rate | 0.001 |
| n_updates | 40161 |
---------------------------------
###Markdown
Model 3: PPO
###Code
agent = DRLAgent(env = env_train)
PPO_PARAMS = {
"n_steps": 2048,
"ent_coef": 0.01,
"learning_rate": 0.00025,
"batch_size": 128,
}
model_ppo = agent.get_model("ppo",model_kwargs = PPO_PARAMS)
trained_ppo = agent.train_model(model=model_ppo,
tb_log_name='ppo',
total_timesteps=50000)
###Output
Logging to tensorboard_log/ppo/ppo_1
-----------------------------
| time/ | |
| fps | 76 |
| iterations | 1 |
| time_elapsed | 26 |
| total_timesteps | 2048 |
-----------------------------
-----------------------------------------
| time/ | |
| fps | 75 |
| iterations | 2 |
| time_elapsed | 54 |
| total_timesteps | 4096 |
| train/ | |
| approx_kl | 0.018077655 |
| clip_fraction | 0.231 |
| clip_range | 0.2 |
| entropy_loss | -42.6 |
| explained_variance | -0.0123 |
| learning_rate | 0.00025 |
| loss | 3.1 |
| n_updates | 10 |
| policy_gradient_loss | -0.0292 |
| std | 1 |
| value_loss | 7.21 |
-----------------------------------------
-----------------------------------------
| time/ | |
| fps | 75 |
| iterations | 3 |
| time_elapsed | 81 |
| total_timesteps | 6144 |
| train/ | |
| approx_kl | 0.013950874 |
| clip_fraction | 0.17 |
| clip_range | 0.2 |
| entropy_loss | -42.6 |
| explained_variance | -0.00143 |
| learning_rate | 0.00025 |
| loss | 5.92 |
| n_updates | 20 |
| policy_gradient_loss | -0.0229 |
| std | 1 |
| value_loss | 13.6 |
-----------------------------------------
----------------------------------------
| time/ | |
| fps | 74 |
| iterations | 4 |
| time_elapsed | 109 |
| total_timesteps | 8192 |
| train/ | |
| approx_kl | 0.01641549 |
| clip_fraction | 0.183 |
| clip_range | 0.2 |
| entropy_loss | -42.6 |
| explained_variance | -0.0118 |
| learning_rate | 0.00025 |
| loss | 6.06 |
| n_updates | 30 |
| policy_gradient_loss | -0.0282 |
| std | 1 |
| value_loss | 11.9 |
----------------------------------------
-----------------------------------------
| time/ | |
| fps | 74 |
| iterations | 5 |
| time_elapsed | 136 |
| total_timesteps | 10240 |
| train/ | |
| approx_kl | 0.025979618 |
| clip_fraction | 0.241 |
| clip_range | 0.2 |
| entropy_loss | -42.7 |
| explained_variance | -0.00485 |
| learning_rate | 0.00025 |
| loss | 13 |
| n_updates | 40 |
| policy_gradient_loss | -0.0157 |
| std | 1 |
| value_loss | 19.3 |
-----------------------------------------
-----------------------------------------
| time/ | |
| fps | 74 |
| iterations | 6 |
| time_elapsed | 163 |
| total_timesteps | 12288 |
| train/ | |
| approx_kl | 0.016590398 |
| clip_fraction | 0.21 |
| clip_range | 0.2 |
| entropy_loss | -42.7 |
| explained_variance | -0.0153 |
| learning_rate | 0.00025 |
| loss | 3.53 |
| n_updates | 50 |
| policy_gradient_loss | -0.0251 |
| std | 1.01 |
| value_loss | 11 |
-----------------------------------------
-----------------------------------------
| time/ | |
| fps | 74 |
| iterations | 7 |
| time_elapsed | 191 |
| total_timesteps | 14336 |
| train/ | |
| approx_kl | 0.020591479 |
| clip_fraction | 0.229 |
| clip_range | 0.2 |
| entropy_loss | -42.8 |
| explained_variance | 0.0132 |
| learning_rate | 0.00025 |
| loss | 6.55 |
| n_updates | 60 |
| policy_gradient_loss | -0.0197 |
| std | 1.01 |
| value_loss | 14.2 |
-----------------------------------------
day: 3650, episode: 20
begin_total_asset: 1000000.00
end_total_asset: 2689089.43
total_reward: 1689089.43
total_cost: 380034.51
total_trades: 104033
Sharpe: 0.638
=================================
-----------------------------------------
| time/ | |
| fps | 74 |
| iterations | 8 |
| time_elapsed | 218 |
| total_timesteps | 16384 |
| train/ | |
| approx_kl | 0.020969098 |
| clip_fraction | 0.268 |
| clip_range | 0.2 |
| entropy_loss | -42.9 |
| explained_variance | -0.000622 |
| learning_rate | 0.00025 |
| loss | 7 |
| n_updates | 70 |
| policy_gradient_loss | -0.0173 |
| std | 1.01 |
| value_loss | 12.7 |
-----------------------------------------
----------------------------------------
| time/ | |
| fps | 74 |
| iterations | 9 |
| time_elapsed | 246 |
| total_timesteps | 18432 |
| train/ | |
| approx_kl | 0.02511882 |
| clip_fraction | 0.28 |
| clip_range | 0.2 |
| entropy_loss | -43 |
| explained_variance | -0.0182 |
| learning_rate | 0.00025 |
| loss | 5.87 |
| n_updates | 80 |
| policy_gradient_loss | -0.0152 |
| std | 1.02 |
| value_loss | 11.4 |
----------------------------------------
----------------------------------------
| time/ | |
| fps | 74 |
| iterations | 10 |
| time_elapsed | 273 |
| total_timesteps | 20480 |
| train/ | |
| approx_kl | 0.02978786 |
| clip_fraction | 0.276 |
| clip_range | 0.2 |
| entropy_loss | -43.1 |
| explained_variance | 0.00553 |
| learning_rate | 0.00025 |
| loss | 7.83 |
| n_updates | 90 |
| policy_gradient_loss | -0.0169 |
| std | 1.02 |
| value_loss | 18 |
----------------------------------------
----------------------------------------
| time/ | |
| fps | 74 |
| iterations | 11 |
| time_elapsed | 301 |
| total_timesteps | 22528 |
| train/ | |
| approx_kl | 0.02986148 |
| clip_fraction | 0.263 |
| clip_range | 0.2 |
| entropy_loss | -43.1 |
| explained_variance | -0.0465 |
| learning_rate | 0.00025 |
| loss | 4.94 |
| n_updates | 100 |
| policy_gradient_loss | -0.0156 |
| std | 1.02 |
| value_loss | 9.13 |
----------------------------------------
---------------------------------------
| time/ | |
| fps | 74 |
| iterations | 12 |
| time_elapsed | 328 |
| total_timesteps | 24576 |
| train/ | |
| approx_kl | 0.0287299 |
| clip_fraction | 0.267 |
| clip_range | 0.2 |
| entropy_loss | -43.2 |
| explained_variance | -0.00762 |
| learning_rate | 0.00025 |
| loss | 9.6 |
| n_updates | 110 |
| policy_gradient_loss | -0.0165 |
| std | 1.02 |
| value_loss | 20.9 |
---------------------------------------
-----------------------------------------
| time/ | |
| fps | 74 |
| iterations | 13 |
| time_elapsed | 355 |
| total_timesteps | 26624 |
| train/ | |
| approx_kl | 0.023247771 |
| clip_fraction | 0.264 |
| clip_range | 0.2 |
| entropy_loss | -43.2 |
| explained_variance | -0.0257 |
| learning_rate | 0.00025 |
| loss | 2.04 |
| n_updates | 120 |
| policy_gradient_loss | -0.0105 |
| std | 1.02 |
| value_loss | 6.91 |
-----------------------------------------
-----------------------------------------
| time/ | |
| fps | 74 |
| iterations | 14 |
| time_elapsed | 382 |
| total_timesteps | 28672 |
| train/ | |
| approx_kl | 0.020957708 |
| clip_fraction | 0.243 |
| clip_range | 0.2 |
| entropy_loss | -43.3 |
| explained_variance | -0.00506 |
| learning_rate | 0.00025 |
| loss | 3.57 |
| n_updates | 130 |
| policy_gradient_loss | -0.0166 |
| std | 1.02 |
| value_loss | 11.4 |
-----------------------------------------
-----------------------------------------
| time/ | |
| fps | 74 |
| iterations | 15 |
| time_elapsed | 410 |
| total_timesteps | 30720 |
| train/ | |
| approx_kl | 0.032833345 |
| clip_fraction | 0.296 |
| clip_range | 0.2 |
| entropy_loss | -43.4 |
| explained_variance | -0.0181 |
| learning_rate | 0.00025 |
| loss | 2.71 |
| n_updates | 140 |
| policy_gradient_loss | -0.0192 |
| std | 1.03 |
| value_loss | 7.09 |
-----------------------------------------
----------------------------------------
| time/ | |
| fps | 74 |
| iterations | 16 |
| time_elapsed | 437 |
| total_timesteps | 32768 |
| train/ | |
| approx_kl | 0.02443498 |
| clip_fraction | 0.241 |
| clip_range | 0.2 |
| entropy_loss | -43.5 |
| explained_variance | -0.0293 |
| learning_rate | 0.00025 |
| loss | 4.9 |
| n_updates | 150 |
| policy_gradient_loss | -0.0277 |
| std | 1.03 |
| value_loss | 8.48 |
----------------------------------------
-----------------------------------------
| time/ | |
| fps | 74 |
| iterations | 17 |
| time_elapsed | 464 |
| total_timesteps | 34816 |
| train/ | |
| approx_kl | 0.016761096 |
| clip_fraction | 0.233 |
| clip_range | 0.2 |
| entropy_loss | -43.5 |
| explained_variance | -0.0188 |
| learning_rate | 0.00025 |
| loss | 3 |
| n_updates | 160 |
| policy_gradient_loss | -0.0162 |
| std | 1.03 |
| value_loss | 9.8 |
-----------------------------------------
----------------------------------------
| time/ | |
| fps | 74 |
| iterations | 18 |
| time_elapsed | 491 |
| total_timesteps | 36864 |
| train/ | |
| approx_kl | 0.03664797 |
| clip_fraction | 0.34 |
| clip_range | 0.2 |
| entropy_loss | -43.6 |
| explained_variance | 0.00438 |
| learning_rate | 0.00025 |
| loss | 4.71 |
| n_updates | 170 |
| policy_gradient_loss | -0.0206 |
| std | 1.04 |
| value_loss | 6.72 |
----------------------------------------
-----------------------------------------
| time/ | |
| fps | 74 |
| iterations | 19 |
| time_elapsed | 518 |
| total_timesteps | 38912 |
| train/ | |
| approx_kl | 0.030327313 |
| clip_fraction | 0.308 |
| clip_range | 0.2 |
| entropy_loss | -43.6 |
| explained_variance | 0.0309 |
| learning_rate | 0.00025 |
| loss | 6 |
| n_updates | 180 |
| policy_gradient_loss | -0.00991 |
| std | 1.04 |
| value_loss | 11.2 |
-----------------------------------------
-----------------------------------------
| time/ | |
| fps | 75 |
| iterations | 20 |
| time_elapsed | 545 |
| total_timesteps | 40960 |
| train/ | |
| approx_kl | 0.028725432 |
| clip_fraction | 0.244 |
| clip_range | 0.2 |
| entropy_loss | -43.7 |
| explained_variance | 0.0224 |
| learning_rate | 0.00025 |
| loss | 1.66 |
| n_updates | 190 |
| policy_gradient_loss | -0.00988 |
| std | 1.04 |
| value_loss | 6.45 |
-----------------------------------------
-----------------------------------------
| time/ | |
| fps | 75 |
| iterations | 21 |
| time_elapsed | 573 |
| total_timesteps | 43008 |
| train/ | |
| approx_kl | 0.035785355 |
| clip_fraction | 0.252 |
| clip_range | 0.2 |
| entropy_loss | -43.8 |
| explained_variance | -0.00199 |
| learning_rate | 0.00025 |
| loss | 7.69 |
| n_updates | 200 |
| policy_gradient_loss | -0.00915 |
| std | 1.04 |
| value_loss | 14.2 |
-----------------------------------------
----------------------------------------
| time/ | |
| fps | 75 |
| iterations | 22 |
| time_elapsed | 600 |
| total_timesteps | 45056 |
| train/ | |
| approx_kl | 0.02488321 |
| clip_fraction | 0.259 |
| clip_range | 0.2 |
| entropy_loss | -43.8 |
| explained_variance | 0.0224 |
| learning_rate | 0.00025 |
| loss | 3.55 |
| n_updates | 210 |
| policy_gradient_loss | -0.00496 |
| std | 1.04 |
| value_loss | 8.94 |
----------------------------------------
-----------------------------------------
| time/ | |
| fps | 75 |
| iterations | 23 |
| time_elapsed | 627 |
| total_timesteps | 47104 |
| train/ | |
| approx_kl | 0.024153344 |
| clip_fraction | 0.272 |
| clip_range | 0.2 |
| entropy_loss | -43.9 |
| explained_variance | -0.0405 |
| learning_rate | 0.00025 |
| loss | 5.38 |
| n_updates | 220 |
| policy_gradient_loss | -0.0153 |
| std | 1.05 |
| value_loss | 14.4 |
-----------------------------------------
-----------------------------------------
| time/ | |
| fps | 75 |
| iterations | 24 |
| time_elapsed | 654 |
| total_timesteps | 49152 |
| train/ | |
| approx_kl | 0.037768982 |
| clip_fraction | 0.309 |
| clip_range | 0.2 |
| entropy_loss | -44 |
| explained_variance | -0.00958 |
| learning_rate | 0.00025 |
| loss | 4.37 |
| n_updates | 230 |
| policy_gradient_loss | 0.00366 |
| std | 1.05 |
| value_loss | 12.4 |
-----------------------------------------
day: 3650, episode: 30
begin_total_asset: 1000000.00
end_total_asset: 3250700.91
total_reward: 2250700.91
total_cost: 329606.76
total_trades: 98701
Sharpe: 0.750
=================================
-----------------------------------------
| time/ | |
| fps | 75 |
| iterations | 25 |
| time_elapsed | 681 |
| total_timesteps | 51200 |
| train/ | |
| approx_kl | 0.034196474 |
| clip_fraction | 0.301 |
| clip_range | 0.2 |
| entropy_loss | -44.1 |
| explained_variance | -0.00227 |
| learning_rate | 0.00025 |
| loss | 3.84 |
| n_updates | 240 |
| policy_gradient_loss | -0.0192 |
| std | 1.05 |
| value_loss | 11.4 |
-----------------------------------------
###Markdown
Model 4: TD3
###Code
agent = DRLAgent(env = env_train)
TD3_PARAMS = {"batch_size": 100,
"buffer_size": 1000000,
"learning_rate": 0.001}
model_td3 = agent.get_model("td3",model_kwargs = TD3_PARAMS)
trained_td3 = agent.train_model(model=model_td3,
tb_log_name='td3',
total_timesteps=30000)
###Output
Logging to tensorboard_log/td3/td3_1
---------------------------------
| time/ | |
| episodes | 4 |
| fps | 26 |
| time_elapsed | 559 |
| total timesteps | 14604 |
| train/ | |
| actor_loss | 4.64 |
| critic_loss | 720 |
| learning_rate | 0.001 |
| n_updates | 10953 |
---------------------------------
---------------------------------
| time/ | |
| episodes | 8 |
| fps | 22 |
| time_elapsed | 1289 |
| total timesteps | 29208 |
| train/ | |
| actor_loss | 10.6 |
| critic_loss | 14.2 |
| learning_rate | 0.001 |
| n_updates | 25557 |
---------------------------------
day: 3650, episode: 40
begin_total_asset: 1000000.00
end_total_asset: 3319811.55
total_reward: 2319811.55
total_cost: 998.99
total_trades: 51100
Sharpe: 0.649
=================================
###Markdown
Model 5: SAC
###Code
agent = DRLAgent(env = env_train)
SAC_PARAMS = {
"batch_size": 128,
"buffer_size": 1000000,
"learning_rate": 0.0001,
"learning_starts": 100,
"ent_coef": "auto_0.1",
}
model_sac = agent.get_model("sac",model_kwargs = SAC_PARAMS)
trained_sac = agent.train_model(model=model_sac,
tb_log_name='sac',
total_timesteps=80000)
###Output
Logging to tensorboard_log/sac/sac_2
---------------------------------
| time/ | |
| episodes | 4 |
| fps | 21 |
| time_elapsed | 685 |
| total timesteps | 14604 |
| train/ | |
| actor_loss | 172 |
| critic_loss | 28.6 |
| ent_coef | 0.0742 |
| ent_coef_loss | -126 |
| learning_rate | 0.0001 |
| n_updates | 14503 |
---------------------------------
---------------------------------
| time/ | |
| episodes | 8 |
| fps | 20 |
| time_elapsed | 1401 |
| total timesteps | 29208 |
| train/ | |
| actor_loss | 9.68 |
| critic_loss | 9.81 |
| ent_coef | 0.0174 |
| ent_coef_loss | -173 |
| learning_rate | 0.0001 |
| n_updates | 29107 |
---------------------------------
day: 3650, episode: 10
begin_total_asset: 1000000.00
end_total_asset: 4889674.97
total_reward: 3889674.97
total_cost: 7706.97
total_trades: 70158
Sharpe: 0.752
=================================
---------------------------------
| time/ | |
| episodes | 12 |
| fps | 20 |
| time_elapsed | 2114 |
| total timesteps | 43812 |
| train/ | |
| actor_loss | -13.3 |
| critic_loss | 14 |
| ent_coef | 0.00427 |
| ent_coef_loss | -128 |
| learning_rate | 0.0001 |
| n_updates | 43711 |
---------------------------------
---------------------------------
| time/ | |
| episodes | 16 |
| fps | 20 |
| time_elapsed | 2842 |
| total timesteps | 58416 |
| train/ | |
| actor_loss | -7 |
| critic_loss | 8.71 |
| ent_coef | 0.00148 |
| ent_coef_loss | -3.87 |
| learning_rate | 0.0001 |
| n_updates | 58315 |
---------------------------------
day: 3650, episode: 20
begin_total_asset: 1000000.00
end_total_asset: 3389166.27
total_reward: 2389166.27
total_cost: 1895.61
total_trades: 62481
Sharpe: 0.623
=================================
---------------------------------
| time/ | |
| episodes | 20 |
| fps | 20 |
| time_elapsed | 3585 |
| total timesteps | 73020 |
| train/ | |
| actor_loss | -4.82 |
| critic_loss | 12.4 |
| ent_coef | 0.00159 |
| ent_coef_loss | -4.38 |
| learning_rate | 0.0001 |
| n_updates | 72919 |
---------------------------------
###Markdown
TradingAssume that we have $1,000,000 initial capital at 2019-01-01. We use the DDPG model to trade Dow jones 30 stocks. TradeDRL model needs to update periodically in order to take full advantage of the data, ideally we need to retrain our model yearly, quarterly, or monthly. We also need to tune the parameters along the way, in this notebook I only use the in-sample data from 2009-01 to 2018-12 to tune the parameters once, so there is some alpha decay here as the length of trade date extends. Numerous hyperparameters – e.g. the learning rate, the total number of samples to train on – influence the learning process and are usually determined by testing some variations.
###Code
trade = data_split(processed_full, '2019-01-01','2021-01-01')
e_trade_gym = StockTradingEnv(df = trade, **env_kwargs)
# env_trade, obs_trade = e_trade_gym.get_sb_env()
trade.head()
df_account_value, df_actions = DRLAgent.DRL_prediction(
model=trained_ddpg,
environment = e_trade_gym)
df_account_value.shape
df_account_value.tail()
df_actions.head()
###Output
_____no_output_____
###Markdown
Part 7: Backtest Our StrategyBacktesting plays a key role in evaluating the performance of a trading strategy. Automated backtesting tool is preferred because it reduces the human error. We usually use the Quantopian pyfolio package to backtest our trading strategies. It is easy to use and consists of various individual plots that provide a comprehensive image of the performance of a trading strategy. 7.1 BackTestStatspass in df_account_value, this information is stored in env class
###Code
print("==============Get Backtest Results===========")
now = datetime.datetime.now().strftime('%Y%m%d-%Hh%M')
perf_stats_all = backtest_stats(account_value=df_account_value)
perf_stats_all = pd.DataFrame(perf_stats_all)
perf_stats_all.to_csv("./"+config.RESULTS_DIR+"/perf_stats_all_"+now+'.csv')
#baseline stats
print("==============Get Baseline Stats===========")
baseline_df = get_baseline(
ticker="^DJI",
start = '2019-01-01',
end = '2021-01-01')
stats = backtest_stats(baseline_df, value_col_name = 'close')
###Output
==============Get Baseline Stats===========
[*********************100%***********************] 1 of 1 completed
Shape of DataFrame: (505, 8)
Annual return 0.144674
Cumulative returns 0.310981
Annual volatility 0.274619
Sharpe ratio 0.631418
Calmar ratio 0.390102
Stability 0.116677
Max drawdown -0.370862
Omega ratio 1.149365
Sortino ratio 0.870084
Skew NaN
Kurtosis NaN
Tail ratio 0.860710
Daily value at risk -0.033911
dtype: float64
###Markdown
7.2 BackTestPlot
###Code
print("==============Compare to DJIA===========")
%matplotlib inline
# S&P 500: ^GSPC
# Dow Jones Index: ^DJI
# NASDAQ 100: ^NDX
backtest_plot(df_account_value,
baseline_ticker = '^DJI',
baseline_start = '2019-01-01',
baseline_end = '2021-01-01')
###Output
_____no_output_____ |
comrx/dev/comics_rx-01_data_prep.ipynb | ###Markdown
Comics Rx [A comic book recommendation system](https://github.com/MangrobanGit/comics_rx) --- A. Data Procurement and Cleaning --- Libraries
###Code
!pip install psycopg2
%matplotlib inline
%load_ext autoreload
%autoreload 2 # 1 would be where you need to specify the files
#%aimport data_fcns
import pandas as pd # dataframes
import os
import gspread_pandas
from gspread_pandas import Spread, Client # gsheets interaction
# Data storage
from sqlalchemy import create_engine # SQL helper
import psycopg2 as psql #PostgreSQL DBs
import sys
sys.path.append('..')
# Custom
import data_fcns as dfc
import keys # Custom keys lib
###Output
_____no_output_____
###Markdown
Part 1: Get and Prep Data Import Arcane's transaction data Using **Google Sheets** as a data sourceThe data is currently stored on Google drive, and is readable as a Google Sheet. I'm going to try to use a Google Sheet API to get into Pandas so I don't have to worry about it traversing across my local machine everytime I need to re-import it. Before starting you need your credentials stored on your computer. More details [here](https://gspread-pandas.readthedocs.io/en/latest/getting_started.htmlinstallation-usage).
###Code
#gspread_pandas.conf.get_config()
###Output
_____no_output_____
###Markdown
Work through `gspread_pandas` Example
###Code
file_name = "http://stats.idre.ucla.edu/stat/data/binary.csv"
df = pd.read_csv(file_name)
df.head()
spread = Spread('https://docs.google.com/spreadsheets/d/19_AEcTEwHXe7LS-U1scZIHLqP0iF7W4UYMiSlBUE5bs/edit#gid=0')
spread.sheets
spread.url
spread.open_sheet(0)
spread
deef = spread.sheet_to_df(index=None)
deef
###Output
_____no_output_____
###Markdown
**Sweet!** That example worked. I was able to download a Google Sheet into this Juypter Notebook as a `pandas dataframe`. Let's try to get the dataset! Get the transactions dataset **Instantiate spreadsheet object**
###Code
sheet_url = 'https://docs.google.com/spreadsheets/d/1IznAOevvBbV0k3OKPImUMUESSwWXoOaASngPJUepnlU'
trans = Spread(sheet_url)
###Output
_____no_output_____
###Markdown
**Double check details of the spreadsheet to make sure we are looking at the correct one.**
###Code
print(trans.sheets)
print(trans.url)
###Output
[<Worksheet 'Copy of Detailed Sales Report.tab' id:1615090597>]
https://docs.google.com/spreadsheets/d/1IznAOevvBbV0k3OKPImUMUESSwWXoOaASngPJUepnlU
###Markdown
**Open the sheet and dump into a Pandas dataframe**
###Code
trans.open_sheet(0)
trans_df = trans.sheet_to_df(index=None, start_row=3)
trans_df.head()
trans_df.tail()
###Output
_____no_output_____
###Markdown
We started at row 3 because I could see that the 'actual' headers didn't start until the third row. We can see the first two rows are likely just summary rows; we can take care of those down below.Seems good so far. Let's list some tasks we want to accomplish, just from inspecting the rows above: - Standardize column headers - Make sure date sold is a `date` - Change `Account ` to a string? - Is `;Department` all the same value? In which case we can probably just drop it. --- Let's get started. I will save a copy first so I won't have to keep re-importing it from Google Sheets (in case we make a mistake).
###Code
trans_df_orig = trans_df.copy()
###Output
_____no_output_____
###Markdown
Drop rows without account numbers.This should eliminate the superfluous summary rows.
###Code
trans_df = trans_df.loc[trans_df['Account #']!='',:].copy()
###Output
_____no_output_____
###Markdown
Check the values of `;Department`
###Code
trans_df[';Department'].unique()
###Output
_____no_output_____
###Markdown
They're all the same. Drop `;Department` column.
###Code
trans_df.drop([';Department'], axis=1, inplace=True)
trans_df.head()
###Output
_____no_output_____
###Markdown
The rest of the columns look useful. Now's a good time to change the column headers to a more standard format.`Category` looks like Publisher. Let's get the lay of the land.
###Code
trans_df['Category'].value_counts()
###Output
_____no_output_____
###Markdown
It looks like it's basically the publisher fo the comic. This is likely the context of Category relative to `;Department` of `New Comics` that we dropped earlier.Let's look at those headers again.
###Code
trans_df.head(1)
###Output
_____no_output_____
###Markdown
Assign new column names.
###Code
# Create list of new column names
col_names = ['publisher', 'item_id', 'title_and_num', 'qty_sold', 'date_sold', 'account_num']
trans_df.columns = col_names
trans_df.head(1)
###Output
_____no_output_____
###Markdown
Convert Account Number to string with leading zeroesLet's look at those account numbers.
###Code
trans_df['account_num'].value_counts()
trans_df['account_num'].max()
###Output
_____no_output_____
###Markdown
That's not what I expected for max. Probably a string.
###Code
trans_df.info()
###Output
<class 'pandas.core.frame.DataFrame'>
Int64Index: 494703 entries, 2 to 494704
Data columns (total 6 columns):
publisher 494703 non-null object
item_id 494703 non-null object
title_and_num 494703 non-null object
qty_sold 494703 non-null object
date_sold 494703 non-null object
account_num 494703 non-null object
dtypes: object(6)
memory usage: 26.4+ MB
###Markdown
Yes, that is the case.
###Code
trans_df['account_num'].astype(int).max()
###Output
_____no_output_____
###Markdown
Ok that seems more realistic. Let's add some leading zeros. Since there are about 3K accounts, let's just settle on 5 characters.
###Code
trans_df['account_num'] = trans_df['account_num'].str.zfill(5)
trans_df['account_num'].head()
trans_df.head()
###Output
_____no_output_____
###Markdown
Convert dates Found a relatively quick date converter on StackOverflow: https://stackoverflow.com/questions/29882573/pandas-slow-date-conversionSaved a copy in custom libary, `data_fcns`
###Code
trans_df['date_sold'] = dfc.date_converter(trans_df['date_sold'])
trans_df.head()
trans_df.tail()
###Output
_____no_output_____
###Markdown
Seems ok! Create `comic_title` columnIndividual issues are not going to work for recommendations. We'll need to roll it up to title/volume is possible. For example: *Spider-Man* is useful; *Spider-Man 23* is not.Based on what data we have available at this time, for the time being I think the following will have to suffice to proxy `comic_title`:- Cut off the issue number off of `title_and_num`- Concatenate `publisher` on the back end to prevent any potential duplicate titles across publishers. We created function to strip off everything to the right of the pound sign () on a string, named `cut_issue_num`. Refer to the library `data_fcns`.
###Code
trans_df['comic_title'] = (trans_df['title_and_num'].apply(dfc.cut_issue_num)
+ ' (' + trans_df['publisher'] + ')')
trans_df.head()
###Output
_____no_output_____
###Markdown
The publisher names can be unwieldly long. I will create a dictionary to shorten so easier to digest the title names once the the publisher is concatentated. Refer to `code_archive.py` and `data_fcns.py` for development and final output.
###Code
dfc.pub_dict
###Output
_____no_output_____
###Markdown
Ok, let's go ahead and redo the `comic_title` with the shorter publisher names.
###Code
trans_df['comic_title'] = (trans_df['title_and_num'].apply(dfc.cut_issue_num) +
' (' + trans_df['publisher'].map(dfc.pub_dict) +
')')
trans_df.head()
trans_df.tail()
###Output
_____no_output_____
###Markdown
YES.Okay, I think the last task is to convert the `qty_sold` column to an integer. Convert `qty_sold` to integer
###Code
trans_df['qty_sold'] = trans_df['qty_sold'].astype(int)
trans_df.head()
trans_df.info()
###Output
<class 'pandas.core.frame.DataFrame'>
Int64Index: 494703 entries, 2 to 494704
Data columns (total 7 columns):
publisher 494703 non-null object
item_id 494703 non-null object
title_and_num 494703 non-null object
qty_sold 494703 non-null int64
date_sold 494703 non-null datetime64[ns]
account_num 494703 non-null object
comic_title 494703 non-null object
dtypes: datetime64[ns](1), int64(1), object(5)
memory usage: 30.2+ MB
###Markdown
OK! I think this is all we can do for now. Let's save this to a DB. Part 2: Save to AWS DB Set up AWS connection to PostgreSQL DB
###Code
# Define path to secret
secret_path_aws = os.path.join(os.environ['HOME'], '.secret',
'aws_ps_flatiron.json')
secret_path_aws
aws_keys = keys.get_keys(secret_path_aws)
user = aws_keys['user']
ps = aws_keys['password']
host = aws_keys['host']
db = aws_keys['db_name']
aws_ps_engine = ('postgresql://' + user + ':' + ps + '@' + host + '/' + db)
# Setup PSQL connection
conn = psql.connect(database=db,
user=user,
password=ps,
host=host,
port='5432')
###Output
_____no_output_____
###Markdown
Write dataframe to DB Use SQLAlchemy to create PSQL engine
###Code
# dialect+driver://username:password@host:port/database
sql_alch_engine = create_engine(aws_ps_engine)
###Output
_____no_output_____
###Markdown
BELOW HAS BEEN SET TO MARKDOWN BECAUSE IT ONLY NEED TO BE RUN ONCE Use built-in pandas functionality to write to AWStrans_tbl_nm = 'comic_trans'trans_df.to_sql(trans_tbl_nm, con=sql_alch_engine, if_exists='append', chunksize=3000) Let's check the records.
###Code
# Setup PSQL connection
conn = psql.connect(database=db,
user=user,
password=ps,
host=host,
port='5432')
# Instantiate cursor
cur = conn.cursor()
# Count records.
query = """
SELECT count(*) from comic_trans;
"""
# Execute the query
cur.execute(query)
# Check results
temp_df = pd.DataFrame(cur.fetchall())
temp_df.columns = [col.name for col in cur.description]
temp_df
###Output
_____no_output_____
###Markdown
And let's remind ourselves how many records we had in our dataframe:
###Code
trans_df.shape
###Output
_____no_output_____
###Markdown
Let's also pull a sample and see if the data returns correctly.
###Code
# Get sample of 10 records
query = """
SELECT * from comic_trans limit 10;
"""
# Execute the query
cur.execute(query)
# Use if execute fails
# conn.rollback()
# Check results
temp_df = pd.DataFrame(cur.fetchall())
temp_df.columns = [col.name for col in cur.description]
temp_df.head()
###Output
_____no_output_____
###Markdown
Great. Now, just because I'm risk-averse, let's back up the table to another copy. BELOW HAS BEEN SET TO MARKDOWN BECAUSE IT ONLY NEED TO BE RUN ONCE create dupe tablequery = """ create table comic_trans_20190624 as select * from comic_trans;"""
###Code
# Execute the query
cur.execute(query)
###Output
_____no_output_____
###Markdown
Now check the dupe table.
###Code
# Check results
temp_df = pd.DataFrame(cur.fetchall())
temp_df.columns = [col.name for col in cur.description]
temp_df.head()
###Output
_____no_output_____
###Markdown
Looks good!Now that we have a decent dataset we can move forward to building our first draft model. Prepping data for PySpark There is a way to use JDBC drivers to import directly from PostgreSQL to Spark, it seems. But the time to get that up and running seems very high. So for now, let's go basic and write it back out to text file, and use that as input to be read into Spark. BELOW HAS BEEN SET TO MARKDOWN BECAUSE IT ONLY NEED TO BE RUN ONCE trans_df.to_json('raw_data/trans.json', orient='records', lines=True)
###Code
!head raw_data/trans.json
###Output
_____no_output_____
###Markdown
--- **Reverse record check from the ALS notebook**
###Code
trans_df.loc[trans_df['item_id'] == 'DCD151935']
###Output
_____no_output_____
###Markdown
Create `comic_id`Each `comic_title` will need an integer `comic_id`, since that is what is supported by the matrix factorization process via ALS.
###Code
# Setup PSQL connection
conn = psql.connect(
database=db,
user=user,
password=ps,
host=host,
port='5432'
)
# Instantiate cursor
cur = conn.cursor()
###Output
_____no_output_____
###Markdown
BELOW HAS BEEN SET TO MARKDOWN BECAUSE IT ONLY NEED TO BE RUN ONCE Create comics tablequery = """ CREATE TABLE comics AS SELECT row_number() over (ORDER BY comic_title) AS comic_id ,comic_title FROM comic_trans GROUP BY comic_title ORDER BY 1 ;"""
###Code
# Execute the query
cur.execute(query)
conn.rollback()
conn.commit()
###Output
_____no_output_____
###Markdown
Let's check that the table is there!
###Code
# Get sample from comics.
query = """
SELECT * from comics;
"""
# Instantiate cursor
cur = conn.cursor()
# Execute the query
cur.execute(query)
# Check results
temp_df = pd.DataFrame(cur.fetchall())
temp_df.columns = [col.name for col in cur.description]
temp_df.head()
temp_df.shape
###Output
_____no_output_____
###Markdown
Now let's output to JSON for use in the ALS workflow.
###Code
!pwd
###Output
_____no_output_____
###Markdown
BELOW HAS BEEN SET TO MARKDOWN BECAUSE IT ONLY NEED TO BE RUN ONCE temp_df.to_json('support_data/comics.json', orient='records', lines=True)
###Code
!head support_data/comics.json
###Output
_____no_output_____ |
notebooks/sentiment-movie-review.ipynb | ###Markdown
Sentiment AnalysisHi 🙂, if you are seeing this notebook, you've succesfully started your first project on FloydHub, hooray! 🚀[Sentiment analysis](https://en.wikipedia.org/wiki/Sentiment_analysis) is one of the most common [NLP](https://en.wikipedia.org/wiki/Natural-language_processing) problems. The goal is to analyze a text and predict whether the underlying sentiment is positive, negative or neutral. *What can you use it for?* Here are a few ideas - measure sentiment of customer support tickets, survey responses, social media, and movie reviews! Predicting sentiment of movie reviewsIn this notebook we will build a [Convolutional Neural Network](http://www.wildml.com/2015/11/understanding-convolutional-neural-networks-for-nlp/) (CNN) classifier to predict the sentiment (positive or negative) of movie reviews. We will use the [Stanford Large Movie Reviews](http://ai.stanford.edu/~amaas/data/sentiment/) dataset for training our model. The dataset is compiled from a collection of 50,000 reviews from IMDB. It contains an equal number of positive and negative reviews. The authors considered only highly polarized reviews. Negative reviews have scores ≤ 4 (out of 10), while positive reviews have score ≥ 7. Neutral reviews are not included. The dataset is divided evenly into training and test sets.We will:- Preprocess text data for NLP- Build and train a 1-D CNN using Keras and Tensorflow- Evaluate our model on the test set- Run the model on your own movie reviews! Instructions- To execute a code cell, click on the cell and press `Shift + Enter` (shortcut for Run).- To learn more about Workspaces, check out the [Getting Started Notebook](get_started_workspace.ipynb).- **Tip**: *Feel free to try this Notebook with your own data and on your own super awesome sentiment classification task.*Now, let's get started! 🚀 Initial SetupLet's start by importing some packages
###Code
from keras.preprocessing import sequence
from keras.models import Sequential
from keras.layers import Dense, Embedding, GlobalMaxPooling1D, Flatten, Conv1D, Dropout, Activation
from keras.preprocessing.text import Tokenizer
import tensorflow as tf
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import os
import re
import string
# For reproducibility
from tensorflow import set_random_seed
from numpy.random import seed
seed(1)
set_random_seed(2)
###Output
Using TensorFlow backend.
###Markdown
Training ParametersWe'll set the hyperparameters for training our model. If you understand what they mean, feel free to play around - otherwise, we recommend keeping the defaults for your first run 🙂
###Code
# Hyperparams if GPU is available
if tf.test.is_gpu_available():
# GPU
BATCH_SIZE = 128 # Number of examples used in each iteration
EPOCHS = 2 # Number of passes through entire dataset
VOCAB_SIZE = 30000 # Size of vocabulary dictionary
MAX_LEN = 500 # Max length of review (in words)
EMBEDDING_DIM = 40 # Dimension of word embedding vector
# Hyperparams for CPU training
else:
# CPU
BATCH_SIZE = 32
EPOCHS = 2
VOCAB_SIZE = 20000
MAX_LEN = 90
EMBEDDING_DIM = 40
###Output
_____no_output_____
###Markdown
DataThe movie reviews dataset is already attached to your workspace (if you want to attach your own data, [check out our docs](https://docs.floydhub.com/guides/workspace/attaching-floydhub-datasets)).Let's take a look at data. The labels are encoded in the dataset: **0** is for *negative* and **1** for a *positive* review.
###Code
DS_PATH = '/floyd/input/imdb/' # ADD path/to/dataset
LABELS = ['negative', 'positive']
# Load data
train = pd.read_csv(os.path.join(DS_PATH, "train.tsv"), sep='\t') # EDIT WITH YOUR TRAIN FILE NAME
val = pd.read_csv(os.path.join(DS_PATH, "val.tsv"), sep='\t') # EDIT WITH YOUR VALIDATION FILE NAME
print("Train shape (rows, columns): ", train.shape, ", Validation shape (rows, columns): ", val.shape)
# How a row/sample looks like
print("\n--- First Sample ---")
print('Label:', train['label'][0])
print('Text:', train['text'][0])
# Custom Tokenizer
re_tok = re.compile(f'([{string.punctuation}“”¨«»®´·º½¾¿¡§£₤‘’])')
def tokenize(s): return re_tok.sub(r' \1 ', s).split()
# Plot sentence by lenght
plt.hist([len(tokenize(s)) for s in train['text'].values], bins=50)
plt.title('Tokens per sentence')
plt.xlabel('Len (number of token)')
plt.ylabel('# samples')
plt.show()
###Output
_____no_output_____
###Markdown
Data PreprocessingBefore feeding the data into the model, we have to preprocess the text. - We will use the Keras `Tokenizer` to convert each word to a corresponding integer ID. Representing words as integers saves a lot of memory!- In order to feed the text into our CNN, all texts should be the same length. We ensure this using the `sequence.pad_sequences()` method and `MAX_LEN` variable. All texts longer than `MAX_LEN` are truncated and shorter texts are padded to get them to the same length.The *Tokens per sentence* plot (see above) is useful for setting the `MAX_LEN` training hyperparameter.
###Code
imdb_tokenizer = Tokenizer(num_words=VOCAB_SIZE)
imdb_tokenizer.fit_on_texts(train['text'].values)
x_train_seq = imdb_tokenizer.texts_to_sequences(train['text'].values)
x_val_seq = imdb_tokenizer.texts_to_sequences(val['text'].values)
x_train = sequence.pad_sequences(x_train_seq, maxlen=MAX_LEN, padding="post", value=0)
x_val = sequence.pad_sequences(x_val_seq, maxlen=MAX_LEN, padding="post", value=0)
y_train, y_val = train['label'].values, val['label'].values
print('First sample before preprocessing: \n', train['text'].values[0], '\n')
print('First sample after preprocessing: \n', x_train[0])
###Output
First sample before preprocessing:
Watch the Original with the same title from 1944! This made for TV movie, is just god-awful! Although it does use (as far as I can tell) almost the same dialog, it just doesn't work! Is it the acting, the poor directing? OK so it's made for TV, but why watch a bad copy, when you can get your hands on the superb original? Especially as you'll be spoiled to the plot and won't enjoy the original as much, as if you've watched it first! <br /><br />There are a few things that are different from the original (it's shorter for once), but all are for the worse! The actors playing the parts here, just don't fit the bill! You just don't believe them and who could top Edward G. Robinsons performance from the original? If you want, only watch it after you've seen the original and even then you'll be very brave, if you watch it through! It's almost sacrilege!
First sample after preprocessing:
[ 5 1 111 2 525 354 1 201 14 73 14 44 871 293
9 83 7 7 47 23 3 168 180 12 23 272 36 1
201 42 5844 15 277 18 29 23 15 1 430 1 153 392
1 528 130 40 89 1180 1 985 22 40 89 261 95 2
34 97 347 2485 1328 236 36 1 201 44 22 178 61 103
9 100 871 107 1 201 2 57 92 487 27 52 2502 44
22 103 9 140 42 217]
###Markdown
ModelWe will implement a model similar to Kim Yoon’s [Convolutional Neural Networks for Sentence Classification](https://arxiv.org/abs/1408.5882).*Image from [the paper](https://arxiv.org/abs/1408.5882)*
###Code
# Model Parameters - You can play with these
NUM_FILTERS = 250
KERNEL_SIZE = 3
HIDDEN_DIMS = 250
# CNN Model
print('Build model...')
model = Sequential()
# we start off with an efficient embedding layer which maps
# our vocab indices into EMBEDDING_DIM dimensions
model.add(Embedding(VOCAB_SIZE, EMBEDDING_DIM, input_length=MAX_LEN))
model.add(Dropout(0.2))
# we add a Convolution1D, which will learn NUM_FILTERS filters
model.add(Conv1D(NUM_FILTERS,
KERNEL_SIZE,
padding='valid',
activation='relu',
strides=1))
# we use max pooling:
model.add(GlobalMaxPooling1D())
# We add a vanilla hidden layer:
model.add(Dense(HIDDEN_DIMS))
model.add(Dropout(0.2))
model.add(Activation('relu'))
# We project onto a single unit output layer, and squash it with a sigmoid:
model.add(Dense(1))
model.add(Activation('sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
model.summary()
###Output
Build model...
WARNING:tensorflow:From /usr/local/lib/python3.6/site-packages/tensorflow/python/util/deprecation.py:497: calling conv1d (from tensorflow.python.ops.nn_ops) with data_format=NHWC is deprecated and will be removed in a future version.
Instructions for updating:
`NHWC` for data_format is deprecated, use `NWC` instead
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
embedding_1 (Embedding) (None, 90, 40) 800000
_________________________________________________________________
dropout_1 (Dropout) (None, 90, 40) 0
_________________________________________________________________
conv1d_1 (Conv1D) (None, 88, 250) 30250
_________________________________________________________________
global_max_pooling1d_1 (Glob (None, 250) 0
_________________________________________________________________
dense_1 (Dense) (None, 250) 62750
_________________________________________________________________
dropout_2 (Dropout) (None, 250) 0
_________________________________________________________________
activation_1 (Activation) (None, 250) 0
_________________________________________________________________
dense_2 (Dense) (None, 1) 251
_________________________________________________________________
activation_2 (Activation) (None, 1) 0
=================================================================
Total params: 893,251
Trainable params: 893,251
Non-trainable params: 0
_________________________________________________________________
###Markdown
Train & EvaluateIf you left the default hyperpameters in the Notebook untouched, your training should take approximately: - On CPU machine: 2 minutes for 2 epochs.- On GPU machine: 1 minute for 2 epochs.You should get an accuracy of > 84%. *Note*: The model will start overfitting after 2 to 3 epochs.
###Code
# fit a model
model.fit(x_train, y_train,
batch_size=BATCH_SIZE,
epochs=EPOCHS,
validation_split=0.1)
# Evaluate the model
score, acc = model.evaluate(x_val, y_val, batch_size=BATCH_SIZE)
print('\nAccuracy: ', acc*100)
pred = model.predict_classes(x_val)
# Plot confusion matrix
from sklearn.metrics import confusion_matrix
from support import print_confusion_matrix
cnf_matrix = confusion_matrix(pred, y_val)
_ = print_confusion_matrix(cnf_matrix, LABELS)
# Print Precision Recall F1-Score Report
from sklearn.metrics import classification_report
report = classification_report(pred, y_val, target_names=LABELS)
print(report)
###Output
precision recall f1-score support
negative 0.80 0.89 0.84 11266
positive 0.90 0.82 0.85 13734
avg / total 0.85 0.85 0.85 25000
###Markdown
It's your turn Test out the model you just trained. Edit the `my_review` variable and Run the Code cell below. Have fun!🎉Here are some inspirations:- Rian Johnson\'s Star Wars: The Last Jedi is a satisfying, at times transporting entertainment with visual wit and a distinctly human touch. - All evidence points to this animated film being contrived as a money-making scheme. The result is worse than crass, it\'s abominably bad.- It was inevitable that there would be the odd turkey in there. What I didn\'t realise however, was that there could be one THIS bad.And some wrong predictions:- Pulp Fiction: Quentin Tarantino proves that he is the master of witty dialogue and a fast plot that doesn\'t allow the viewer a moment of boredom or rest.Can you do better? Play around with the model hyperparameters!
###Code
from ipywidgets import interact_manual
from ipywidgets import widgets
def get_prediction(review):
# Preprocessing
review_np_array = imdb_tokenizer.texts_to_sequences([review])
review_np_array = sequence.pad_sequences(review_np_array, maxlen=MAX_LEN, padding="post", value=0)
# Prediction
score = model.predict(review_np_array)[0][0]
prediction = LABELS[model.predict_classes(review_np_array)[0][0]]
print('REVIEW:', review, '\nPREDICTION:', prediction, '\nSCORE: ', score)
interact_manual(get_prediction, review=widgets.Textarea(placeholder='Type your Review here'));
###Output
_____no_output_____
###Markdown
Save the result
###Code
import pickle
# Saving Tokenizer
with open('models/tokenizer.pickle', 'wb') as handle:
pickle.dump(imdb_tokenizer, handle, protocol=pickle.HIGHEST_PROTOCOL)
# Saving Model Weight
model.save_weights('models/cnn_sentiment_weights.h5')
###Output
_____no_output_____ |
examples/ULMFit.ipynb | ###Markdown
ULMFit Fine-tuning a forward and backward langauge model to get to 95.4% accuracy on the IMDB movie reviews dataset. This tutorial is done with fastai v1.0.53.
###Code
from fastai.text import *
###Output
_____no_output_____
###Markdown
From a language model... Data collection This was run on a Titan RTX (24 GB of RAM) so you will probably need to adjust the batch size accordinly. If you divide it by 2, don't forget to divide the learning rate by 2 as well in the following cells. You can also reduce a little bit the bptt to gain a bit of memory.
###Code
bs,bptt=256,80
###Output
_____no_output_____
###Markdown
This will download and untar the file containing the IMDB dataset, returning a `Pathlib` object pointing to the directory it's in (default is ~/.fastai/data/imdb0). You can specify another folder with the `dest` argument.
###Code
path = untar_data(URLs.IMDB)
###Output
_____no_output_____
###Markdown
We then gather the data we will use to fine-tune the language model using the [data block API](https://docs.fast.ai/data_block.html). For this step, we want all the texts available (even the ones that don't have lables in the unsup folder) and we won't use the IMDB validation set (we will do this for the classification part later only). Instead, we set aside a random 10% of all the texts to build our validation set.The fastai library will automatically launch the tokenization process with the [spacy tokenizer](https://spacy.io/api/tokenizer/) and a few [default rules](https://docs.fast.ai/text.transform.htmlRules) for pre and post-processing before numericalizing the tokens, with a vocab of maximum size 60,000. Tokens are sorted by their frequency and only the 60,000 most commom are kept, the other ones being replace by an unkown token. This cell takes a few minutes to run, so we save the result.
###Code
data_lm = (TextList.from_folder(path)
#Inputs: all the text files in path
.filter_by_folder(include=['train', 'test', 'unsup'])
#We may have other temp folders that contain text files so we only keep what's in train, test and unsup
.split_by_rand_pct(0.1)
#We randomly split and keep 10% (10,000 reviews) for validation
.label_for_lm()
#We want to do a language model so we label accordingly
.databunch(bs=bs, bptt=bptt))
data_lm.save('data_lm.pkl')
###Output
_____no_output_____
###Markdown
When restarting the notebook, as long as the previous cell was executed once, you can skip it and directly load your data again with the following.
###Code
data_lm = load_data(path, 'data_lm.pkl', bs=bs, bptt=bptt)
###Output
_____no_output_____
###Markdown
Since we are training a language model, all the texts are concatenated together (with a random shuffle between them at each new epoch). The model is trained to guess what the next word in the sentence is.
###Code
data_lm.show_batch()
###Output
_____no_output_____
###Markdown
For a backward model, the only difference is we'll have to pqss the flag `backwards=True`.
###Code
data_bwd = load_data(path, 'data_lm.pkl', bs=bs, bptt=bptt, backwards=True)
data_bwd.show_batch()
###Output
_____no_output_____
###Markdown
Fine-tuning the forward language model The idea behind the [ULMFit paper](https://arxiv.org/abs/1801.06146) is to use transfer learning for this classification task. Our language model isn't randomly initialized but with the weights of a model pretrained on a larger corpus, [Wikitext 103](https://blog.einstein.ai/the-wikitext-long-term-dependency-language-modeling-dataset/). The vocabulary of the two datasets are slightly different, so when loading the weights, we take care to put the embedding weights at the right place, and we rando;ly initiliaze the embeddings for words in the IMDB vocabulary that weren't in the wikitext-103 vocabulary of our pretrained model.This is all done by the first line of code that will download the pretrained model for you at the first use. The seocnd line is to use [Mixed Precision Trianing](), which enables us to use a higher batch size by training part of our model in FP16 precision, and also speeds up trqining by a factor 2 to 3 on modern GPUs.
###Code
learn = language_model_learner(data_lm, AWD_LSTM)
learn = learn.to_fp16(clip=0.1)
###Output
_____no_output_____
###Markdown
The `Learner` object we get is frozen by default, which means we only train the embeddings at first (since some of them are random).
###Code
learn.fit_one_cycle(1, 2e-2, moms=(0.8,0.7), wd=0.1)
###Output
_____no_output_____
###Markdown
Then we unfreeze the model and fine-tune the whole thing.
###Code
learn.unfreeze()
learn.fit_one_cycle(10, 2e-3, moms=(0.8,0.7), wd=0.1)
###Output
_____no_output_____
###Markdown
Once done, we jsut save the encoder of the model (everything except the last linear layer that was decoding our final hidden states to words) because this is what we will use for the classifier.
###Code
learn.save_encoder('fwd_enc')
###Output
_____no_output_____
###Markdown
The same but backwards You can't directly train a bidirectional RNN for language modeling, but you can always enseble a forward and backward model. fastai provides a pretrained forward and backawrd model, so we can repeat the previous step to fine-tune the pretrained backward model. The command `language_model_learner` checks the `data` object you pass to automatically decide if it should use the pretrained forward or backward model.
###Code
learn = language_model_learner(data_bwd, AWD_LSTM)
learn = learn.to_fp16(clip=0.1)
###Output
_____no_output_____
###Markdown
Then the training is the same:
###Code
learn.fit_one_cycle(1, 2e-2, moms=(0.8,0.7), wd=0.1)
learn.unfreeze()
learn.fit_one_cycle(10, 2e-3, moms=(0.8,0.7), wd=0.1)
learn.save_encoder('bwd_enc')
###Output
_____no_output_____
###Markdown
... to a classifier Data Collection The classifier is a model that is a bit heavier, so we have lower the batch size.
###Code
path = untar_data(URLs.IMDB)
bs = 128
###Output
_____no_output_____
###Markdown
We use the data block API again to gather all the texts for classification. This time, we only keep the ones in the trainind and validation folderm and label then by the folder they are in. Since this step takes a bit of time, we save the result.
###Code
data_clas = (TextList.from_folder(path, vocab=data_lm.vocab)
#grab all the text files in path
.split_by_folder(valid='test')
#split by train and valid folder (that only keeps 'train' and 'test' so no need to filter)
.label_from_folder(classes=['neg', 'pos'])
#label them all with their folders
.databunch(bs=bs))
data_clas.save('data_clas.pkl')
###Output
_____no_output_____
###Markdown
As long as the previous cell was executed once, you can skip it and directly do this.
###Code
data_clas = load_data(path, 'data_clas.pkl', bs=bs)
data_clas.show_batch()
###Output
_____no_output_____
###Markdown
Like before, you only have to add `backwards=True` to load the data for a backward model.
###Code
data_clas_bwd = load_data(path, 'data_clas.pkl', bs=bs, backwards=True)
data_clas_bwd.show_batch()
###Output
_____no_output_____
###Markdown
Fine-tuning the forward classifier The classifier needs a little less dropout, so we pass `drop_mult=0.5` to multiply all the dropouts by this amount (it's easier than adjusting all the five different values manually). We don't load the pretrained model, but instead our fine-tuned encoder from the previous section.
###Code
learn = text_classifier_learner(data_clas, AWD_LSTM, drop_mult=0.5, pretrained=False)
learn.load_encoder('fwd_enc')
###Output
_____no_output_____
###Markdown
Then we train the model using gradual unfreezing (partially training the model from everything but the classification head frozen to the whole model trianing by unfreezing one layer at a time) and differential learning rate (deeper layer gets a lower learning rate).
###Code
lr = 1e-1
learn.fit_one_cycle(1, lr, moms=(0.8,0.7), wd=0.1)
learn.freeze_to(-2)
lr /= 2
learn.fit_one_cycle(1, slice(lr/(2.6**4),lr), moms=(0.8,0.7), wd=0.1)
learn.freeze_to(-3)
lr /= 2
learn.fit_one_cycle(1, slice(lr/(2.6**4),lr), moms=(0.8,0.7), wd=0.1)
learn.unfreeze()
lr /= 5
learn.fit_one_cycle(2, slice(lr/(2.6**4),lr), moms=(0.8,0.7), wd=0.1)
learn.save('fwd_clas')
###Output
_____no_output_____
###Markdown
The same but backwards Then we do the same thing for the backward model, the only thigns to adjust are the names of the data object and the fine-tuned encoder we load.
###Code
learn_bwd = text_classifier_learner(data_clas_bwd, AWD_LSTM, drop_mult=0.5, pretrained=False)
learn_bwd.load_encoder('bwd_enc')
learn_bwd.fit_one_cycle(1, lr, moms=(0.8,0.7), wd=0.1)
learn_bwd.freeze_to(-2)
lr /= 2
learn_bwd.fit_one_cycle(1, slice(lr/(2.6**4),lr), moms=(0.8,0.7), wd=0.1)
learn_bwd.freeze_to(-3)
lr /= 2
learn_bwd.fit_one_cycle(1, slice(lr/(2.6**4),lr), moms=(0.8,0.7), wd=0.1)
learn_bwd.unfreeze()
lr /= 5
learn_bwd.fit_one_cycle(2, slice(lr/(2.6**4),lr), moms=(0.8,0.7), wd=0.1)
learn_bwd.save('bwd_clas')
###Output
_____no_output_____
###Markdown
Ensembling the two models For our final results, we'll take the average of the predictions of the forward and the backward models. SInce the samples are sorted by text lengths for batching, we pass the argument `ordered=True` to get the predictions in the order of the texts.
###Code
pred_fwd,lbl_fwd = learn.get_preds(ordered=True)
pred_bwd,lbl_bwd = learn_bwd.get_preds(ordered=True)
final_pred = (pred_fwd+pred_bwd)/2
accuracy(pred, lbl_fwd)
###Output
_____no_output_____
###Markdown
ULMFit Fine-tuning a forward and backward langauge model to get to 95.4% accuracy on the IMDB movie reviews dataset. This tutorial is done with fastai v1.0.53.
###Code
from fastai.text import *
###Output
_____no_output_____
###Markdown
From a language model... Data collection This was run on a Titan RTX (24 GB of RAM) so you will probably need to adjust the batch size accordinly. If you divide it by 2, don't forget to divide the learning rate by 2 as well in the following cells. You can also reduce a little bit the bptt to gain a bit of memory.
###Code
bs,bptt=256,80
###Output
_____no_output_____
###Markdown
This will download and untar the file containing the IMDB dataset, returning a `Pathlib` object pointing to the directory it's in (default is ~/.fastai/data/imdb0). You can specify another folder with the `dest` argument.
###Code
path = untar_data(URLs.IMDB)
###Output
_____no_output_____
###Markdown
We then gather the data we will use to fine-tune the language model using the [data block API](https://fastai1.fast.ai/data_block.html). For this step, we want all the texts available (even the ones that don't have lables in the unsup folder) and we won't use the IMDB validation set (we will do this for the classification part later only). Instead, we set aside a random 10% of all the texts to build our validation set.The fastai library will automatically launch the tokenization process with the [spacy tokenizer](https://spacy.io/api/tokenizer/) and a few [default rules](https://fastai1.fast.ai/text.transform.htmlRules) for pre and post-processing before numericalizing the tokens, with a vocab of maximum size 60,000. Tokens are sorted by their frequency and only the 60,000 most commom are kept, the other ones being replace by an unkown token. This cell takes a few minutes to run, so we save the result.
###Code
data_lm = (TextList.from_folder(path)
#Inputs: all the text files in path
.filter_by_folder(include=['train', 'test', 'unsup'])
#We may have other temp folders that contain text files so we only keep what's in train, test and unsup
.split_by_rand_pct(0.1)
#We randomly split and keep 10% (10,000 reviews) for validation
.label_for_lm()
#We want to do a language model so we label accordingly
.databunch(bs=bs, bptt=bptt))
data_lm.save('data_lm.pkl')
###Output
_____no_output_____
###Markdown
When restarting the notebook, as long as the previous cell was executed once, you can skip it and directly load your data again with the following.
###Code
data_lm = load_data(path, 'data_lm.pkl', bs=bs, bptt=bptt)
###Output
_____no_output_____
###Markdown
Since we are training a language model, all the texts are concatenated together (with a random shuffle between them at each new epoch). The model is trained to guess what the next word in the sentence is.
###Code
data_lm.show_batch()
###Output
_____no_output_____
###Markdown
For a backward model, the only difference is we'll have to pqss the flag `backwards=True`.
###Code
data_bwd = load_data(path, 'data_lm.pkl', bs=bs, bptt=bptt, backwards=True)
data_bwd.show_batch()
###Output
_____no_output_____
###Markdown
Fine-tuning the forward language model The idea behind the [ULMFit paper](https://arxiv.org/abs/1801.06146) is to use transfer learning for this classification task. Our language model isn't randomly initialized but with the weights of a model pretrained on a larger corpus, [Wikitext 103](https://blog.einstein.ai/the-wikitext-long-term-dependency-language-modeling-dataset/). The vocabulary of the two datasets are slightly different, so when loading the weights, we take care to put the embedding weights at the right place, and we rando;ly initiliaze the embeddings for words in the IMDB vocabulary that weren't in the wikitext-103 vocabulary of our pretrained model.This is all done by the first line of code that will download the pretrained model for you at the first use. The second line is to use [Mixed Precision Training](), which enables us to use a higher batch size by training part of our model in FP16 precision, and also speeds up training by a factor 2 to 3 on modern GPUs.
###Code
learn = language_model_learner(data_lm, AWD_LSTM)
learn = learn.to_fp16(clip=0.1)
###Output
_____no_output_____
###Markdown
The `Learner` object we get is frozen by default, which means we only train the embeddings at first (since some of them are random).
###Code
learn.fit_one_cycle(1, 2e-2, moms=(0.8,0.7), wd=0.1)
###Output
_____no_output_____
###Markdown
Then we unfreeze the model and fine-tune the whole thing.
###Code
learn.unfreeze()
learn.fit_one_cycle(10, 2e-3, moms=(0.8,0.7), wd=0.1)
###Output
_____no_output_____
###Markdown
Once done, we jsut save the encoder of the model (everything except the last linear layer that was decoding our final hidden states to words) because this is what we will use for the classifier.
###Code
learn.save_encoder('fwd_enc')
###Output
_____no_output_____
###Markdown
The same but backwards You can't directly train a bidirectional RNN for language modeling, but you can always enseble a forward and backward model. fastai provides a pretrained forward and backawrd model, so we can repeat the previous step to fine-tune the pretrained backward model. The command `language_model_learner` checks the `data` object you pass to automatically decide if it should use the pretrained forward or backward model.
###Code
learn = language_model_learner(data_bwd, AWD_LSTM)
learn = learn.to_fp16(clip=0.1)
###Output
_____no_output_____
###Markdown
Then the training is the same:
###Code
learn.fit_one_cycle(1, 2e-2, moms=(0.8,0.7), wd=0.1)
learn.unfreeze()
learn.fit_one_cycle(10, 2e-3, moms=(0.8,0.7), wd=0.1)
learn.save_encoder('bwd_enc')
###Output
_____no_output_____
###Markdown
... to a classifier Data Collection The classifier is a model that is a bit heavier, so we have lower the batch size.
###Code
path = untar_data(URLs.IMDB)
bs = 128
###Output
_____no_output_____
###Markdown
We use the data block API again to gather all the texts for classification. This time, we only keep the ones in the trainind and validation folderm and label then by the folder they are in. Since this step takes a bit of time, we save the result.
###Code
data_clas = (TextList.from_folder(path, vocab=data_lm.vocab)
#grab all the text files in path
.split_by_folder(valid='test')
#split by train and valid folder (that only keeps 'train' and 'test' so no need to filter)
.label_from_folder(classes=['neg', 'pos'])
#label them all with their folders
.databunch(bs=bs))
data_clas.save('data_clas.pkl')
###Output
_____no_output_____
###Markdown
As long as the previous cell was executed once, you can skip it and directly do this.
###Code
data_clas = load_data(path, 'data_clas.pkl', bs=bs)
data_clas.show_batch()
###Output
_____no_output_____
###Markdown
Like before, you only have to add `backwards=True` to load the data for a backward model.
###Code
data_clas_bwd = load_data(path, 'data_clas.pkl', bs=bs, backwards=True)
data_clas_bwd.show_batch()
###Output
_____no_output_____
###Markdown
Fine-tuning the forward classifier The classifier needs a little less dropout, so we pass `drop_mult=0.5` to multiply all the dropouts by this amount (it's easier than adjusting all the five different values manually). We don't load the pretrained model, but instead our fine-tuned encoder from the previous section.
###Code
learn = text_classifier_learner(data_clas, AWD_LSTM, drop_mult=0.5, pretrained=False)
learn.load_encoder('fwd_enc')
###Output
_____no_output_____
###Markdown
Then we train the model using gradual unfreezing (partially training the model from everything but the classification head frozen to the whole model trianing by unfreezing one layer at a time) and differential learning rate (deeper layer gets a lower learning rate).
###Code
lr = 1e-1
learn.fit_one_cycle(1, lr, moms=(0.8,0.7), wd=0.1)
learn.freeze_to(-2)
lr /= 2
learn.fit_one_cycle(1, slice(lr/(2.6**4),lr), moms=(0.8,0.7), wd=0.1)
learn.freeze_to(-3)
lr /= 2
learn.fit_one_cycle(1, slice(lr/(2.6**4),lr), moms=(0.8,0.7), wd=0.1)
learn.unfreeze()
lr /= 5
learn.fit_one_cycle(2, slice(lr/(2.6**4),lr), moms=(0.8,0.7), wd=0.1)
learn.save('fwd_clas')
###Output
_____no_output_____
###Markdown
The same but backwards Then we do the same thing for the backward model, the only thigns to adjust are the names of the data object and the fine-tuned encoder we load.
###Code
learn_bwd = text_classifier_learner(data_clas_bwd, AWD_LSTM, drop_mult=0.5, pretrained=False)
learn_bwd.load_encoder('bwd_enc')
learn_bwd.fit_one_cycle(1, lr, moms=(0.8,0.7), wd=0.1)
learn_bwd.freeze_to(-2)
lr /= 2
learn_bwd.fit_one_cycle(1, slice(lr/(2.6**4),lr), moms=(0.8,0.7), wd=0.1)
learn_bwd.freeze_to(-3)
lr /= 2
learn_bwd.fit_one_cycle(1, slice(lr/(2.6**4),lr), moms=(0.8,0.7), wd=0.1)
learn_bwd.unfreeze()
lr /= 5
learn_bwd.fit_one_cycle(2, slice(lr/(2.6**4),lr), moms=(0.8,0.7), wd=0.1)
learn_bwd.save('bwd_clas')
###Output
_____no_output_____
###Markdown
Ensembling the two models For our final results, we'll take the average of the predictions of the forward and the backward models. SInce the samples are sorted by text lengths for batching, we pass the argument `ordered=True` to get the predictions in the order of the texts.
###Code
pred_fwd,lbl_fwd = learn.get_preds(ordered=True)
pred_bwd,lbl_bwd = learn_bwd.get_preds(ordered=True)
final_pred = (pred_fwd+pred_bwd)/2
accuracy(pred, lbl_fwd)
###Output
_____no_output_____
###Markdown
ULMFit Fine-tuning a forward and backward langauge model to get to 95.4% accuracy on the IMDB movie reviews dataset. This tutorial is done with fastai v1.0.53.
###Code
from fastai.text import *
###Output
_____no_output_____
###Markdown
From a language model... Data collection This was run on a Titan RTX (24 GB of RAM) so you will probably need to adjust the batch size accordinly. If you divide it by 2, don't forget to divide the learning rate by 2 as well in the following cells. You can also reduce a little bit the bptt to gain a bit of memory.
###Code
bs,bptt=256,80
###Output
_____no_output_____
###Markdown
This will download and untar the file containing the IMDB dataset, returning a `Pathlib` object pointing to the directory it's in (default is ~/.fastai/data/imdb0). You can specify another folder with the `dest` argument.
###Code
path = untar_data(URLs.IMDB)
###Output
_____no_output_____
###Markdown
We then gather the data we will use to fine-tune the language model using the [data block API](https://docs.fast.ai/data_block.html). For this step, we want all the texts available (even the ones that don't have lables in the unsup folder) and we won't use the IMDB validation set (we will do this for the classification part later only). Instead, we set aside a random 10% of all the texts to build our validation set.The fastai library will automatically launch the tokenization process with the [spacy tokenizer](https://spacy.io/api/tokenizer/) and a few [default rules](https://docs.fast.ai/text.transform.htmlRules) for pre and post-processing before numericalizing the tokens, with a vocab of maximum size 60,000. Tokens are sorted by their frequency and only the 60,000 most commom are kept, the other ones being replace by an unkown token. This cell takes a few minutes to run, so we save the result.
###Code
data_lm = (TextList.from_folder(path)
#Inputs: all the text files in path
.filter_by_folder(include=['train', 'test', 'unsup'])
#We may have other temp folders that contain text files so we only keep what's in train, test and unsup
.split_by_rand_pct(0.1)
#We randomly split and keep 10% (10,000 reviews) for validation
.label_for_lm()
#We want to do a language model so we label accordingly
.databunch(bs=bs, bptt=bptt))
data_lm.save('data_lm.pkl')
###Output
_____no_output_____
###Markdown
When restarting the notebook, as long as the previous cell was executed once, you can skip it and directly load your data again with the following.
###Code
data_lm = load_data(path, 'data_lm.pkl', bs=bs, bptt=bptt)
###Output
_____no_output_____
###Markdown
Since we are training a language model, all the texts are concatenated together (with a random shuffle between them at each new epoch). The model is trained to guess what the next word in the sentence is.
###Code
data_lm.show_batch()
###Output
_____no_output_____
###Markdown
For a backward model, the only difference is we'll have to pqss the flag `backwards=True`.
###Code
data_bwd = load_data(path, 'data_lm.pkl', bs=bs, bptt=bptt, backwards=True)
data_bwd.show_batch()
###Output
_____no_output_____
###Markdown
Fine-tuning the forward language model The idea behind the [ULMFit paper](https://arxiv.org/abs/1801.06146) is to use transfer learning for this classification task. Our language model isn't randomly initialized but with the weights of a model pretrained on a larger corpus, [Wikitext 103](https://blog.einstein.ai/the-wikitext-long-term-dependency-language-modeling-dataset/). The vocabulary of the two datasets are slightly different, so when loading the weights, we take care to put the embedding weights at the right place, and we rando;ly initiliaze the embeddings for words in the IMDB vocabulary that weren't in the wikitext-103 vocabulary of our pretrained model.This is all done by the first line of code that will download the pretrained model for you at the first use. The second line is to use [Mixed Precision Training](), which enables us to use a higher batch size by training part of our model in FP16 precision, and also speeds up training by a factor 2 to 3 on modern GPUs.
###Code
learn = language_model_learner(data_lm, AWD_LSTM)
learn = learn.to_fp16(clip=0.1)
###Output
_____no_output_____
###Markdown
The `Learner` object we get is frozen by default, which means we only train the embeddings at first (since some of them are random).
###Code
learn.fit_one_cycle(1, 2e-2, moms=(0.8,0.7), wd=0.1)
###Output
_____no_output_____
###Markdown
Then we unfreeze the model and fine-tune the whole thing.
###Code
learn.unfreeze()
learn.fit_one_cycle(10, 2e-3, moms=(0.8,0.7), wd=0.1)
###Output
_____no_output_____
###Markdown
Once done, we jsut save the encoder of the model (everything except the last linear layer that was decoding our final hidden states to words) because this is what we will use for the classifier.
###Code
learn.save_encoder('fwd_enc')
###Output
_____no_output_____
###Markdown
The same but backwards You can't directly train a bidirectional RNN for language modeling, but you can always enseble a forward and backward model. fastai provides a pretrained forward and backawrd model, so we can repeat the previous step to fine-tune the pretrained backward model. The command `language_model_learner` checks the `data` object you pass to automatically decide if it should use the pretrained forward or backward model.
###Code
learn = language_model_learner(data_bwd, AWD_LSTM)
learn = learn.to_fp16(clip=0.1)
###Output
_____no_output_____
###Markdown
Then the training is the same:
###Code
learn.fit_one_cycle(1, 2e-2, moms=(0.8,0.7), wd=0.1)
learn.unfreeze()
learn.fit_one_cycle(10, 2e-3, moms=(0.8,0.7), wd=0.1)
learn.save_encoder('bwd_enc')
###Output
_____no_output_____
###Markdown
... to a classifier Data Collection The classifier is a model that is a bit heavier, so we have lower the batch size.
###Code
path = untar_data(URLs.IMDB)
bs = 128
###Output
_____no_output_____
###Markdown
We use the data block API again to gather all the texts for classification. This time, we only keep the ones in the trainind and validation folderm and label then by the folder they are in. Since this step takes a bit of time, we save the result.
###Code
data_clas = (TextList.from_folder(path, vocab=data_lm.vocab)
#grab all the text files in path
.split_by_folder(valid='test')
#split by train and valid folder (that only keeps 'train' and 'test' so no need to filter)
.label_from_folder(classes=['neg', 'pos'])
#label them all with their folders
.databunch(bs=bs))
data_clas.save('data_clas.pkl')
###Output
_____no_output_____
###Markdown
As long as the previous cell was executed once, you can skip it and directly do this.
###Code
data_clas = load_data(path, 'data_clas.pkl', bs=bs)
data_clas.show_batch()
###Output
_____no_output_____
###Markdown
Like before, you only have to add `backwards=True` to load the data for a backward model.
###Code
data_clas_bwd = load_data(path, 'data_clas.pkl', bs=bs, backwards=True)
data_clas_bwd.show_batch()
###Output
_____no_output_____
###Markdown
Fine-tuning the forward classifier The classifier needs a little less dropout, so we pass `drop_mult=0.5` to multiply all the dropouts by this amount (it's easier than adjusting all the five different values manually). We don't load the pretrained model, but instead our fine-tuned encoder from the previous section.
###Code
learn = text_classifier_learner(data_clas, AWD_LSTM, drop_mult=0.5, pretrained=False)
learn.load_encoder('fwd_enc')
###Output
_____no_output_____
###Markdown
Then we train the model using gradual unfreezing (partially training the model from everything but the classification head frozen to the whole model trianing by unfreezing one layer at a time) and differential learning rate (deeper layer gets a lower learning rate).
###Code
lr = 1e-1
learn.fit_one_cycle(1, lr, moms=(0.8,0.7), wd=0.1)
learn.freeze_to(-2)
lr /= 2
learn.fit_one_cycle(1, slice(lr/(2.6**4),lr), moms=(0.8,0.7), wd=0.1)
learn.freeze_to(-3)
lr /= 2
learn.fit_one_cycle(1, slice(lr/(2.6**4),lr), moms=(0.8,0.7), wd=0.1)
learn.unfreeze()
lr /= 5
learn.fit_one_cycle(2, slice(lr/(2.6**4),lr), moms=(0.8,0.7), wd=0.1)
learn.save('fwd_clas')
###Output
_____no_output_____
###Markdown
The same but backwards Then we do the same thing for the backward model, the only thigns to adjust are the names of the data object and the fine-tuned encoder we load.
###Code
learn_bwd = text_classifier_learner(data_clas_bwd, AWD_LSTM, drop_mult=0.5, pretrained=False)
learn_bwd.load_encoder('bwd_enc')
learn_bwd.fit_one_cycle(1, lr, moms=(0.8,0.7), wd=0.1)
learn_bwd.freeze_to(-2)
lr /= 2
learn_bwd.fit_one_cycle(1, slice(lr/(2.6**4),lr), moms=(0.8,0.7), wd=0.1)
learn_bwd.freeze_to(-3)
lr /= 2
learn_bwd.fit_one_cycle(1, slice(lr/(2.6**4),lr), moms=(0.8,0.7), wd=0.1)
learn_bwd.unfreeze()
lr /= 5
learn_bwd.fit_one_cycle(2, slice(lr/(2.6**4),lr), moms=(0.8,0.7), wd=0.1)
learn_bwd.save('bwd_clas')
###Output
_____no_output_____
###Markdown
Ensembling the two models For our final results, we'll take the average of the predictions of the forward and the backward models. SInce the samples are sorted by text lengths for batching, we pass the argument `ordered=True` to get the predictions in the order of the texts.
###Code
pred_fwd,lbl_fwd = learn.get_preds(ordered=True)
pred_bwd,lbl_bwd = learn_bwd.get_preds(ordered=True)
final_pred = (pred_fwd+pred_bwd)/2
accuracy(pred, lbl_fwd)
###Output
_____no_output_____
###Markdown
ULMFit Fine-tuning a forward and backward langauge model to get to 95.4% accuracy on the IMDB movie reviews dataset. This tutorial is done with fastai v1.0.53.
###Code
from fastai.text import *
###Output
_____no_output_____
###Markdown
From a language model... Data collection This was run on a Titan RTX (24 GB of RAM) so you will probably need to adjust the batch size accordinly. If you divide it by 2, don't forget to divide the learning rate by 2 as well in the following cells. You can also reduce a little bit the bptt to gain a bit of memory.
###Code
bs,bptt=256,80
###Output
_____no_output_____
###Markdown
This will download and untar the file containing the IMDB dataset, returning a `Pathlib` object pointing to the directory it's in (default is ~/.fastai/data/imdb0). You can specify another folder with the `dest` argument.
###Code
path = untar_data(URLs.IMDB)
###Output
_____no_output_____
###Markdown
We then gather the data we will use to fine-tune the language model using the [data block API](https://docs.fast.ai/data_block.html). For this step, we want all the texts available (even the ones that don't have lables in the unsup folder) and we won't use the IMDB validation set (we will do this for the classification part later only). Instead, we set aside a random 10% of all the texts to build our validation set.The fastai library will automatically launch the tokenization process with the [spacy tokenizer](https://spacy.io/api/tokenizer/) and a few [default rules](https://docs.fast.ai/text.transform.htmlRules) for pre and post-processing before numericalizing the tokens, with a vocab of maximum size 60,000. Tokens are sorted by their frequency and only the 60,000 most commom are kept, the other ones being replace by an unkown token. This cell takes a few minutes to run, so we save the result.
###Code
data_lm = (TextList.from_folder(path)
#Inputs: all the text files in path
.filter_by_folder(include=['train', 'test', 'unsup'])
#We may have other temp folders that contain text files so we only keep what's in train, test and unsup
.split_by_rand_pct(0.1)
#We randomly split and keep 10% (10,000 reviews) for validation
.label_for_lm()
#We want to do a language model so we label accordingly
.databunch(bs=bs, bptt=bptt))
data_lm.save('data_lm.pkl')
###Output
_____no_output_____
###Markdown
When restarting the notebook, as long as the previous cell was executed once, you can skip it and directly load your data again with the following.
###Code
data_lm = load_data(path, 'data_lm.pkl', bs=bs, bptt=bptt)
###Output
_____no_output_____
###Markdown
Since we are training a language model, all the texts are concatenated together (with a random shuffle between them at each new epoch). The model is trained to guess what the next word in the sentence is.
###Code
data_lm.show_batch()
###Output
_____no_output_____
###Markdown
For a backward model, the only difference is we'll have to pqss the flag `backwards=True`.
###Code
data_bwd = load_data(path, 'data_lm.pkl', bs=bs, bptt=bptt, backwards=True)
data_bwd.show_batch()
###Output
_____no_output_____
###Markdown
Fine-tuning the forward language model The idea behind the [ULMFit paper](https://arxiv.org/abs/1801.06146) is to use transfer learning for this classification task. Our language model isn't randomly initialized but with the weights of a model pretrained on a larger corpus, [Wikitext 103](https://blog.einstein.ai/the-wikitext-long-term-dependency-language-modeling-dataset/). The vocabulary of the two datasets are slightly different, so when loading the weights, we take care to put the embedding weights at the right place, and we rando;ly initiliaze the embeddings for words in the IMDB vocabulary that weren't in the wikitext-103 vocabulary of our pretrained model.This is all done by the first line of code that will download the pretrained model for you at the first use. The seocnd line is to use [Mixed Precision Trianing](), which enables us to use a higher batch size by training part of our model in FP16 precision, and also speeds up trqining by a factor 2 to 3 on modern GPUs.
###Code
learn = language_model_learner(data_lm, AWD_LSTM)
learn = learn.to_fp16(clip=0.1)
###Output
_____no_output_____
###Markdown
The `Learner` object we get is frozen by default, which means we only train the embeddings at first (since some of them are random).
###Code
learn.fit_one_cycle(1, 2e-2, moms=(0.8,0.7), wd=0.1)
###Output
_____no_output_____
###Markdown
Then we unfreeze the model and fine-tune the whole thing.
###Code
learn.unfreeze()
learn.fit_one_cycle(10, 2e-3, moms=(0.8,0.7), wd=0.1)
###Output
_____no_output_____
###Markdown
Once done, we jsut save the encoder of the model (everything except the last linear layer that was decoding our final hidden states to words) because this is what we will use for the classifier.
###Code
learn.save_encoder('fwd_enc')
###Output
_____no_output_____
###Markdown
The same but backwards You can't directly train a bidirectional RNN for language modeling, but you can always enseble a forward and backward model. fastai provides a pretrained forward and backawrd model, so we can repeat the previous step to fine-tune the pretrained backward model. The command `language_model_learner` checks the `data` object you pass to automatically decide if it should use the pretrained forward or backward model.
###Code
learn = language_model_learner(data_bwd, AWD_LSTM)
learn = learn.to_fp16(clip=0.1)
###Output
_____no_output_____
###Markdown
Then the training is the same:
###Code
learn.fit_one_cycle(1, 2e-2, moms=(0.8,0.7), wd=0.1)
learn.unfreeze()
learn.fit_one_cycle(10, 2e-3, moms=(0.8,0.7), wd=0.1)
learn.save_encoder('bwd_enc')
###Output
_____no_output_____
###Markdown
... to a classifier Data Collection The classifier is a model that is a bit heavier, so we have lower the batch size.
###Code
path = untar_data(URLs.IMDB)
bs = 128
###Output
_____no_output_____
###Markdown
We use the data block API again to gather all the texts for classification. This time, we only keep the ones in the trainind and validation folderm and label then by the folder they are in. Since this step takes a bit of time, we save the result.
###Code
data_clas = (TextList.from_folder(path, vocab=data_lm.vocab)
#grab all the text files in path
.split_by_folder(valid='test')
#split by train and valid folder (that only keeps 'train' and 'test' so no need to filter)
.label_from_folder(classes=['neg', 'pos'])
#label them all with their folders
.databunch(bs=bs))
data_clas.save('data_clas.pkl')
###Output
_____no_output_____
###Markdown
As long as the previous cell was executed once, you can skip it and directly do this.
###Code
data_clas = load_data(path, 'data_clas.pkl', bs=bs)
data_clas.show_batch()
###Output
_____no_output_____
###Markdown
Like before, you only have to add `backwards=True` to load the data for a backward model.
###Code
data_clas_bwd = load_data(path, 'data_clas.pkl', bs=bs, backwards=True)
data_clas_bwd.show_batch()
###Output
_____no_output_____
###Markdown
Fine-tuning the forward classifier The classifier needs a little less dropout, so we pass `drop_mult=0.5` to multiply all the dropouts by this amount (it's easier than adjusting all the five different values manually). We don't load the pretrained model, but instead our fine-tuned encoder from the previous section.
###Code
learn = text_classifier_learner(data_clas, AWD_LSTM, drop_mult=0.5, pretrained=False)
learn.load_encoder('fwd_enc')
###Output
_____no_output_____
###Markdown
Then we train the model using gradual unfreezing (partially training the model from everything but the classification head frozen to the whole model trianing by unfreezing one layer at a time) and differential learning rate (deeper layer gets a lower learning rate).
###Code
lr = 1e-1
learn.fit_one_cycle(1, lr, moms=(0.8,0.7))
learn.freeze_to(-2)
lr /= 2
learn.fit_one_cycle(1, slice(lr/(2.6**4),lr), moms=(0.8,0.7))
learn.freeze_to(-3)
lr /= 2
learn.fit_one_cycle(1, slice(lr/(2.6**4),lr), moms=(0.8,0.7))
learn.unfreeze()
lr /= 5
learn.fit_one_cycle(2, slice(lr/(2.6**4),lr), moms=(0.8,0.7))
learn.save('fwd_clas')
###Output
_____no_output_____
###Markdown
The same but backwards Then we do the same thing for the backward model, the only thigns to adjust are the names of the data object and the fine-tuned encoder we load.
###Code
learn_bwd = text_classifier_learner(data_clas_bwd, AWD_LSTM, drop_mult=0.5, pretrained=False)
learn_bwd.load_encoder('bwd_enc')
learn_bwd.fit_one_cycle(1, lr, moms=(0.8,0.7), wd=0.1)
learn_bwd.freeze_to(-2)
lr /= 2
learn_bwd.fit_one_cycle(1, slice(lr/(2.6**4),lr), moms=(0.8,0.7), wd=0.1)
learn_bwd.freeze_to(-3)
lr /= 2
learn_bwd.fit_one_cycle(1, slice(lr/(2.6**4),lr), moms=(0.8,0.7), wd=0.1)
learn_bwd.unfreeze()
lr /= 5
learn_bwd.fit_one_cycle(2, slice(lr/(2.6**4),lr), moms=(0.8,0.7), wd=0.1)
learn_bwd.save('bwd_clas')
###Output
_____no_output_____
###Markdown
Ensembling the two models For our final results, we'll take the average of the predictions of the forward and the backward models. SInce the samples are sorted by text lengths for batching, we pass the argument `ordered=True` to get the predictions in the order of the texts.
###Code
pred_fwd,lbl_fwd = learn.get_preds(ordered=True)
pred_bwd,lbl_bwd = learn_bwd.get_preds(ordered=True)
final_pred = (pred_fwd+pred_bwd)/2
accuracy(pred, lbl_fwd)
###Output
_____no_output_____ |
content/04/.ipynb_checkpoints/sectionalmap-checkpoint.ipynb | ###Markdown
Reformat NetCDF4 File for Function Call
###Code
import sys
!{sys.executable} -m pip install netCDF4
!{sys.executable} -m pip install xarray
import opedia
import netCDF4
import os
import numpy as np
import pandas as pd
import xarray as xr
import datetime as dt
from scipy.interpolate import griddata
import db
import subset
import common as com
import climatology as clim
from bokeh.io import output_notebook
from datetime import datetime, timedelta
import time
from bokeh.plotting import figure, show, output_file
from bokeh.layouts import column
from bokeh.palettes import all_palettes
from bokeh.models import HoverTool, LinearColorMapper, BasicTicker, ColorBar
from bokeh.embed import components
import jupyterInline as jup
if jup.jupytered():
from tqdm import tqdm_notebook as tqdm
else:
from tqdm import tqdm
###Output
_____no_output_____
###Markdown
NetCDF Compatible Function
###Code
def xarraySectionMap(tables, variabels, dt1, dt2, lat1, lat2, lon1, lon2, depth1, depth2, fname, exportDataFlag):
data, lats, lons, subs, frameVars, units = [], [], [], [], [], []
xs, ys, zs = [], [], []
for i in tqdm(range(len(tables)), desc='overall'):
toDateTime = tables[i].indexes['TIME'].to_datetimeindex()
tables[i]['TIME'] = toDateTime
table = tables[i].sel(TIME = slice(dt1, dt2), LAT_C = slice(lat1, lat2), LON_C = slice(lon1, lon2), DEP_C = slice(depth1, depth2))
############### export retrieved data ###############
if exportDataFlag: # export data
dirPath = 'data/'
if not os.path.exists(dirPath):
os.makedirs(dirPath)
exportData(df, path=dirPath + fname + '_' + tables[i] + '_' + variabels[i] + '.csv')
#####################################################
times = np.unique(table.variables['TIME'].values)
lats = np.unique(table.variables['LAT_C'].values)
lons = np.unique(table.variables['LON_C'].values)
depths = np.flip(np.unique(table.variables['DEP_C'].values))
shape = (len(lats), len(lons), len(depths))
hours = [None]
unit = '[PLACEHOLDER]'
for t in times:
for h in hours:
frame = table.sel(TIME = t, method = 'nearest')
sub = variabels[i] + unit + ', TIME: ' + str(t)
if h != None:
frame = frame[frame['hour'] == h]
sub = sub + ', hour: ' + str(h) + 'hr'
try:
shot = frame[variabels[i]].values.reshape(shape)
shot[shot < 0] = float('NaN')
except Exception as e:
continue
data.append(shot)
xs.append(lons)
ys.append(lats)
zs.append(depths)
frameVars.append(variabels[i])
units.append(unit)
subs.append(sub)
bokehSec(data=data, subject=subs, fname=fname, ys=ys, xs=xs, zs=zs, units=units, variabels=frameVars)
return
###Output
_____no_output_____
###Markdown
Helper Functions
###Code
def bokehSec(data, subject, fname, ys, xs, zs, units, variabels):
TOOLS="crosshair,pan,wheel_zoom,zoom_in,zoom_out,box_zoom,undo,redo,reset,tap,save,box_select,poly_select,lasso_select,"
w = 1000
h = 500
p = []
data_org = list(data)
for ind in range(len(data_org)):
data = data_org[ind]
lon = xs[ind]
lat = ys[ind]
depth = zs[ind]
bounds = (None, None)
paletteName = com.getPalette(variabels[ind], 10)
low, high = bounds[0], bounds[1]
if low == None:
low, high = np.nanmin(data[ind].flatten()), np.nanmax(data[ind].flatten())
color_mapper = LinearColorMapper(palette=paletteName, low=low, high=high)
output_notebook()
if len(lon) > len(lat):
p1 = figure(tools=TOOLS, toolbar_location="above", title=subject[ind], plot_width=w, plot_height=h, x_range=(np.min(lon), np.max(lon)), y_range=(-np.max(depth), -np.min(depth)))
data = np.nanmean(data, axis=0)
data = np.transpose(data)
data = np.squeeze(data)
xLabel = 'Longitude'
data = regulate(lat, lon, depth, data)
p1.image(image=[data], color_mapper=color_mapper, x=np.min(lon), y=-np.max(depth), dw=np.max(lon)-np.min(lon), dh=np.max(depth)-np.min(depth))
else:
p1 = figure(tools=TOOLS, toolbar_location="above", title=subject[ind], plot_width=w, plot_height=h, x_range=(np.min(lat), np.max(lat)), y_range=(-np.max(depth), -np.min(depth)))
data = np.nanmean(data, axis=1)
data = np.transpose(data)
data = np.squeeze(data)
xLabel = 'Latitude'
data = regulate(lat, lon, depth, data)
p1.image(image=[data], color_mapper=color_mapper, x=np.min(lat), y=-np.max(depth), dw=np.max(lat)-np.min(lat), dh=np.max(depth)-np.min(depth))
p1.xaxis.axis_label = xLabel
p1.add_tools(HoverTool(
tooltips=[
(xLabel.lower(), '$x'),
('depth', '$y'),
(variabels[ind]+units[ind], '@image'),
],
mode='mouse'
))
p1.yaxis.axis_label = 'depth [m]'
color_bar = ColorBar(color_mapper=color_mapper, ticker=BasicTicker(),
label_standoff=12, border_line_color=None, location=(0,0))
p1.add_layout(color_bar, 'right')
p.append(p1)
dirPath = 'embed/'
# if not os.path.exists(dirPath):
# os.makedirs(dirPath)
# if not inline: ## if jupyter is not the caller
# output_file(dirPath + fname + ".html", title="Section Map")
show(column(p))
return
def regulate(lat, lon, depth, data):
depth = -1* depth
deltaZ = np.min( np.abs( depth - np.roll(depth, -1) ) )
newDepth = np.arange(np.min(depth), np.max(depth), deltaZ)
if len(lon) > len(lat):
lon1, depth1 = np.meshgrid(lon, depth)
lon2, depth2 = np.meshgrid(lon, newDepth)
lon1 = lon1.ravel()
lon1 = list(lon1[lon1 != np.isnan])
depth1 = depth1.ravel()
depth1 = list(depth1[depth1 != np.isnan])
data = data.ravel()
data = list(data[data != np.isnan])
data = griddata((lon1, depth1), data, (lon2, depth2), method='linear')
else:
lat1, depth1 = np.meshgrid(lat, depth)
lat2, depth2 = np.meshgrid(lat, newDepth)
lat1 = lat1.ravel()
lat1 = list(lat1[lat1 != np.isnan])
depth1 = depth1.ravel()
depth1 = list(depth1[depth1 != np.isnan])
data = data.ravel()
data = list(data[data != np.isnan])
data = griddata((lat1, depth1), data, (lat2, depth2), method='linear')
depth = -1* depth
return data
###Output
_____no_output_____
###Markdown
Testing Space
###Code
#TESTS NETCDF-COMPATIBLE FUNCTION
xFile = xr.open_dataset('http://3.88.71.225:80/thredds/dodsC/las/id-a1d60eba44/data_usr_local_tomcat_content_cbiomes_20190510_20_darwin_v0.2_cs510_darwin_v0.2_cs510_nutrients.nc.jnl')
tables = [xFile] # see catalog.csv for the complete list of tables and variable names
variabels = ['O2'] # see catalog.csv for the complete list of tables and variable name
dt1 = '2016-04-22' # PISCES is a weekly model, and here we are using monthly climatology of Darwin model
dt2 = '2016-04-22'
lat1, lat2 = 23, 55
lon1, lon2 = -159, -157
depth1, depth2 = 0, 3597
fname = 'sectional'
exportDataFlag = False # True if you you want to download data
xarraySectionMap(tables, variabels, dt1, dt2, lat1, lat2, lon1, lon2, depth1, depth2, fname, exportDataFlag)
###Output
_____no_output_____ |
3-3.Classification_MNIST.ipynb | ###Markdown
torchvision.datasetstorchvision.datasets에는 다양한 dataset들이 존재한다. 그중 대표적인 예시는 다음과 같다.- MNIST- CIFAR- COCO- ImageNet- STL10
###Code
train_data=torchvision.datasets.MNIST(root="./MNIST_data", train=True,
download=True, transform=transform)
train_loader = torch.utils.data.DataLoader(train_data, batch_size=batch_size, shuffle=True, num_workers=4, drop_last=True)
class Model(torch.nn.Module):
def __init__(self):
super(Model, self).__init__()
self.layer_1 = nn.Conv2d(1,64,10,1)
self.act_1 = nn.ReLU()
self.layer_2 = nn.Conv2d(64,64,5,1)
self.act_2 = nn.ReLU()
self.layer_3 = nn.Conv2d(64,128,5,1)
self.act_3 = nn.ReLU()
self.layer_4 = nn.Conv2d(128,128,2,1)
self.act_4 = nn.ReLU()
self.layer_5 = nn.Conv2d(128,256,2,1)
self.act_5 = nn.ReLU()
self.max_1=nn.MaxPool2d(2,2)
self.layer_6 = nn.Conv2d(256,256,2,1)
self.act_6 = nn.ReLU()
self.fc_layer_1 = nn.Linear(9*256,1000)
self.act_7 = nn.ReLU()
self.bnm1=nn.BatchNorm1d(1000)
self.fc_layer_2 = nn.Linear(1000,10)
self.act_8 = nn.ReLU()
def forward(self, x):
x = x.view(batch_size,1,28,28)
out = self.layer_1(x)
out = self.act_1(out)
for module in list(self.modules())[2:-5]:
out = module(out)
out = out.view(batch_size,-1)
for module in list(self.modules())[-5:]:
out = module(out)
return out
model=Model()
if torch.cuda.is_available():
model=model.cuda()
criterion=nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters())
total_epoch=10
for epoch in range(total_epoch):
trn_loss=0
trn_correct=0
for i, data in enumerate(train_loader, 0):
inputs, labels = data
if torch.cuda.is_available():
inputs=inputs.cuda()
labels=labels.cuda()
# grad init
optimizer.zero_grad()
# forward propagation
output= model(inputs)
# calculate loss
loss=criterion(output, labels)
# back propagation
loss.backward()
# weight update
optimizer.step()
# trn_loss summary
trn_loss += loss.item()
_, predicted=torch.max(output,1)
trn_correct+=np.count_nonzero(predicted.cpu().detach()==labels.cpu().detach())
# del (memory issue)
del loss
del output
print("epoch: {}/{} | trn loss: {:.4f} | trn accuracy: {:.2f}% ".format(
epoch+1, total_epoch, trn_loss / len(train_loader),
trn_correct/(len(train_loader)*batch_size)*100
))
###Output
epoch: 1/10 | trn loss: 0.1511 | trn accuracy: 95.27%
epoch: 2/10 | trn loss: 0.0655 | trn accuracy: 98.02%
epoch: 3/10 | trn loss: 0.0473 | trn accuracy: 98.58%
epoch: 4/10 | trn loss: 0.0377 | trn accuracy: 98.81%
epoch: 5/10 | trn loss: 0.0346 | trn accuracy: 98.97%
epoch: 6/10 | trn loss: 0.0307 | trn accuracy: 99.05%
epoch: 7/10 | trn loss: 0.0272 | trn accuracy: 99.14%
epoch: 8/10 | trn loss: 0.0259 | trn accuracy: 99.21%
epoch: 9/10 | trn loss: 0.0221 | trn accuracy: 99.33%
epoch: 10/10 | trn loss: 0.0201 | trn accuracy: 99.38%
|
paper/export_models.ipynb | ###Markdown
Create some maps
###Code
import click
import os
import joblib
import numpy as np
import pandas as pd
from collections import defaultdict
from copy import deepcopy
from darts import TimeSeries
from pyprocessta.model.tcn import (
TCNModelDropout,
parallelized_inference,
summarize_results,
)
THIS_DIR = os.path.abspath('/home/kjablonk/documents/timeseries_analysis/pyprocessta/examples')
def load_pickle(filename):
with open(filename, "rb") as handle:
res = pickle.load(handle)
return res
def dump_pickle(object, filename):
with open(filename, "wb") as handle:
pickle.dump(object, handle)
MEAS_COLUMNS = [
"TI-19",
# "FI-16",
# "TI-33",
# "FI-2",
# "FI-151",
# "TI-8",
# "FI-241",
# "valve-position-12", # dry-bed
# "FI-38", # strippera
# "PI-28", # stripper
# "TI-28", # stripper
# "FI-20",
# "FI-30",
"TI-3",
"FI-19",
# "FI-211",
"FI-11",
# "TI-30",
# "PI-30",
"TI-1213",
# "TI-4",
"FI-23",
"FI-20",
#"FI-20/FI-23",
# "TI-22",
# "delta_t",
"TI-35",
#"delta_t_2",
]
# First, we train a model on *all* data
# Then, we do a partial-denpendency plot approach and change one variable and see how the model predictions change
# load the trained model
model_cov1 = TCNModelDropout(
input_chunk_length=8,
output_chunk_length=1,
num_layers=5,
num_filters=16,
kernel_size=6,
dropout=0.3,
weight_norm=True,
batch_size=32,
n_epochs=100,
log_tensorboard=True,
optimizer_kwargs={"lr": 2e-4},
)
model_cov2 = TCNModelDropout(
input_chunk_length=8,
output_chunk_length=1,
num_layers=5,
num_filters=16,
kernel_size=6,
dropout=0.3,
weight_norm=True,
batch_size=32,
n_epochs=100,
log_tensorboard=True,
optimizer_kwargs={"lr": 2e-4},
)
FEAT_NUM_MAPPING = dict(zip(MEAS_COLUMNS, [str(i) for i in range(len(MEAS_COLUMNS))]))
UPDATE_MAPPING = {
"amine": {
"scaler": joblib.load("20210814_y_transformer__reduced_feature_set"),
"model": model_cov1.load_from_checkpoint(
os.path.join(THIS_DIR, "20210814_2amp_pip_model_reduced_feature_set_darts")
),
"name": ["2-Amino-2-methylpropanol C4H11NO", "Piperazine C4H10N2"],
},
"co2": {
"scaler": joblib.load("20210814_y_transformer_co2_ammonia_reduced_feature_set"),
"model": model_cov2.load_from_checkpoint(
os.path.join(
THIS_DIR, "20210814_co2_ammonia_model_reduced_feature_set_darts"
)
),
"name": ["Carbon dioxide CO2", "Ammonia NH3"],
},
}
SCALER = joblib.load("20210814_x_scaler_reduced_feature_set")
# making the input one item longer as "safety margin"
def calculate_initialization_percentage(
timeseries_length: int, input_sequence_length: int = 61
):
fraction_of_input = input_sequence_length / timeseries_length
res = max([fraction_of_input, 0.1])
return res
def run_update(df, x, target="amine"):
model_dict = UPDATE_MAPPING[target]
y = model_dict["scaler"].transform(
TimeSeries.from_dataframe(df, value_cols=model_dict["name"])
)
df = parallelized_inference(
model_dict["model"],
x,
y,
repeats=1,
start=calculate_initialization_percentage(len(y)),
horizon=2,
)
means, stds = summarize_results(df)
return {"means": means, "stds": stds}
def run_targets(df, feature_levels, target: str = "amine"):
df = deepcopy(df)
for k, v in feature_levels.items():
if k == "valve-position-12":
df[k] = v
else:
df[k] = df[k] + v / 100 * np.abs(df[k])
X_ = TimeSeries.from_dataframe(df, value_cols=MEAS_COLUMNS)
X_ = SCALER.transform(X_)
res = run_update(df, X_, target)
return res
def run_grid(
df,
feature_a: str = "TI-19",
feature_b: str = "TI-1213",
lower: float = -20,
upper: float = 20,
num_points: int = 5,
objectives: str = "amine",
):
grid = np.linspace(lower, upper, num_points)
results_double_new = defaultdict(dict)
if feature_a == "valve-position-12":
grid_a = [0, 1]
else:
grid_a = grid
if feature_b == "valve-position-12":
grid_b = [0, 1]
else:
grid_b = grid
for point_a in grid_a:
for point_b in grid_b:
print(f"Running point {feature_a}: {point_a} {feature_b}: {point_b}")
results_double_new[point_a][point_b] = run_targets(
df, {feature_a: point_a, feature_b: point_b}, objectives
)
return results_double_new
import pickle
mymap = run_grid(df)
def get_grids(d):
outer_keys = sorted(d.keys())
inner_keys = sorted(d[outer_keys[0]].keys())
return outer_keys, inner_keys
def make_image(res, objective="1"):
outer, inner = get_grids(res)
image_m = np.zeros((len(outer), len(inner)))
image_l = np.zeros((len(outer), len(inner)))
image_t = np.zeros((len(outer), len(inner)))
for i, point_x in enumerate(outer):
for j, point_y in enumerate(inner):
image_m[i][j] = np.sum(res[point_x][point_y]['means'][objective].values-res[0][0]['means'][objective].values)
return image_m, outer, inner
im, _, _ = make_image(mymap)
im2, _, _ = make_image(mymap, objective='0')
import matplotlib.pyplot as plt
plt.imshow(im,cmap='coolwarm')
plt.imshow(im,cmap='coolwarm')
plt.imshow(im,cmap='coolwarm')
plt.imshow(im2, cmap='coolwarm')
plt.imshow(im2, cmap='coolwarm')
plt.imshow(im2, cmap='coolwarm')
with open('20210811_ti3_ti1212_amine.pkl', 'wb') as handle:
pickle.dump(im, handle)
###Output
_____no_output_____ |
1. Beginner/Pytorch6_NLP_BoW_Classifier.ipynb | ###Markdown
Master Pytorch 6 : NLP - BoW Classifier- 논리 회귀 Bag-of-Words 분류기 만들기- BoW 표현을 레이블에 대한 로그 확률로 매핑
###Code
import pandas as pd
data = {'단어' : ['hello', 'world']}
df = pd.DataFrame(data)
df
###Output
_____no_output_____
###Markdown
- 각각 0과 1의 색인을 가진 두 단어(hello, world)가 있다.- 위 사전을 이용하면 다음과 같이 매핑된다.[count(hello), count(world)]>"hello hello hello hello" = [4,0]"helloworldworldhello" = [2,2] data 준비
###Code
data = [("me gusta comer en la cafeteria".split(), 'SPANISH'),
("Give it to me".split(), 'ENGLISH'),
("No creo que sea una buena idea".split(), 'SPANISH'),
('No it is not a good idea to get lost at sea'.split(), 'ENGLISH')]
test_data = [('Yo creo que si'.split(), 'SPANISH'),
('it is lost on me'.split(), 'ENGLISH')]
###Output
_____no_output_____
###Markdown
Word to ix- 각 단어를 고유한 숫자로 매핑
###Code
word_to_ix = {}
for sent, lan in data + test_data:
for word in sent:
if word not in word_to_ix:
word_to_ix[word] = len(word_to_ix)
print(word_to_ix)
vocab_size = len(word_to_ix)
labels_n = 2
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
class BoWClassifier(nn.Module):
def __init__(self, input_size, output_size):
super(BoWClassifier, self).__init__()
self.linear = nn.Linear(input_size, output_size) # input : vocab_size, output : num_labels
def forward(self, bow_vec):
y = self.linear(bow_vec)
y = F.log_softmax(y, dim = 1)
return y
def make_bow_vector(sentence, word_to_ix):
vec = torch.zeros(len(word_to_ix))
for word in sentence:
vec[word_to_ix[word]] += 1
return vec.view(1, -1) # size가 [26]이 아닌 [26,1]로 나와야한다.
def make_target(label, label_to_ix):
return torch.LongTensor([label_to_ix[label]])
model = BoWClassifier(vocab_size, labels_n)
print(model)
print('')
for p in model.parameters():
print(p)
with torch.no_grad(): # grad없이(학습 없이) 그냥 결과만 확인하는 방법
sample = data[0]
bow_vector = make_bow_vector(sample[0], word_to_ix)
log_probs = model(bow_vector)
print(log_probs)
label_to_ix = {'SPANISH' : 0, 'ENGLISH' : 1}
with torch.no_grad(): # test data 확인하기
for sent, label in test_data:
bow_vec = make_bow_vector(sent, word_to_ix)
log_probs = model(bow_vec)
print(log_probs)
print(next(model.parameters())[:, word_to_ix['creo']]) # creo에 해당하는 가중치 행렬 부분 출력
print(next(model.parameters())[:, word_to_ix['is']])
loss_function = nn.NLLLoss()
optimizer = optim.SGD(model.parameters(), lr = 0.1)
batch_size = 1
epoch_n = 300
iter_n = 1000
for epoch in range(epoch_n):
loss_avg = 0
for sent, label in data:
model.zero_grad()
bow_vec = make_bow_vector(sent, word_to_ix)
target = make_target(label, label_to_ix)
log_probs = model(bow_vec)
loss = loss_function(log_probs, target)
loss.backward()
optimizer.step()
print(next(model.parameters())[:, word_to_ix['creo']])
print(next(model.parameters())[:, word_to_ix['is']])
label_to_ix = {'SPANISH' : 0, 'ENGLISH' : 1}
with torch.no_grad(): # test data 확인하기
for sent, label in test_data:
bow_vec = make_bow_vector(sent, word_to_ix)
log_probs = model(bow_vec)
print(sent, log_probs)
###Output
['Yo', 'creo', 'que', 'si'] tensor([[-0.1436, -2.0118]])
['it', 'is', 'lost', 'on', 'me'] tensor([[-3.1194, -0.0452]])
|
Web_Application/MLApp.ipynb | ###Markdown
14/06/220 Step 1: Model Training and Validation
###Code
!pip install pycaret
###Output
_____no_output_____
###Markdown
FlaskFlask is a framework that allows you to build web applications. A web application can be a commercial website, a blog, e-commerce system, or an application that generates predictions from data provided in real-time using trained models
###Code
!pip install Flask
###Output
Requirement already satisfied: Flask in /usr/local/lib/python3.6/dist-packages (1.1.2)
Requirement already satisfied: Jinja2>=2.10.1 in /usr/local/lib/python3.6/dist-packages (from Flask) (2.11.2)
Requirement already satisfied: click>=5.1 in /usr/local/lib/python3.6/dist-packages (from Flask) (7.1.2)
Requirement already satisfied: itsdangerous>=0.24 in /usr/local/lib/python3.6/dist-packages (from Flask) (1.1.0)
Requirement already satisfied: Werkzeug>=0.15 in /usr/local/lib/python3.6/dist-packages (from Flask) (1.0.1)
Requirement already satisfied: MarkupSafe>=0.23 in /usr/local/lib/python3.6/dist-packages (from Jinja2>=2.10.1->Flask) (1.1.1)
###Markdown
GitHubGitHub is a cloud-based service that is used to host, manage and control code. Imagine you are working in a large team where multiple people (sometime hundreds of them) are making changes HerokuHeroku is a platform as a service (PaaS) that enables the deployment of web apps based on a managed container system, with integrated data services and a powerful ecosystem. In simple words, this will allow you to take the application from your local machine to the cloud so that anybody can access it using a Web URL Why Deploy Machine Learning ModelsThe deployment of ML models is the process of making models available in production where web applications, enterprise software and APIs can consume the trained model by providing new data points and generating predictions> Normally models are built so that they can be used to predict an outcome **(binary value i.e. 1 or 0 for Classification, continuous values for Regression, labels for Clustering etc.** There are 2 broad ways of generating predictions + (i) predict by batch+ (ii) predict in real-timeThis experiment we'll deploy a machine learning model to predict in real-time Workflow Business ProblemAn insurance company wants to improve its cash flow forecasting by better predicting patient charges using demographic and basic patient health risk metrics at the time of hospitalization The ObjectiveTo build a web application where demographic and health information of a patient is entered in a web form to predict charges
###Code
# GET DATA
from pycaret.datasets import get_data
data = get_data('insurance')
data.shape
# EXPERIMENT 1
# PERFORMED WITH DEFAULT PRE-PROCESSING SETTINGS
from pycaret.regression import *
s = setup(data, target='charges', session_id=123)
# MODEL TRAINING AND VALIDATION
lr = create_model('lr')
###Output
_____no_output_____
###Markdown
Notice the impact of transformations and automatic feature engineering. The R2 has increased by 10% with very little effort. We can compare the residual plot from our linear regression model for both experiments and observe the impact of transformations and feature engineering on the heteroskedasticity of model
###Code
# PLOT TRAINED MODEL
plot_model(lr)
# EXPERIMENT 2
# ADDITIONAL PRE-PROCESSING
s2 = setup(data, target='charges', session_id=123,
normalize=True,
polynomial_features=True, # automatic FE
trigonometry_features=True, # automatic FE
feature_interaction=True, # automatic FE
bin_numeric_features=['age', 'bmi']) # binning continuous data into intervals
s2[0].columns
lr = create_model('lr')
# PLOT TRAINED MODEL
plot_model(lr)
###Output
_____no_output_____
###Markdown
ML is an iterative process. A Number of iterations and techniques are used depending on how critical the task/problem is and what the impact will be if predictions are wrong. The severity and impact of a model to predict a patient outcome in real-time in the ICU of a hospital is far more than a model built to predict customer churnIn this experiment, we have performed only 2 iterations and the linear regression model from the 2nd experiment will be used for deployment> At this stage, however, the model is still only an object within our notebook. To save it as a file that can be transferred to and consumed by other applications, run the following code
###Code
# SAVE TRANSFORMATION PIPELINE AND MODEL
save_model(lr, '/deployment_28042020')
# PREVIEW THE PIPELINE AND MODEL STORED IN VARIABLE
deployment_28042020 = load_model('/deployment_28042020')
deployment_28042020
import requests
url = 'https://pycaret-insurance.herokuapp.com/predict_api'
pred = requests.post(url, json={'age':55, 'sex':'male', 'bmi':59, 'children':1, 'smoker':'male', 'region':'northwest'})
print(pred.json())
###Output
75714.0
###Markdown
Step 2: Build Web AppThis will connect to and generate predictions on new data in real-time2 parts to this application+ (i) front-end designed using HTML+ (ii) back-end developed using Flask Front-end of Web ApplicationGenerally, the front-end of web applications are built using HTML which is not the focus of this experiment. We have used a simple HTML template and a CSS style sheet to design an input formYou don’t need to be an expert in HTML to build simple applications. There are numerous free platforms that provide HTML and CSS templates as well as enable building beautiful HTML pages quickly by using a drag and drop interface CSS Style SheetCSS (also known as Cascading Style Sheets) describes how HTML elements are displayed on a screen. It's an efficient way of controlling the layout of your application. Style sheets contain information such as + background color+ font size+ and color + margins etc. They are saved externally as a .css file and is linked to HTML but including 1 line of code ``` style.css@import url(https://fonts.googleapis.com/css?family=Open+Sans);.btn { display: inline-block; *display: inline; *zoom: 1; padding: 4px 10px 4px; margin-bottom: 0; font-size: 13px; line-height: 18px; color: 333333; text-align: center;text-shadow: 0 1px 1px rgba(255, 255, 255, 0.75); vertical-align: middle; background-color: f5f5f5; background-image: -moz-linear-gradient(top, ffffff, e6e6e6); background-image: -ms-linear-gradient(top, ffffff, e6e6e6); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(ffffff), to(e6e6e6)); background-image: -webkit-linear-gradient(top, ffffff, e6e6e6); background-image: -o-linear-gradient(top, ffffff, e6e6e6); background-image: linear-gradient(top, ffffff, e6e6e6); background-repeat: repeat-x; filter: progid:dximagetransform.microsoft.gradient(startColorstr=ffffff, endColorstr=e6e6e6, GradientType=0); border-color: e6e6e6 e6e6e6 e6e6e6; border-color: rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.1) rgba(0, 0, 0, 0.25); border: 1px solid e6e6e6; -webkit-border-radius: 4px; -moz-border-radius: 4px; border-radius: 4px; -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); -moz-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.05); cursor: pointer; *margin-left: .3em; }.btn:hover, .btn:active, .btn.active, .btn.disabled, .btn[disabled] { background-color: e6e6e6; }.btn-large { padding: 9px 14px; font-size: 15px; line-height: normal; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; }.btn:hover { color: 333333; text-decoration: none; background-color: e6e6e6; background-position: 0 -15px; -webkit-transition: background-position 0.1s linear; -moz-transition: background-position 0.1s linear; -ms-transition: background-position 0.1s linear; -o-transition: background-position 0.1s linear; transition: background-position 0.1s linear; }.btn-primary, .btn-primary:hover { text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); color: ffffff; }.btn-primary.active { color: rgba(255, 255, 255, 0.75); }.btn-primary { background-color: 4a77d4; background-image: -moz-linear-gradient(top, 6eb6de, 4a77d4); background-image: -ms-linear-gradient(top, 6eb6de, 4a77d4); background-image: -webkit-gradient(linear, 0 0, 0 100%, from(6eb6de), to(4a77d4)); background-image: -webkit-linear-gradient(top, 6eb6de, 4a77d4); background-image: -o-linear-gradient(top, 6eb6de, 4a77d4); background-image: linear-gradient(top, 6eb6de, 4a77d4); background-repeat: repeat-x; filter: progid:dximagetransform.microsoft.gradient(startColorstr=6eb6de, endColorstr=4a77d4, GradientType=0); border: 1px solid 3762bc; text-shadow: 1px 1px 1px rgba(0,0,0,0.4); box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2), 0 1px 2px rgba(0, 0, 0, 0.5); }.btn-primary:hover, .btn-primary:active, .btn-primary.active, .btn-primary.disabled, .btn-primary[disabled] { filter: none; background-color: 4a77d4; }.btn-block { width: 100%; display:block; }* { -webkit-box-sizing:border-box; -moz-box-sizing:border-box; -ms-box-sizing:border-box; -o-box-sizing:border-box; box-sizing:border-box; }html { width: 100%; height:100%; overflow:hidden; }body { width: 100%; height:100%; font-family: 'Open Sans', sans-serif; background: 092756; color: fff; font-size: 18px; text-align:center; letter-spacing:1.2px; background: -moz-radial-gradient(0% 100%, ellipse cover, rgba(104,128,138,.4) 10%,rgba(138,114,76,0) 40%),-moz-linear-gradient(top, rgba(57,173,219,.25) 0%, rgba(42,60,87,.4) 100%), -moz-linear-gradient(-45deg, 670d10 0%, 092756 100%); background: -webkit-radial-gradient(0% 100%, ellipse cover, rgba(104,128,138,.4) 10%,rgba(138,114,76,0) 40%), -webkit-linear-gradient(top, rgba(57,173,219,.25) 0%,rgba(42,60,87,.4) 100%), -webkit-linear-gradient(-45deg, 670d10 0%,092756 100%); background: -o-radial-gradient(0% 100%, ellipse cover, rgba(104,128,138,.4) 10%,rgba(138,114,76,0) 40%), -o-linear-gradient(top, rgba(57,173,219,.25) 0%,rgba(42,60,87,.4) 100%), -o-linear-gradient(-45deg, 670d10 0%,092756 100%); background: -ms-radial-gradient(0% 100%, ellipse cover, rgba(104,128,138,.4) 10%,rgba(138,114,76,0) 40%), -ms-linear-gradient(top, rgba(57,173,219,.25) 0%,rgba(42,60,87,.4) 100%), -ms-linear-gradient(-45deg, 670d10 0%,092756 100%); background: -webkit-radial-gradient(0% 100%, ellipse cover, rgba(104,128,138,.4) 10%,rgba(138,114,76,0) 40%), linear-gradient(to bottom, rgba(57,173,219,.25) 0%,rgba(42,60,87,.4) 100%), linear-gradient(135deg, 670d10 0%,092756 100%); filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='3E1D6D', endColorstr='092756',GradientType=1 );}.login { position: absolute; top: 40%; left: 50%; margin: -150px 0 0 -150px; width:400px; height:400px;}.login h1 { color: fff; text-shadow: 0 0 10px rgba(0,0,0,0.3); letter-spacing:1px; text-align:center; }input { width: 100%; margin-bottom: 10px; background: rgba(0,0,0,0.3); border: none; outline: none; padding: 10px; font-size: 13px; color: fff; text-shadow: 1px 1px 1px rgba(0,0,0,0.3); border: 1px solid rgba(0,0,0,0.3); border-radius: 4px; box-shadow: inset 0 -5px 45px rgba(100,100,100,0.2), 0 1px 1px rgba(255,255,255,0.2); -webkit-transition: box-shadow .5s ease; -moz-transition: box-shadow .5s ease; -o-transition: box-shadow .5s ease; -ms-transition: box-shadow .5s ease; transition: box-shadow .5s ease;}input:focus { box-shadow: inset 0 -5px 45px rgba(100,100,100,0.4), 0 1px 1px rgba(255,255,255,0.2); }``` ``` home.html Predict Insurance Bill link to css style sheet Predict Insurance Bill update fields for input form here Predict {{pred}}``` Back-end of Web ApplicationThe back-end of a web application is developed using a Flask framework. For beginner’s it is intuitive to consider Flask as a library that you can import just like any other library in PythonIf you remember from the Step 1 above we have finalized linear regression model that was trained on 60 features that were automatically engineered by PyCaret. However, the front-end of our web app has an input form that collects only the 6 features i.e. age, sex, bmi, children, smoker, regionHow do we transform 6 features of a new data point in real-time into 60 features on which model was trained? With a sequence of transformations applied during model training, coding becomes increasingly complex and time-taking task> Using PyCaret all transformations such as categorical encoding, scaling, missing value imputation, feature engineering and even feature selection are automatically executed in real-time before generating predictions ``` build appfrom flask import Flask,request, url_for, redirect, render_template, jsonifyfrom pycaret.regression import *import pandas as pdimport pickleimport numpy as npapp = Flask(__name__)model = load_model('deployment_28042020') loading transformation pipeline and trained modelcols = ['age', 'sex', 'bmi', 'children', 'smoker', 'region']@app.route('/')def home(): return render_template("home.html")@app.route('/predict',methods=['POST'])def predict(): int_features = [x for x in request.form.values()] final = np.array(int_features) data_unseen = pd.DataFrame([final], columns = cols) prediction = predict_model(model, data=data_unseen, round = 0) this is where the MAGIC happens. predict_model() of pycaret applies the entire ML pipeline sequentially and generates predictions using TRAINED prediction = int(prediction.Label[0]) return render_template('home.html',pred='Expected Bill will be {}'.format(prediction))@app.route('/predict_api',methods=['POST'])def predict_api(): data = request.get_json(force=True) data_unseen = pd.DataFrame([data]) prediction = predict_model(model, data=data_unseen) output = prediction.Label[0] return jsonify(output)if __name__ == '__main__': app.run(debug=True)```
###Code
###Output
_____no_output_____ |
analysis/IMP_ir_007_Auto_Tracking_engine.ipynb | ###Markdown
Load the pre-processed data and display an example frame
###Code
data_folder = 'example_data/tracking/'
top_folder_0 = '/media/chrelli/Data0/recording_20200821-131033'
top_folder_1 = '/media/chrelli/Data1/recording_20200821-131033'
# validation dataset with LASER ON 90 fps
top_folder_0 = '/media/chrelli/Data0/recording_20200828-114251'
top_folder_1 = '/media/chrelli/Data1/recording_20200828-114251'
# Data with female partner 3500 exposure
top_folder_0 = '/media/chrelli/Data0/recording_20201110-102009/'
top_folder_1 = '/media/chrelli/Data1/recording_20201110-102009/'
top_folder_0 = '/media/chrelli/SSD4TB/Data0_backup/recording_20201110-102009/'
top_folder_1 = '/media/chrelli/SSD4TB/Data1_backup/recording_20201110-102009/'
# # Data with male partner 3500 exposure
# top_folder_0 = '/media/chrelli/Data0/recording_20201110-105540/'
# top_folder_1 = '/media/chrelli/Data1/recording_20201110-105540/'
# top_folder_0 = '/media/chrelli/SSD4TB/Data0_backup/recording_20201110-105540'
# top_folder_1 = '/media/chrelli/SSD4TB/Data1_backup/recording_20201110-105540'
# # Thrusting data
# top_folder_0 = '/media/chrelli/Data0/recording_20201112-104816/'
# top_folder_1 = '/media/chrelli/Data1/recording_20201112-104816/'
data_folder = top_folder_0
# load ALL the frames as jagged lines
with h5py.File(data_folder+'/pre_processed_frames.hdf5', mode='r') as hdf5_file:
print(hdf5_file.keys())
print(len(hdf5_file['dataset']))
jagged_lines = hdf5_file['dataset'][...]
from utils.cuda_tracking_utils import unpack_from_jagged, cheap4d
# kill first 6 secs of the frames (delay is ~180)
start_frame = 10*60
pos, pos_weights, keyp, pkeyp, ikeyp = unpack_from_jagged(jagged_lines[start_frame])
print(ikeyp)
print(pos.shape)
fig = plt.gcf()
plt.title("N positions is {}".format(pos.shape))
plt.show()
cheap4d(pos,keyp,ikeyp)
# AUTO-start the tracking, start with frame 0, and loop until there is a frame, where the animals are reasonably far apart!
plt.close('all')
from utils.cuda_tracking_utils_weights_for_figures import body_constants, particles_to_distance_cuda, clean_keyp_by_r
from utils.cuda_tracking_utils_weights_for_figures import loading_wrapper
from utils.clicking import *
from scipy.spatial.distance import pdist, squareform
from scipy.stats import kurtosis
from scipy.stats import skew
from scipy.cluster.vq import vq, kmeans, whiten
def bimodality_coeff(dat):
# from https://www.ncbi.nlm.nih.gov/pmc/articles/PMC3791391/
m3 = skew(dat)
m4 = kurtosis(dat)
n = len(dat)
BC = (m3**2 + 1)/(m4**2 + 3 * ((n-1)**2)/( (n-2)*(n-3) ) )
return BC
def check_mouse_separation(keyp,ikeyp, has_implant = False):
# get the xy-coordinates of the keypoints
xy_head = keyp[(ikeyp == 1)| (ikeyp == 2) ,:].cpu().numpy()
xy_tail = keyp[ikeyp == 3,:].cpu().numpy()
if len(xy_head) < 2 or len(xy_tail) < 2:
return False, np.nan*np.ones((2,3)), np.nan*np.ones((2,3))
# kmeans two clusters # a bit slow, but w/e
c_head,distortion_head = kmeans(xy_head, 2)
c_tail,distortion_tail = kmeans(xy_tail, 2)
# associate to partners, since there are only two, we can do it this way
match_0 = np.argmin(np.sum((c_tail - c_head[0,:])**2,1))
match_1 = np.argmin(np.sum((c_tail - c_head[1,:])**2,1))
# assemble the mice
mouse_0 = np.vstack((c_head[0,:],c_tail[match_0,:]))
mouse_1 = np.vstack((c_head[1,:],c_tail[match_1,:]))
# check that all the cross-mouse distances are larger than a threshold
# h2h, t2t, and the two h2t
cross_difference = mouse_0[[0,1,0,1],:] - mouse_1[[0,1,1,0],:]
cross_dist = np.sqrt( np.sum(cross_difference**2,1) )
# Hmm
separation_cutoff = 0.05 # let's do 7 cm!
sep_criterion = np.all(cross_dist > separation_cutoff)
#also make sure the two mice are long enough!
mouse_lengths = np.array([np.linalg.norm(np.diff(mouse_0,axis = 0)),
np.linalg.norm(np.diff(mouse_1,axis = 0))])
length_cutoff = 0.05 # let's do 7 cm!
l_criterion = np.all(mouse_lengths > length_cutoff)
criterion = sep_criterion * l_criterion
# If we are looking for an implant, we also want to make sure that there are visible implant keypoints
if has_implant:
impl_criterion = np.sum(ikeyp.cpu().numpy() == 0) > 0
criterion = criterion * impl_criterion
# make sure that mouse0 has the implant!
xy_impl = keyp[ikeyp == 0,:].cpu().numpy()
c_impl = np.mean(xy_impl,axis=0)
# distance to mice, sorting by the head, see above
mice= [mouse_0,mouse_1]
d1 = np.sqrt(np.sum( (c_head - c_impl)**2 ,axis = 1))
# since there are only two, we can just do logic, little bit hacky
implanted_index = np.argmin(d1).astype('bool')
mouse_0 = np.vstack([mice[implanted_index.astype(int)],c_impl])
mouse_1 = mice[ (~implanted_index).astype(int) ]
return criterion, mouse_0, mouse_1
def plot_top_view(pos,keyp,ikeyp,mouse_0=None,mouse_1=None):
keyp_colors = ['dodgerblue','green','red','orange']
plt.figure()
posi = pos.cpu().numpy()
plt.plot(posi[:,0],posi[:,1],'.',alpha=.1,c='k')
if mouse_0 is not None:
lw = 3
plt.plot(mouse_0[:,0],mouse_0[:,1],':',lw=lw,c='k')
plt.plot(mouse_1[:,0],mouse_1[:,1],':',lw=lw,c='peru')
ss = 10
plt.plot(mouse_0[0,0],mouse_0[0,1],'v',markersize=ss,c='k')
plt.plot(mouse_1[0,0],mouse_1[0,1],'v',markersize=ss,c='peru')
plt.plot(mouse_0[1,0],mouse_0[1,1],'o',markersize=ss,c='k')
plt.plot(mouse_1[1,0],mouse_1[1,1],'o',markersize=ss,c='peru')
for ik,colors in enumerate(keyp_colors):
xy = keyp[ikeyp == ik,:2].cpu().numpy()
xy = keyp[ikeyp == ik,:2].cpu().numpy()
x = xy[:,0]
y = xy[:,1]
plt.plot(x,y,'o',c=keyp_colors[ik])
plt.show()
def plot_3_views(pos,keyp,ikeyp,mouse_0=None,mouse_1=None,has_implant=False,savepath=None):
keyp_colors = ['dodgerblue','green','red','orange']
plt.figure(figsize = (9,6))
for i_row in range(2):
for i_sub,(p1,p2) in enumerate(zip([0,0,1],[1,2,2])):
plt.subplot(2,3,1+i_sub+3*i_row)
if i_row ==0:
posi = pos.cpu().numpy()
plt.plot(posi[:,p1],posi[:,p2],'.',alpha=.01,c='k')
for ik,colors in enumerate(keyp_colors):
xy = keyp[ikeyp == ik,:].cpu().numpy()
xy = keyp[ikeyp == ik,:].cpu().numpy()
x = xy[:,p1]
y = xy[:,p2]
plt.plot(x,y,'o',c=keyp_colors[ik],alpha = 0.3)
if mouse_0 is not None:
lw = 1.5
mz = 2
if mouse_0.shape[0] > 2:
plt.plot(mouse_0[[2,0,1],p1],mouse_0[[2,0,1],p2],'o-',markersize=mz,lw=lw,c='k')
else:
plt.plot(mouse_0[:,p1],mouse_0[:,p2],'o-',markersize=mz,lw=lw,c='k')
plt.plot(mouse_1[:,p1],mouse_1[:,p2],'o-',markersize=mz,lw=lw,c='peru')
plt.xlim([-.2,.2])
plt.ylim([-.2,.2])
if savepath is not None:
plt.savefig(savepath,dpi=300)
plt.show()
def generate_starting_x0(pos,keyp,ikeyp,mouse_0,mouse_1, has_implant = False):
# x0_start is a,b,s, theta, phi, xyz
# negative angle on b, because the rotation is down
vec_0 = mouse_0[0,:] - mouse_0[1,:]
center_0 = mouse_0[1,:] + 0.5 *vec_0
# gamma and beta:
g_0 = angle_between(np.array([1,0,0]),vec_0 *np.array([1,1,0]) )
b_0 = - angle_between(vec_0 * np.array([1,1,0]),vec_0)
# x0_start is a,b,s, theta, phi, xyz
vec_1 = mouse_1[0,:] - mouse_1[1,:]
center_1 = mouse_1[1,:] + 0.5 *vec_1
g_1 = angle_between(np.array([1,0,0]),vec_1 *np.array([1,1,0]) )
b_1 = - angle_between(vec_1 * np.array([1,1,0]),vec_1)
if has_implant: # if there is an implant, we just squeeze it in to the right place!
mouse_0_start = np.hstack([ np.array([b_0,g_0,.9,0.,0.,0.]), center_0])
else:
mouse_0_start = np.hstack([ np.array([b_0,g_0,.9,0.,0.]), center_0])
mouse_1_start = np.hstack([ np.array([b_1,g_1,.9,0.,0.]), center_1])
x0_start = np.hstack([mouse_0_start, mouse_1_start])
return x0_start
has_implant = True
# skip first 5 secs to make sure all cameras are going:
for start_frame in np.arange(5*60,30000,100):
pos,pos_weights,keyp,ikeyp = loading_wrapper(start_frame,jagged_lines)
criterion, mouse_0, mouse_1 = check_mouse_separation(keyp,ikeyp,has_implant = has_implant)
if criterion:
# plot_top_view(pos,keyp,ikeyp,mouse_0,mouse_1)
print("Found a good starting point on frame # {} !".format(start_frame) )
# # convert the mouse_0, mouse_1 into a starting guess
x0_start = generate_starting_x0(pos,keyp,ikeyp,mouse_0,mouse_1, has_implant = has_implant)
plot_3_views(pos,keyp,ikeyp,mouse_0,mouse_1,has_implant=has_implant,savepath='../st')
break
pos,pos_weights,keyp,ikeyp = loading_wrapper(start_frame,jagged_lines)
part = torch.Tensor(x0_start).to(torch_device).unsqueeze(0)
# no need for the the particle to have gradients
part.requires_grad = False
print(part)
print(part.shape)
print(pos.shape)
###Output
tensor([[-0.4757, 1.3763, 0.9000, 0.0000, 0.0000, 0.0000, -0.1049, 0.0409,
0.0219, 0.3951, -0.1016, 0.9000, 0.0000, 0.0000, -0.0779, -0.0545,
0.0239]], device='cuda:0')
torch.Size([1, 17])
torch.Size([3854, 3])
###Markdown
Import the actual particle filter tracking engine, 'MousePFilt', and fit the first frame
###Code
# get the limits for the tracking and the residual functions
from utils.cuda_tracking_utils_weights_for_figures import search_cone, global_min, global_max
from utils.cuda_tracking_utils_weights_for_figures import add_implant_residual,add_body_residual,add_ass_residual, add_ear_residual, add_nose_residual
# for single mice
# global_min = global_min[:3,4:]
# global_max = global_max[:,:3]
from utils.cuda_tracking_utils_weights_for_figures import search_cone_noimp, global_min_noimp, global_max_noimp
print(global_max_noimp)
print(global_min_noimp)
print(global_max)
print(global_min)
from utils.cuda_tracking_utils_weights_for_figures import MousePFilt, make_some_bounds,particles_to_body_supports_cuda
if has_implant:
upper_bound,lower_bound = make_some_bounds(part,search_cone/3,global_max,global_min)
pzo = MousePFilt(swarm_size = 150)
else:
part_noimp = part
upper_bound,lower_bound = make_some_bounds(part_noimp,search_cone_noimp/3,global_max_noimp,global_min_noimp)
pzo = MousePFilt(swarm_size = 150,has_implant = False) # fix
pzo.search_space(upper_bound,lower_bound)
# populate the tracker
pzo.populate(sobol = True)
# send the data for tracking
pzo.pos = pos[::1,:]
pzo.pos_weights = pos_weights
pzo.keyp = keyp
pzo.ikeyp = ikeyp
pzo.max_iterations = 1
self = pzo
pzo.run2(cinema=False, fast_sort = False)
plt.close('all')
print(np.mean(self.time_benchmarking))
# if has_implant:
# pzo.plot_status(reduce_mean=True,keep_open=True,plot_ellipsoids=True)
# else:
# pzo.plot_status_noimpl(reduce_mean=False,keep_open=True,plot_ellipsoids=True)
#
plt.close('all')
swarm_sizes = [10,50,100,200,400,600]
gpu_fast_sort = [15.2,15.4,17.8,21.3,35.0,51.5]
gpu_normal_sort = [14.7,15.3,17.1,20.8,34.6,50]
plt.figure(figsize = (2.5,2))
# plt.plot(swarm_sizes,gpu_fast_sort,'--o', label = 'GPU, topk')
plt.plot(swarm_sizes,gpu_normal_sort,'-ok', label = 'GPU, sort')
# swarm_sizes = [10,50,100,150,200,400,600]
# cpu_fast_sort = [23.6, 49.3, 117.8, 177.8, 266.8, 12.8, 1654.0]
# cpu_normal_sort = [24.8, 48.3, 116.5, 181.7, 280.3, 816.7, 1658.6]
swarm_sizes = [10,50,100,200,400,600]
cpu_fast_sort = [23.6, 49.3, 117.8, 266.8, 812.8, 1654.0]
cpu_normal_sort = [24.8, 48.3, 116.5, 280.3, 816.7, 1658.6]
# plt.plot(swarm_sizes,cpu_fast_sort,'--o', label = 'CPU, topk')
plt.plot(swarm_sizes,cpu_normal_sort,'--ok', label = 'CPU, sort')
# plt.legend()
# plt.xlabel("Particles")
# plt.ylabel("Iteration time [ms]")
plt.xticks(swarm_sizes,rotation=90)
ax = plt.gca()
# ax.set_xticklabels('')
ax = plt.gca()
# ax.set_ylim([0, None])
plt.yscale('log')
plt.yticks([10,100,1000])
ax.set_yticklabels(['10 ms','100 ms','1 s'
])
ax.set_yticklabels([])
ax.set_xticklabels([])
# plt.tight_layout()
plt.savefig('revision_figures/profile_network/GPUspeed.pdf',transparent= True)
plt.show()
plt.close('all')
###Output
_____no_output_____
###Markdown
Make a wrapper to run the particle filter across all frames, set options
###Code
if has_implant:
pzo = MousePFilt(swarm_size = 200)
def pzo_wrapper(part,pos,pos_weights,keyp,ikeyp,pzo):
upper_bound,lower_bound = make_some_bounds(part,search_cone/3,global_max,global_min)
pzo.search_space(upper_bound,lower_bound)
pzo.populate(sobol = True)
pzo.pos = pos
pzo.pos_weights = pos_weights
pzo.keyp = keyp
pzo.ikeyp = ikeyp
pzo.max_iterations = 3
pzo.run2(verbose=False,use_weights = False,barrier = True,fast_sort = True)
return pzo.meanwinner
else:
pzo = MousePFilt(swarm_size = 200,has_implant = False) # fix
def pzo_wrapper(part,pos,pos_weights,keyp,ikeyp,pzo):
upper_bound,lower_bound = make_some_bounds(part,search_cone_noimp/3,global_max_noimp,global_min_noimp)
pzo.search_space(upper_bound,lower_bound)
pzo.populate(sobol = True)
pzo.pos = pos
pzo.pos_weights = pos_weights
pzo.keyp = keyp
pzo.ikeyp = ikeyp
pzo.max_iterations = 3
pzo.run2(verbose=False,use_weights = False,barrier = True,fast_sort = True)
return pzo.meanwinner
###Output
_____no_output_____
###Markdown
Make a function to dump plots during tracking
###Code
plt.close('all')
from utils.plotting_during_tracking import *
def plot_single_frame(part,pos, keyp, ikeyp,frame):
plt.ioff()
plt.close('all')
# the winning mouse is the one, with the lowest final loss
#end_loss = [np.mean(ll[-1:]) for ll in ll_holder]
dist0,_,body_support_0 = particles_to_distance_cuda(part[:,:8],pos,implant = False)
dist1,_,body_support_1 = particles_to_distance_cuda(part[:,8:],pos,implant = False)
body_supports = [body_support_0,body_support_1]
#best_idx = np.argmin(end_loss)
#best_mouse = best_holder[best_idx]
fig = plt.figure(figsize=(7.5,7.5))
ax = fig.add_subplot(1, 1, 1, projection='3d')
plot_particles_new_nose(ax,part.cpu().numpy(),pos.cpu().numpy(),body_constants,alpha = .5,keyp = keyp.cpu(), ikeyp = ikeyp.cpu(),body_supports = [ [i.cpu() for i in j] for j in body_supports] )
plt.axis('tight')
ax.set_xlim(-.10,.20)
ax.set_ylim(-.20,.1)
ax.set_zlim(0,.3)
ax.view_init(elev=60., azim=-147.)
plt.savefig('frames/temp/frame_'+str(frame).zfill(6)+'.png')
# plt.show()
plt.close('all')
# frame = start_frame
# plot_single_frame(part,pos, keyp, ikeyp,frame)
###Output
_____no_output_____
###Markdown
And import a bank for online filtering and prediction
###Code
plt.close('all')
from utils.cuda_tracking_utils import rls_bank
def ML_predict(bank,i_frame,embedding,tracking_holder,guessing_holder):
# # do the RLS step to predict the next step
if (i_frame > embedding + 2)*True:
x_train = np.flip( tracking_holder[:-1,(i_frame-embedding):i_frame],axis = 1)
y_train = tracking_holder[:-1,i_frame]
d = torch.from_numpy(y_train.copy())
x = torch.from_numpy(x_train.copy())
# make sure the type is right
d = torch.tensor(d,dtype = torch.float32)
x = torch.tensor(x,dtype = torch.float32)
# and send to the holder
bank.adapt(d,x)
# guess the upcoming step!
x_predict = torch.cat((d.unsqueeze(1),x[:,:-1]),1)
part_guess = bank.predict(x_predict)
if ( i_frame +1 ) < ( guessing_holder.shape[1] - 2 ):
guessing_holder[:-1,i_frame+1] = part_guess[:].numpy()
return bank,part_guess.unsqueeze(0),guessing_holder
else:
return bank,0.,guessing_holder
###Output
_____no_output_____
###Markdown
Now, run the tracking across all frames and save to disk
###Code
# start_frame = 10*60
n_frames = len(jagged_lines)-1-start_frame
# do 1000 frames!
# n_frames = 1000
# do one min for profiling
# n_frames = 1*30*60
end_frame = start_frame + n_frames
if has_implant:
part = torch.Tensor(x0_start).to(torch_device).unsqueeze(0)
pzo = MousePFilt(swarm_size = 200)
pzo.has_implant = True
part = pzo_wrapper(part,pos,pos_weights,keyp,ikeyp,pzo)
else:
part = torch.Tensor(x0_start).to(torch_device).unsqueeze(0)
pzo = MousePFilt(swarm_size = 150,has_implant = False)
pzo.has_implant = False
part = pzo_wrapper(part,pos,pos_weights,keyp,ikeyp,pzo)
# for naming the tracked behavior
if has_implant:
var_names = ['b','c','s','psi','theta','phi','x','y','z','b','c','s','theta','phi','x','y','z','frame']
ivar_names = ['b0','c0','s0','psi0','theta0','phi0','x0','y0','z0','b1','c1','s1','theta1','phi1','x1','y1','z1','frame']
else:
var_names = ['b','c','s','theta','phi','x','y','z','b','c','s','theta','phi','x','y','z','frame']
ivar_names = ['b0','c0','s0','theta0','phi0','x0','y0','z0','b1','c1','s1','theta1','phi1','x1','y1','z1','frame']
embedding = 5
bank = rls_bank(n_vars = part.shape[1], embedding=embedding)
bank.mu = .99
x0_trace = []
frame_trace = []
history_trace = []
# just make a numpy holder for it directly
# and a frame index which tells us which frame we're currently tracking
tracking_holder = np.zeros((part.shape[1]+1,n_frames))
guessing_holder = np.zeros((part.shape[1]+1,n_frames))*np.nan
from tqdm import tqdm, tqdm_notebook
with torch.no_grad():
for i_frame, this_frame in enumerate(tqdm(range(start_frame,start_frame+n_frames))):
# if we've learned, preditc
# load and fit
pos,pos_weights,keyp,ikeyp = pos,pos_weights,keyp,ikeyp = loading_wrapper(this_frame,jagged_lines)
# optional, cut down the cloud a bit
# pos = pos[::3,:]
# keyp,ikeyp = clean_keyp_by_r(part,keyp,ikeyp,has_implant=has_implant)
# part,history = klm_routine(part,pos,keyp,ikeyp,max_iters = 100,verbose=False,save_history = True,ftol = 1e-4)
# part, histo = pzo_step(part,pos,keyp,ikeyp)
part = pzo_wrapper(part,pos,pos_weights,keyp,ikeyp,pzo)
# 3. add to fitting history
x0_trace.append(part.cpu().numpy())
frame_trace.append(this_frame)
# history_trace.append(history)
# and update the frame index and the tracking_holder
tracking_holder[:-1,i_frame] = part[0,:].cpu().numpy()
tracking_holder[-1,i_frame] = this_frame
# always adapt!
if True:
bank,part_guess,guessing_holder = ML_predict(bank,i_frame,embedding,tracking_holder,guessing_holder)
if i_frame > 150 and True:
# do prediction after the first 150 frames
pass
# part_guess[:,[5,13]] = part[:,[5,13]]
# part = part_guess
# part[:,[0,1,2,6,7,8,9,10,11,14,15,16]] = part_guess[:,[0,1,2,6,7,8,9,10,11,14,15,16]]
if has_implant:
part[:,[6,7,8,14,15,16]] = part_guess[:,[6,7,8,14,15,16]].to(torch_device)
# part = part_guess.to(torch_device)
else:
# part[:,[0,1,2,5,6,7,8,9,10,13,14,15]] = part_guess[:,[0,1,2,5,6,7,8,9,10,13,14,15]].to(torch_device)
# part = part_guess.to(torch_device)
part[:,[5,6,7,13,14,15]] = part_guess[:,[5,6,7,13,14,15]].to(torch_device)
if i_frame%2 == 0 and False:
# fully update the
if i_frame > 150:
plot_single_frame(part_guess.to(torch_device),pos, keyp, ikeyp,this_frame)
else:
plot_single_frame(part,pos, keyp, ikeyp,this_frame)
if i_frame%500 == 0:
top_folder = 'frames/'
print("saving tracking at frame {} of {}...".format(i_frame,start_frame+n_frames))
np.save(top_folder+'tracking_holder.npy',tracking_holder)
np.save(top_folder+'guessing_holder.npy',guessing_holder)
np.save(top_folder+'body_constants.npy',body_constants)
print("tracking saved!")
tracked_behavior = {
"var": var_names,
"ivar": ivar_names,
"body_constants": body_constants,
"body_constant_names" : ["body_scale","a_hip_min","a_hip_max","b_hip_min","b_hip_max","a_nose","b_nose","d_nose","x_impl","z_impl","r_impl"],
"start_frame": start_frame,
"end_frame": this_frame, # this saves it druring running!
"has_implant": has_implant,
"tracking_holder": tracking_holder,
"guessing_holder": guessing_holder,
"data_folder": data_folder
}
print("pickling tracking at frame {}...".format(i_frame))
with open(data_folder +'/tracked_behavior_in_progress.pkl', 'wb+') as f:
pickle.dump(tracked_behavior,f)
print("behavior tracking pickled!")
# TODO also add the date of the folder as a string?
tracked_behavior = {
"var": var_names,
"ivar": ivar_names,
"body_constants": body_constants,
"body_constant_names" : ["body_scale","a_hip_min","a_hip_max","b_hip_min","b_hip_max","a_nose","b_nose","d_nose","x_impl","z_impl","r_impl"],
"start_frame": start_frame,
"end_frame": end_frame,
"has_implant": has_implant,
"tracking_holder": tracking_holder,
"guessing_holder": guessing_holder,
"data_folder": data_folder
}
print("pickling tracking at frame {}...".format(i_frame))
with open(data_folder +'/tracked_behavior.pkl', 'wb+') as f:
pickle.dump(tracked_behavior,f)
print("behavior tracking pickled!")
#%% Plot tracked data to see that everything is fine
plt.close('all')
plt.figure()
if has_implant:
NNN = ['b','c','s','psi','theta','phi','x','y','z','b','c','s','theta','phi','x','y','z']
else:
NNN = ['b','c','s','theta','phi','x','y','z','b','c','s','theta','phi','x','y','z']
for ii,name in enumerate(NNN):
plt.subplot(len(NNN),1,ii+1)
index = np.arange(tracking_holder.shape[1])
plt.plot(index[:i_frame],tracking_holder[ii,:i_frame])
plt.plot(index[:i_frame],guessing_holder[ii,:i_frame])
plt.ylabel(str(ii)+'_'+name)
plt.show()
# TRY to develop a kind of 3D kalman better version of the KRLS-T
# TRY to penalize if the center of the implant is lower than the neck of the mouse
# TRY to wrap it for Bonsai
# TRY to make a much more lightweight GUI for playing the data as a video. Preferably for a
# jupyter notebook
# Add tracking time
# Make nice GUI
# ENsure that the TTL pulses are recorded
# Penalize implant to the side of head
# Penalize flying tail
###Output
_____no_output_____ |
RecipeServerNotebooks/NLTK/RP_NLTK.ipynb | ###Markdown
RealPython NLTK Tutorial---Learning the basics of the NLTK module for Natural Language Processessing following this tutorial.https://realpython.com/nltk-nlp-python/This focuses mostly on text preprocessing to faciliate better categorization and analysis. PurposeThe reason for familiarizing myself with this Python package and general area of machine learning is to provide the text categoziation functionality necessary for my [Reicpes Appliction](https://github.com/supermanzer/local-recipe-server)
###Code
# Import needed packages and define constants
import nltk
import numpy as np
nltk.download('punkt')
###Output
[nltk_data] Downloading package punkt to /home/ryan/nltk_data...
[nltk_data] Unzipping tokenizers/punkt.zip.
###Markdown
TokenizingTokenizing is the process of splitting text by word, sentence, or group of sentences. This can be useful in segmenting individual ingredients and steps in the aforemetioned app.
###Code
# Word & Sentence Tokenization
from nltk.tokenize import sent_tokenize, word_tokenize
# Providing a basic sample
example_string = """
Muad'Dib learned rapidly because his first training was in how to learn.
And the first lesson of all was the basic trust that he could learn.
It's shocking to find how many people do not believe they can learn,
and how many more believe learning to be difficult."""
# Splitting up our sample string by sentence.
sent_tokenize(example_string)
# Splitting up sample string by word
word_tokenize(example_string)
###Output
_____no_output_____ |
python/Create Pattern.ipynb | ###Markdown
Line Pattern
###Code
def compute_linepattern(center, width, horiz,
focal, phase_factor, phase_max, phase_wrap_neg, phase_wrap_pos, wavelen):
a = black_pattern(float)
if horiz:
size_para, size_cross = LCOS_X_SIZE, LCOS_Y_SIZE
a_rot = a
else:
size_para, size_cross = LCOS_Y_SIZE, LCOS_X_SIZE
a_rot = a.T
delta = width / 2
xy = np.arange(size_cross) - size_cross // 2
mask = np.abs(xy - center) < delta
r = (xy[mask] - center) * LCOS_PIX_SIZE
phase = phase_max + phase_spherical(r, f=focal, wavelen=wavelen)
a_rot[mask] = phase[:, np.newaxis]
a = phase_wrapping(a, phase_max=phase_max, phase_factor=phase_factor,
phase_wrap_pos=phase_wrap_pos,
phase_wrap_neg=phase_wrap_neg)
return a.round().astype('uint8')
dl = dict(
center=100,
width=30,
horiz=False,
focal=0.036,
phase_factor=82,
phase_max=3,
phase_wrap_pos=False,
phase_wrap_neg=True,
wavelen=532e-9,
)
a = compute_linepattern(**dl)
fig, ax = plt.subplots(figsize=(8, 5))
im = plt.imshow(a, interpolation='none', cmap='magma', vmin=0, vmax=255)
plt.colorbar()
###Output
_____no_output_____ |
Animation.ipynb | ###Markdown
To run by *RunnerPhonon.ipynb*, *cphonon.ipynb*. Creates an animation which is displayed at the *cphonon.ipynb*.
###Code
#%matplotlib notebook
#%pylab qt
#from matplotlib import pyplot as plt
import matplotlib
from matplotlib import animation, rc
from IPython.display import HTML
import numpy as np
rc('animation', html='jshtml')
###Output
_____no_output_____
###Markdown
For the purpose of checking this script alone I leave the commeted out cell bellow
###Code
# %run cphonon.ipynb
# fig
# display(OutWidg)
###Output
_____no_output_____
###Markdown
Initializing values
###Code
if (MyInteraction.result is None): #Before all widgets are moved MyInteraction.result==None. Or when N==2 and bc==1
if (N == 2): #The problematic case of
Vanim=V[:,0]
omegaAnim=omega[0]
else:
Vanim=V[:,1]
omegaAnim=omega[1]
else:
Vanim=MyInteraction.result[2]
omegaAnim=MyInteraction.result[1]
N=NInter.value
bc=bcInter.value
ModeNr=ModeNrInter.value
M1=M1Inter.value
M2=M2Inter.value
Mimp=MimpInter.value
Nimp=NimpInter.value
gamma=gammaInter.value
imp_enabled=imp_enabledInter.value
omegaAnim=5 if np.abs(omegaAnim)<1e-06 else omegaAnim #Otherwise it will mant to make an infinite animation
###Output
_____no_output_____
###Markdown
Dealing with the case of fixed boundary conditions and N=2. This solves the problem
###Code
%%capture
try:
len(Vanim)
except:
Vanim=[[0,0],[0,0]]
omegaAnim=10
Ampl=0.1*((M1+M2)/gamma)**(1/4) # don't know the reason for exactly ^(1/4)
Vplot=np.array(np.transpose(Vanim)*Ampl)[0] #transpose and [0] is for some stupid reasons with arrays
oddAtoms = np.arange(1, N+1, 2)
evenAtoms = np.arange(2, N+1, 2)
allAtoms = np.arange(1, N+1)
Vodd=Vplot[::2]
Veven=Vplot[1::2]
yodd = [0]*len(Vodd)
yeven = [0]*len(Veven)
%%capture
#%matplotlib tk
fig2, ax3 = plt.subplots()
fig2.set_size_inches(10.0, 1.4)
ax3.set_xlim(( 0.5, N+0.5))
ax3.set_ylim((-0.05, 0.05))
#fig2.title='MyTitle'
line,=ax3.plot([], [], 'bo', markersize=10)
if M1 > M2:
mark1 = 11
mark2 = 6
elif M1 == M2:
mark1 = mark2 = 6
else:
mark1 = 6
mark2 = 11
#Marker colors for masses
if M1==M2:
col1, col2="blue", "blue"
else:
col1, col2="blue", "green"
#plotlays=[2]
plotcols, markers = [col1,col2,"white","red"], [mark1,mark2,11,(np.log(Mimp/M1+1.7)*7)] #["blue","green"],[mark1,mark2]
lines = []
for index in range(4):
lobj = ax3.plot([],[],'o',markersize=markers[index],color=plotcols[index])[0]
lines.append(lobj)
def init():
for line in lines:
line.set_data([],[])
return lines
ax3.set(xlabel="x/a, m", ylabel='y',title='Atomic oscilations, mode nr = {}, bc = {}, $\gamma$ = {}'.format(ModeNr,bc,gamma)) # for N={}, M1={}, M2={},Minp={}.'.format(N,M1,M2,Mimp)
steptick=N//15+1
xTickArray=np.arange(0, N+2, step=steptick)
xTickArray = xTickArray.astype('float64')
xTickArray[0], xTickArray[-1]=0.5, N+0.5
ax3.set_xticks(xTickArray)
fig2.subplots_adjust(bottom=0.3,top=0.8)
###Output
_____no_output_____
###Markdown
Note how big problems the periodic boundary conditions cause(particle can appear from the other side). Otherwise the function bellow bould have been pretty simple. Now you have to look through all the cases and change a bit the plotting data.It still does not deal with the case when the impurity is the last particle and it should reapear on the other side. If somebody really creates such a case then congrats, u cool!
###Code
def animate(t, *args):
if bc==0: #periodic boundary conditions (particle can appear from the other side) causes problems
lines[0].set_data(oddAtoms+np.real(np.exp(-omegaAnim*t*0.005*2*np.pi*1j)*Vodd), yodd)
lines[1].set_data(evenAtoms+np.real(np.exp(-omegaAnim*t*0.005*2*np.pi*1j)*Veven), yeven)
if np.real(np.exp(-omegaAnim*t*0.005*2*np.pi*1j)*Vodd[0])< -0.5:
lines[0].set_data(np.append(oddAtoms[1:],N+1)+
np.real(np.exp(-omegaAnim*t*0.005*2*np.pi*1j)*np.append(Vodd[1:],Vodd[0])), yodd)
lines[1].set_data(evenAtoms+np.real(np.exp(-omegaAnim*t*0.005*2*np.pi*1j)*Veven), yeven)
elif (np.real(np.exp(-omegaAnim*t*0.005*2*np.pi*1j)*Vodd[-1])> 0.5) & (N%2) :
lines[0].set_data(np.append(0,oddAtoms)+
np.real(np.exp(-omegaAnim*t*0.005*2*np.pi*1j)*np.append(Vodd[-1],Vodd)), np.append(0,yodd)) #I don't take out the data point because it is not visible anyway
lines[1].set_data(evenAtoms+np.real(np.exp(-omegaAnim*t*0.005*2*np.pi*1j)*Veven), yeven)
elif (np.real(np.exp(-omegaAnim*t*0.005*2*np.pi*1j)*Veven[-1])> 0.5) & (N%2==0) :
lines[0].set_data(oddAtoms+
np.real(np.exp(-omegaAnim*t*0.005*2*np.pi*1j)*Vodd), yodd) #I don't take out the data point because it is not visible anyway
lines[1].set_data(np.append(0,evenAtoms)+np.real(np.exp(-omegaAnim*t*0.005*2*np.pi*1j)*np.append(Veven[-1],Veven)), np.append(0,yeven))
else:
lines[0].set_data(oddAtoms+np.cos(omegaAnim*t*0.005*2*np.pi)*Vodd, yodd)
lines[1].set_data(evenAtoms+np.cos(omegaAnim*t*0.005*2*np.pi)*Veven, yeven)
if imp_enabled == 1:
lines[2].set_data(Nimp+np.real(np.exp(-omegaAnim*t*0.005*2*np.pi*1j)*Vplot[Nimp-1]),0)
lines[3].set_data(Nimp+np.real(np.exp(-omegaAnim*t*0.005*2*np.pi*1j)*Vplot[Nimp-1]),0)
return (lines)
anim = animation.FuncAnimation(fig2, animate, init_func=init,
frames=int(np.round(200/omegaAnim)), interval=4, blit=True) #frames value taken so that the film ends exatly at the end of the period
###Output
_____no_output_____ |
jupyter_russian/topic07_unsupervised/lesson7_part1_PCA.ipynb | ###Markdown
Открытый курс по машинному обучению. Сессия № 2Автор материала: программист-исследователь Mail.ru Group, старший преподаватель Факультета Компьютерных Наук ВШЭ Юрий Кашницкий. Материал распространяется на условиях лицензии [Creative Commons CC BY-NC-SA 4.0](https://creativecommons.org/licenses/by-nc-sa/4.0/). Можно использовать в любых целях (редактировать, поправлять и брать за основу), кроме коммерческих, но с обязательным упоминанием автора материала. Тема 7. Обучение без учителя Часть 1. Метод главных компонент Существует несколько эквивалентных математических формулировок метода главных компонент. Основная идея заключается в нахождении таких попарно ортогональных направлений в исходном многомерном пространстве, вдоль которых данные имеют наибольший разброс (выборочную дисперсию). Эти направления называются главными компонентами. Другая формулировка PCA – для данной многомерной случайной величины построить такое ортогональное преобразование координат, что в результате корреляции между отдельными координатами обратятся в ноль. Таким образом, задача сводится к диагонализации матрицы ковариаций, что эквивалентно нахождению сингулярного разложения матрицы исходных данных. Хотя формально задачи сингулярного разложения матрицы данных и спектрального разложения ковариационной матрицы совпадают, алгоритмы вычисления сингулярного разложения напрямую, без вычисления ковариационной матрицы и её спектра, более эффективны и устойчивы.Ещё одной из формулировок задачи PCA является нахождение такой $d$-мерной плоскости в признаковом пространстве, что ошибка проецирования обучающих объектов на нее будет минимальной. Направляющие векторы этой плоскости и будут первыми $d$ главными компонентами. Интуиция метода Рассмотрим двухмерный пример, где вместо двух признаков можно завести их линейную комбинацию.Для "хорошего"направления сумма расстояний до выбранной прямой (гиперплоскости) минимальна. Слева показано "хорошее" направление, справа – "плохое". Пусть прямая задается единичным вектором $u$. Минимизация расстояния от точки $x^{(i)}$ до прямой эквивалентна минимизации угла между радиус-вектором $x^{(i)}$ и вектором $u$. Косинус такого угла можно выразить так:$$ \Large cos~\theta = \frac{x^{{(i)}^T} u }{||x^{(i)}||}, ||u|| = 1$$ Задача состоит в том, чтобы найти такое направление $u$, что сумма квадратов проекций минимальна (то есть сумма квадратов косинусов максимальна). $$\Large u = \arg\max_{||u||=1} \frac{1}{m} \sum_{i=1}^{m} {(x^{{(i)}^T} u )^2} = \arg\max_{||u||=1} \frac{1}{m} \sum_{i=1}^{m} {(u^Tx^{{(i)}} )(x^{{(i)}^T} u )} =$$ $$ \Large \arg\max_{||u||=1} u^T \left[\frac{1}{m} \sum_{i=1}^{m}{x^{(i)} x^{(i)^T}} \right] u $$Удобно ввести ковариационную матрицу $$\Large \Sigma = \sum_{i=1}^{m}{x^{(i)} x^{(i)^T}} = X^TX \in \mathbb{R}^{n \times n}$$Тогда решается оптимизационная задача:$$\Large \max_{u}{u^T \Sigma u},~~~u^Tu = 1$$Лагранжиан для этой задачи: $$\Large L(u, \lambda) = u^T \Sigma u - \lambda (u^Tu-1)$$Его производная по $u$: $$\Large \nabla_u L = \Sigma u - \lambda u = 0 \Leftrightarrow \Sigma u =\lambda u$$То есть $u$ должен быть собственным вектором ковариационной матрицы $\Sigma$. Обобщение: если хотим ввести $k$-размерное пространства вместо $n$- размерного, берем $k$ собственных векторов ковариационной матрицы $\Sigma$, соответсвующих $k$ максимальным собственным значениям. Тогда новым образом каждой точки $x^{(i)} \in \mathbb{R}^n$ обучающей выборки будет $$\Large z^{(i)} = \left[\begin{array}{c}u_1^Tx^{(i)} \\ u_2^Tx^{(i)} \\ \ldots \\ u_k^Tx^{(i)} \end{array}\right] \in \mathbb{R}^k$$Один из наиболее эффективных способов нахождения собственных векторов матрицы $\Sigma$ - использование сингулярного разложения исходной матрицы $X$:$$\Large X = UDV^T,$$где $U \in R^{m \times m}$, $V \in R^{n \times n}$, а $D \in R^{m \times n}$ - диагональная матрица вида Сингулярное разложениеРассмотрим более подробно задачу о сингулярном разложении матрицы $X \in \mathbb{R}^{m \times n}$. *Сингулярным разложением* матрицы $X$ называется представление её в виде $X = UD V^T$, где: - $D$ есть $m\times n$ матрица у которой элементы, лежащие на главной диагонали, неотрицательны, а все остальные элементы равны нулю. - $U$ и $V$ – ортогональные матрицы порядка $m$ и $n$ соответственно. Элементы главной диагонали матрицы $D$ называются *сингулярными числами* матрицы $X$, а столбцы $U$ и $V$ левыми и правыми *сингулярными векторами* матрицы $X$.Заметим, что матрицы $XX^T$ и $X^TX$ являются симметрическими неотрицательно определенными матрицами, и поэтому ортогональным преобразованием могут быть приведены к диагональному виду, причем на диагонали будут стоять неотрицательные собственные значения этих матриц.В силу указанных выше свойств матриц $X^TX$ и $XX^T$ сингулярное разложение матрицы $X$ тесно связано с задачей о спектральном разложении этих матриц. Более точно:- Левые сингулярные векторы матрицы $X$ – это собственные векторы матрицы $XX^T$.- Правые сингулярные векторы матрицы $X$ – это собственные векторы матрицы $X^TX$.- Сингулярные числа матрицы $X$ - это корни из собственных значений матрицы $X^TX$ (или $XX^T$).Таким образом, для нахождения сингулярного разложения матрицы $X$ необходимо, найти собственные векторы и значения матриц $X^TX$ и $XX^T$ и составить из них матрицы $U, V, D$. Алгоритм PCA1. Определить $k<n$ – новую размерность2. Вычесть из $X$ среднее, то есть заменить все $\Large x^{(i)}$ на $$\Large x^{(i)} - \frac{1}{m} \sum_{i=1}^{m}{x^{(i)}}$$3. Привести данные к единичной дисперсии: посчитать $$\Large \sigma_j^2 = \frac{1}{m} \sum_{i=1}^{m}{(x^{(i)})^2}$$и заменить $\Large x_j^{(i)}$ на $\Large \frac{x_j^{(i)}}{\sigma_j}$ 4. Найти сингулярное разложение матрицы $X$:$$\Large X = UDV^T$$5. Положить $V =$ [$k$ левых столбцов матрицы $V$]6. Вернуть новую матрицу $$\Large Z = XV \in \mathbb{R}^{m \times k}$$ Двухмерный примерЧтобы понять геометрический смысл главных компонент, рассмотрим в качестве примера выборку из двухмерного нормального распределения с явно выраженным "главным" направлением. Выделим в ней главные компоненты и посмотрим, какую долю дисперсии объясняет каждая из них.
###Code
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
from sklearn.decomposition import PCA
np.random.seed(0)
mean = np.array([0.0, 0.0])
cov = np.array([[1.0, -1.0],
[-2.0, 3.0]])
X = np.random.multivariate_normal(mean, cov, 300)
pca = PCA()
pca.fit(X)
print('Proportion of variance explained by each component:\n' +\
'1st component - %.2f,\n2nd component - %.2f\n' %
tuple(pca.explained_variance_ratio_))
print('Directions of principal components:\n' +\
'1st component:', pca.components_[0],
'\n2nd component:', pca.components_[1])
plt.figure(figsize=(10,10))
plt.scatter(X[:, 0], X[:, 1], s=50, c='r')
for l, v in zip(pca.explained_variance_ratio_, pca.components_):
d = 5 * np.sqrt(l) * v
plt.plot([0, d[0]], [0, d[1]], '-k', lw=3)
plt.axis('equal')
plt.title('2D normal distribution sample and its principal components')
plt.show()
###Output
_____no_output_____
###Markdown
Первая главная компонента (ей соответствует более длинный вектор) объясняет более 90% дисперсии исходных данных. Это говорит о том, что она содержит в себе почти всю информацию о расположении выборки в пространстве, и вторая компонента может быть опущена. Спроецируем данные на первую компоненту.
###Code
# Keep enough components to explain 90% of variance
pca = PCA(0.90)
X_reduced = pca.fit_transform(X)
# Map the reduced data into the initial feature space
X_new = pca.inverse_transform(X_reduced)
plt.figure(figsize=(10,10))
plt.plot(X[:, 0], X[:, 1], 'or', alpha=0.3)
plt.plot(X_new[:, 0], X_new[:, 1], 'or', alpha=0.8)
plt.axis('equal')
plt.title('Projection of sample onto the 1st principal component')
plt.show()
###Output
_____no_output_____
###Markdown
Мы понизили размерность данных вдвое, при этом сохранив наиболее значимые черты. В этом заключается основной принцип понижения размерности – приблизить многомерный набор данных с помощью данных меньшей размерности, сохранив при этом как можно больше информации об исходных данных. Визуализация многомерных данныхОдним из применений метода главных компонент является визуализации многомерных данных в двухмерном (или трехмерном) пространстве. Для этого необходимо взять первые две главных компоненты и спроецировать данные на них. При этом, если признаки имеют различную природу, их следует отмасштабировать. Основные способы масштабирования:- На единичную дисперсию по осям (масштабы по осям равны средним квадратичным отклонениям — после этого преобразования ковариационная матрица совпадает с матрицей коэффициентов корреляции).- На равную точность измерения (масштаб по оси пропорционален точности измерения данной величины).- На равные требования в задаче (масштаб по оси определяется требуемой точностью прогноза данной величины или допустимым её искажением — уровнем толерантности). Пример с набором данных Iris
###Code
from sklearn import datasets
iris = datasets.load_iris()
X, y = iris.data, iris.target
pca = PCA(n_components=2)
X_reduced = pca.fit_transform(X)
print("Meaning of the 2 components:")
for component in pca.components_:
print(" + ".join("%.3f x %s" % (value, name)
for value, name in zip(component,
iris.feature_names)))
plt.figure(figsize=(10,7))
plt.scatter(X_reduced[:, 0], X_reduced[:, 1], c=y, s=70, cmap='viridis')
plt.show()
###Output
_____no_output_____
###Markdown
Пример с набором данных digitsРассмотрим применение метода главных компонент для визуализации данных из набора изображений рукописных цифр.
###Code
from sklearn.datasets import load_digits
digits = load_digits()
X = digits.data
y = digits.target
pca = PCA(n_components=2)
X_reduced = pca.fit_transform(X)
print('Projecting %d-dimensional data to 2D' % X.shape[1])
plt.figure(figsize=(12,10))
plt.scatter(X_reduced[:, 0], X_reduced[:, 1], c=y,
edgecolor='none', alpha=0.7, s=40,
cmap=plt.cm.get_cmap('nipy_spectral', 10))
plt.colorbar()
plt.show()
###Output
_____no_output_____
###Markdown
Полученная картинка позволяет увидеть зависимости между различными цифрами. Например, цифры 0 и 6 располагаются в соседних кластерах, что говорит об их схожем написании. Наиболее "разбросанный" (по другим кластерам) – это кластер, соответствующий цифре 8, что говорит о том, что она имеет много различных написаний, делающих её схожей со многими другими цифрами.Посмотрим, как выглядят первые две главные компоненты.
###Code
f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
im = pca.components_[0]
ax1.imshow(im.reshape((8, 8)), cmap='binary')
ax1.set_xticks([])
ax1.set_yticks([])
ax1.set_title('First principal component')
im = pca.components_[1]
ax2.imshow(im.reshape((8, 8)), cmap='binary')
ax2.set_xticks([])
ax2.set_yticks([])
ax2.set_title('Second principal component')
plt.show()
###Output
_____no_output_____
###Markdown
Сжатие данныхДругим применением PCA является снижение размерности данных для их сжатия. Рассмотрим, как влияет число отбираемых главных компонент (на которые осуществляется проекция) на качество восстановления исходного изображения.
###Code
plt.figure(figsize=(4,2))
plt.imshow(X[15].reshape((8, 8)), cmap='binary')
plt.xticks([])
plt.yticks([])
plt.title('Source image')
plt.show()
fig, axes = plt.subplots(8, 8, figsize=(10, 10))
fig.subplots_adjust(hspace=0.1, wspace=0.1)
for i, ax in enumerate(axes.flat):
pca = PCA(i + 1).fit(X)
im = pca.inverse_transform(pca.transform(X[15].reshape(1, -1)))
ax.imshow(im.reshape((8, 8)), cmap='binary')
ax.text(0.95, 0.05, 'n = {0}'.format(i + 1), ha='right',
transform=ax.transAxes, color='red')
ax.set_xticks([])
ax.set_yticks([])
###Output
_____no_output_____
###Markdown
Как понять, какое число главных компонент достаточно оставить? Для этого может оказаться полезным следующий график, выражающий зависимость общей доли объясняемой дисперсии от числа главных компонент.
###Code
pca = PCA().fit(X)
plt.figure(figsize=(10,7))
plt.plot(np.cumsum(pca.explained_variance_ratio_), color='k', lw=2)
plt.xlabel('Number of components')
plt.ylabel('Total explained variance')
plt.xlim(0, 63)
plt.yticks(np.arange(0, 1.1, 0.1))
plt.axvline(21, c='b')
plt.axhline(0.9, c='r')
plt.show()
pca = PCA(0.9).fit(X)
print('We need %d components to explain 90%% of variance'
% pca.n_components_)
###Output
_____no_output_____
###Markdown
Предобработка данных Метод главных компонент часто используется для предварительной обработки данных перед обучением классификатора. В качестве примера такого применения рассмотрим задачу о распознавании лиц. Для начала посмотрим на исходные данные.
###Code
%%time
from sklearn import datasets
from sklearn.model_selection import train_test_split
lfw_people = datasets.fetch_lfw_people(min_faces_per_person=50,
resize=0.4, data_home='../../data/faces')
print('%d objects, %d features, %d classes' % (lfw_people.data.shape[0],
lfw_people.data.shape[1], len(lfw_people.target_names)))
print('\nPersons:')
for name in lfw_people.target_names:
print(name)
###Output
_____no_output_____
###Markdown
Распределение целевого класса:
###Code
for i, name in enumerate(lfw_people.target_names):
print("{}: {} photos.".format(name, (lfw_people.target == i).sum()))
fig = plt.figure(figsize=(8, 6))
for i in range(15):
ax = fig.add_subplot(3, 5, i + 1, xticks=[], yticks=[])
ax.imshow(lfw_people.images[i], cmap='bone')
X_train, X_test, y_train, y_test = \
train_test_split(lfw_people.data, lfw_people.target, random_state=0)
print('Train size:', X_train.shape[0], 'Test size:', X_test.shape[0])
###Output
_____no_output_____
###Markdown
Вместо обычного PCA воспользуемся его приближенной версией (randomized PCA), которая позволяет существенно ускорить работу алгоритма на больших наборах данных. Выделим 100 главных компонент. Как видно, они объясняют более 90% дисперсии исходных данных.
###Code
pca = PCA(n_components=100, svd_solver='randomized')
pca.fit(X_train)
print('100 principal components explain %.2f%% of variance' %
(100 * np.cumsum(pca.explained_variance_ratio_)[-1]))
plt.figure(figsize=(10,7))
plt.plot(np.cumsum(pca.explained_variance_ratio_), lw=2, color='k')
plt.xlabel('Number of components')
plt.ylabel('Total explained variance')
plt.xlim(0, 100)
plt.yticks(np.arange(0, 1.1, 0.1))
plt.show()
###Output
_____no_output_____
###Markdown
Посмотрим на главные компоненты (или главные "лица"). Видим, что первые главные компоненты несут в себе информацию в основном об освещении на фотографии, в то время как оставшиеся выделяют какие-то отдельные черты человеческого лица - глаза, брови и другие.
###Code
fig = plt.figure(figsize=(16, 6))
for i in range(30):
ax = fig.add_subplot(3, 10, i + 1, xticks=[], yticks=[])
ax.imshow(pca.components_[i].reshape((50, 37)), cmap='bone')
###Output
_____no_output_____
###Markdown
PCA позволяет посмотреть на "среднее" лицо – тут считается среднее по каждому новому признаку.
###Code
plt.imshow(pca.mean_.reshape((50, 37)), cmap='bone')
plt.xticks([])
plt.yticks([])
plt.show()
###Output
_____no_output_____
###Markdown
Перейдем теперь непосредственно к классификации. Мы сократили размерность данных (с 1850 признаков до 100), что позволяет существенно ускорить работу стандартных алгоритмов обучения. Настроим SVM с RBF-ядром и посмотрим на результаты классификации.
###Code
%%time
from sklearn.svm import LinearSVC
X_train_pca = pca.transform(X_train)
X_test_pca = pca.transform(X_test)
clf = LinearSVC(random_state=17).fit(X_train_pca, y_train)
y_pred = clf.predict(X_test_pca)
from sklearn.metrics import (accuracy_score, classification_report,
confusion_matrix)
print("Accuracy: %f" % accuracy_score(y_test, y_pred))
print(classification_report(y_test, y_pred, target_names=lfw_people.target_names))
M = confusion_matrix(y_test, y_pred)
M_normalized = M.astype('float') / M.sum(axis=1)[:, np.newaxis]
plt.figure(figsize=(10,10))
im = plt.imshow(M_normalized, interpolation='nearest', cmap='Greens')
plt.colorbar(im, shrink=0.71)
tick_marks = np.arange(len(lfw_people.target_names))
plt.xticks(tick_marks - 0.5, lfw_people.target_names, rotation=45)
plt.yticks(tick_marks, lfw_people.target_names)
plt.tight_layout()
plt.ylabel('True person')
plt.xlabel('Predicted person')
plt.title('Normalized confusion matrix')
plt.show()
###Output
_____no_output_____ |
AI 이노베이션 스퀘어 음성지능 과정/20201107/lecture_seq2seq.ipynb | ###Markdown
실습 내용: SEQ2SEQ 모델링 1. Vocab: 한국어 음절 단위 2. 데이터: 한국어 Q&A 문장 - ex.)공무원 시험 죽을 거 같아 --> 철밥통 되기가 어디 쉽겠어요. Installation (초기 환경 세팅)
###Code
import time
import math
import random
import numpy as np
import json
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
print(torch.__version__)
import os
os.environ["CUDA_VISIBLE_DEVICES"]="0"
device = 'cuda' if torch.cuda.is_available() else 'cpu'
print("device: {}".format(device))
seed = 0
torch.manual_seed(seed)
torch.cuda.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
np.random.seed(seed)
random.seed(seed)
###Output
_____no_output_____
###Markdown
0. 데이터 확인 - 출처: https://github.com/eagle705/pytorch-transformer-chatbot/tree/master/data_in
###Code
!head -n 10 "./data/train_chatbot.txt"
!head -n 10 "./data/valid_chatbot.txt"
###Output
'head'은(는) 내부 또는 외부 명령, 실행할 수 있는 프로그램, 또는
배치 파일이 아닙니다.
###Markdown
1. 어휘사전 (Vocab) 생성 // (음절 단위)
###Code
PAD_TOKEN_ID = 0
UNK_TOKEN_ID = 1
PAD_TOKEN = '<pad>'
UNK_TOKEN = '<unk>'
SOS_TOKEN = '<sos>'
EOS_TOKEN = '<eos>'
def create_vocab(train_path, valid_path, vocab_path):
data = []
with open(train_path, 'r', encoding='utf-8') as f:
for line in f:
for sent in line.strip().split('\t'):
data.append(sent)
with open(valid_path, 'r', encoding='utf-8') as f:
for line in f:
for sent in line.strip().split('\t'):
data.append(sent)
vocab = set()
for sent in data:
for char in sent:
vocab.add(char)
vocab_list = list(sorted(vocab))
vocab_list.insert(0, PAD_TOKEN)
vocab_list.insert(1, UNK_TOKEN)
vocab_list.insert(2, SOS_TOKEN)
vocab_list.insert(3, EOS_TOKEN)
print(vocab_list)
# 파일로 어휘사전 저장
with open(vocab_path, 'w', encoding='utf-8') as f:
f.write(json.dumps(vocab_list, indent=4, ensure_ascii=False))
create_vocab(train_path="./data/train_chatbot.txt",
valid_path="./data/valid_chatbot.txt",
vocab_path="./vocab.json")
###Output
['<pad>', '<unk>', '<sos>', '<eos>', ' ', '!', '%', "'", ',', '-', '.', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ';', '?', 'A', 'B', 'C', 'D', 'L', 'N', 'O', 'P', 'S', 'X', '_', 'a', 'c', 'g', 'j', 'k', 'n', 'o', 's', '~', '…', 'ㅊ', 'ㅋ', 'ㅎ', 'ㅜ', 'ㅠ', '가', '각', '간', '갇', '갈', '감', '갑', '값', '갔', '강', '갖', '같', '갚', '개', '객', '갠', '갯', '갱', '걍', '걔', '거', '걱', '건', '걷', '걸', '검', '겁', '것', '겉', '게', '겐', '겜', '겟', '겠', '겨', '격', '겪', '견', '결', '겹', '겼', '경', '곁', '계', '곗', '고', '곡', '곤', '곧', '골', '곰', '곱', '곳', '공', '과', '관', '광', '괘', '괜', '괴', '교', '구', '국', '군', '굳', '굴', '굶', '굽', '굿', '궁', '궈', '권', '궜', '귀', '귄', '귈', '귐', '규', '균', '귤', '그', '극', '근', '글', '긁', '금', '급', '긋', '긍', '기', '긴', '길', '김', '깃', '깅', '깊', '까', '깍', '깎', '깐', '깔', '깜', '깝', '깠', '깡', '깨', '깬', '깰', '깼', '꺼', '꺽', '껀', '껄', '껏', '께', '껴', '꼈', '꼬', '꼭', '꼰', '꼴', '꼼', '꼿', '꽁', '꽂', '꽃', '꽈', '꽉', '꽝', '꽤', '꾸', '꾹', '꾼', '꿀', '꿈', '꿎', '꿔', '꿧', '꿨', '꿩', '꿰', '뀌', '뀐', '뀔', '끄', '끈', '끊', '끌', '끓', '끔', '끗', '끝', '끼', '낀', '낄', '낌', '나', '낙', '낚', '난', '날', '남', '납', '낫', '났', '낭', '낮', '낳', '내', '낸', '낼', '냄', '냅', '냈', '냉', '냐', '냥', '너', '넋', '넌', '널', '넓', '넘', '넛', '넣', '네', '넥', '넷', '넹', '녀', '녁', '년', '념', '녔', '녕', '노', '녹', '논', '놀', '놈', '놉', '농', '높', '놓', '놔', '놨', '뇌', '뇨', '뇽', '누', '눅', '눈', '눌', '눕', '눠', '눴', '뉴', '느', '는', '늘', '늙', '늠', '능', '늦', '늪', '니', '닉', '닌', '닐', '님', '닙', '닝', '다', '닥', '닦', '단', '닫', '달', '닭', '닮', '닳', '담', '답', '닷', '당', '닿', '대', '댄', '댈', '댓', '댔', '댜', '더', '덕', '던', '덜', '덤', '덥', '덧', '덩', '덮', '데', '덴', '델', '뎌', '뎠', '도', '독', '돈', '돋', '돌', '돕', '동', '돼', '됐', '되', '된', '될', '됨', '됩', '됬', '두', '둑', '둔', '둘', '둠', '둥', '둬', '뒀', '뒤', '뒷', '뒹', '듀', '드', '득', '든', '듣', '들', '듦', '듬', '듭', '듯', '등', '디', '딘', '딛', '딜', '딧', '딨', '딩', '딪', '따', '딱', '딴', '딸', '땀', '땅', '때', '땐', '땜', '땠', '땡', '떄', '떠', '떡', '떤', '떨', '떴', '떻', '떼', '뗄', '또', '똑', '똥', '뚝', '뚫', '뚱', '뛰', '뛴', '뜁', '뜨', '뜩', '뜬', '뜰', '뜸', '뜻', '띄', '띠', '띰', '띵', '라', '락', '란', '랄', '람', '랍', '랐', '랑', '랖', '래', '랙', '랜', '랠', '램', '랩', '랫', '랬', '랭', '량', '러', '런', '럴', '럼', '럽', '럿', '렀', '렁', '렇', '레', '렉', '렌', '렐', '렘', '렛', '렜', '려', '력', '련', '렬', '렴', '렵', '렷', '렸', '령', '례', '로', '록', '론', '롤', '롭', '롯', '롱', '뢰', '료', '루', '룩', '룰', '룸', '룽', '뤄', '류', '륜', '률', '르', '륵', '른', '를', '름', '릅', '릇', '릎', '리', '릭', '린', '릴', '림', '립', '릿', '링', '마', '막', '만', '많', '말', '맘', '맙', '맛', '망', '맞', '맡', '매', '맥', '맨', '맴', '맷', '맹', '맺', '머', '먹', '먼', '멀', '멈', '멋', '멍', '메', '멘', '멤', '며', '면', '명', '몇', '모', '목', '몫', '몬', '몰', '몸', '몹', '못', '몽', '묘', '무', '묵', '문', '묻', '물', '뭇', '뭉', '뭐', '뭔', '뭘', '뭣', '뮤', '미', '민', '믿', '밀', '밉', '밌', '밍', '밑', '바', '박', '밖', '반', '받', '발', '밝', '밟', '밤', '밥', '방', '밭', '배', '백', '밸', '뱃', '뱄', '뱉', '버', '벅', '번', '벋', '벌', '범', '법', '벗', '벚', '베', '벤', '벨', '벴', '벼', '벽', '변', '별', '볍', '병', '볕', '보', '복', '볶', '본', '볼', '봄', '봅', '봇', '봉', '봐', '봤', '뵈', '부', '북', '분', '불', '붓', '붕', '붙', '뷔', '브', '블', '비', '빈', '빌', '빔', '빗', '빙', '빚', '빛', '빠', '빡', '빨', '빴', '빵', '빼', '빽', '뺄', '뺏', '뺴', '뻐', '뻑', '뻔', '뻘', '뻣', '뻤', '뻥', '뽀', '뽑', '뽕', '뿅', '뿌', '뿍', '뿐', '쁘', '쁜', '쁠', '쁨', '삐', '삔', '사', '삭', '산', '살', '삶', '삼', '삽', '삿', '샀', '상', '새', '색', '샌', '샐', '샘', '샜', '생', '샤', '서', '석', '섞', '선', '섣', '설', '섬', '섭', '섯', '섰', '성', '세', '섹', '센', '셀', '셔', '션', '셥', '셨', '소', '속', '손', '솔', '솜', '송', '쇠', '쇼', '숍', '숏', '수', '숙', '순', '술', '숨', '숫', '숭', '쉬', '쉴', '쉼', '쉽', '슈', '스', '슨', '슬', '슴', '습', '슷', '승', '시', '식', '신', '실', '싫', '심', '십', '싱', '싶', '싸', '싹', '싼', '쌀', '쌈', '쌍', '쌓', '쌤', '쌩', '써', '썩', '썰', '썸', '썹', '썼', '쎄', '쎈', '쎌', '쏘', '쏜', '쏟', '쏠', '쐬', '쑤', '쑥', '쓰', '쓴', '쓸', '씀', '씁', '씌', '씨', '씩', '씬', '씰', '씸', '씹', '씻', '씽', '아', '악', '안', '앉', '않', '알', '압', '앗', '았', '앙', '앞', '애', '액', '앨', '앱', '야', '약', '얄', '얇', '양', '얘', '어', '억', '언', '얻', '얼', '얽', '엄', '업', '없', '엇', '었', '엉', '엊', '에', '엔', '엘', '엠', '엣', '여', '역', '엮', '연', '열', '염', '엽', '엿', '였', '영', '옆', '옇', '예', '옛', '오', '옥', '온', '올', '옮', '옳', '옴', '옵', '옷', '와', '완', '왓', '왔', '왕', '왜', '왠', '왤', '외', '왼', '욌', '요', '욕', '욜', '용', '우', '욱', '운', '울', '움', '웁', '웃', '워', '원', '월', '웠', '웨', '웬', '웹', '웽', '위', '윗', '윙', '유', '육', '윤', '율', '으', '은', '을', '음', '응', '의', '이', '익', '인', '일', '읽', '잃', '임', '입', '잇', '있', '잊', '잌', '자', '작', '잔', '잖', '잘', '잠', '잡', '잤', '장', '잦', '재', '잼', '잿', '쟁', '저', '적', '전', '절', '젊', '점', '접', '젔', '정', '젖', '제', '젝', '젠', '젤', '젯', '져', '젹', '졋', '졌', '조', '족', '존', '졸', '좀', '좁', '종', '좋', '좌', '죄', '죠', '주', '죽', '준', '줄', '줌', '줍', '중', '줘', '줬', '쥐', '쥬', '즈', '즉', '즐', '즘', '즙', '증', '지', '직', '진', '질', '짐', '집', '짓', '징', '짚', '짜', '짝', '짠', '짤', '짧', '짬', '짰', '짱', '째', '짼', '쨌', '쩌', '쩍', '쩐', '쩔', '쩝', '쩡', '쪄', '쪘', '쪼', '쪽', '쫄', '쫌', '쫙', '쭈', '쭉', '쭤', '쯤', '찌', '찍', '찐', '찔', '찜', '찝', '찡', '찢', '차', '착', '찬', '찮', '찰', '참', '찹', '찼', '창', '찾', '채', '책', '챔', '챗', '챘', '챙', '처', '척', '천', '철', '첨', '첩', '첫', '청', '체', '쳇', '쳐', '쳤', '초', '촉', '촌', '총', '촬', '최', '추', '축', '춘', '출', '춤', '춥', '충', '춰', '췄', '취', '츄', '츠', '측', '츤', '층', '치', '칙', '친', '칠', '침', '칩', '칫', '칭', '카', '칼', '캄', '캐', '캔', '캬', '커', '컥', '컨', '컴', '컷', '컸', '컹', '케', '켓', '켜', '켠', '켰', '코', '콕', '콘', '콜', '콤', '콧', '콩', '쾌', '쿠', '쿨', '쿵', '쿼', '퀴', '큐', '크', '큰', '클', '큼', '킁', '키', '킥', '킨', '킬', '킴', '킹', '타', '탁', '탄', '탈', '탐', '탑', '탓', '탔', '탕', '태', '택', '탱', '터', '턱', '턴', '털', '텀', '텁', '텄', '텅', '테', '텍', '텐', '텔', '템', '텨', '텻', '텼', '토', '톡', '톤', '톱', '통', '퇴', '투', '툭', '툰', '툴', '툼', '퉁', '퉜', '튀', '튜', '트', '특', '틀', '틈', '틋', '티', '틱', '팀', '팁', '팅', '파', '팍', '판', '팔', '팠', '패', '팩', '팬', '팸', '퍼', '펑', '페', '펜', '펨', '펭', '펴', '편', '펼', '평', '폐', '포', '폭', '폰', '폼', '퐈', '표', '푸', '푹', '푼', '풀', '품', '풋', '풍', '퓨', '프', '픈', '플', '픔', '픕', '피', '픽', '핀', '필', '핍', '핏', '핑', '하', '학', '한', '할', '함', '합', '핫', '항', '해', '핸', '햇', '했', '행', '햐', '향', '허', '헉', '헌', '헐', '험', '헛', '헤', '헥', '헬', '헷', '헹', '혀', '현', '혈', '혐', '협', '혔', '형', '혜', '호', '혹', '혼', '홀', '홈', '화', '확', '환', '활', '홧', '황', '회', '획', '효', '후', '훅', '훈', '훌', '훔', '훨', '휘', '휙', '휨', '휴', '흐', '흑', '흔', '흘', '흠', '흡', '흥', '희', '흰', '히', '힌', '힐', '힘', '힙']
###Markdown
2. Dataset, DataLoader
###Code
class QnADataset(Dataset):
def __init__(self, data_path, vocab_path):
super().__init__()
self.char2index, self.index2char = self._read_vocab(vocab_path)
self.data = self._preprocess(data_path)
def _read_vocab(self, vocab_path):
with open(vocab_path, encoding="utf-8") as f:
labels = json.load(f)
char2index = dict()
index2char = dict()
for index, char in enumerate(labels):
char2index[char] = index
index2char[index] = char
return char2index, index2char
def _preprocess(self, data_path):
data = []
with open(data_path, encoding="utf-8") as f:
for line in f:
sents = line.strip().split('\t')
assert len(sents) == 2, "data error!!"
question_sent, answer_sent = sents[0], sents[1]
data.append((question_sent, answer_sent))
return data
@property
def vocab_size(self):
return len(self.char2index)
def __len__(self):
return len(self.data)
def __getitem__(self, index):
qna = self.data[index]
q_sent, a_sent = qna[0], qna[1]
src = [self.char2index.get(SOS_TOKEN)]
src += [self.char2index.get(token, UNK_TOKEN_ID) for token in q_sent]
src += [self.char2index.get(EOS_TOKEN)]
tgt = [self.char2index.get(SOS_TOKEN)]
tgt += [self.char2index.get(token, UNK_TOKEN_ID) for token in a_sent]
tgt += [self.char2index.get(EOS_TOKEN)]
return torch.LongTensor(src), torch.LongTensor(tgt)
def text_collate_fn(batch):
xs = [x for x, y in batch]
xs_pad = torch.nn.utils.rnn.pad_sequence(xs, batch_first=True, padding_value=PAD_TOKEN_ID)
xs_lengths = [x.size(0) for x, y in batch]
xs_lengths = torch.LongTensor(xs_lengths)
ys = [y for x, y in batch]
ys_pad = torch.nn.utils.rnn.pad_sequence(ys, batch_first=True, padding_value=PAD_TOKEN_ID)
ys_lengths = [y.size(0) for x, y in batch]
ys_lengths = torch.LongTensor(ys_lengths)
return xs_pad, xs_lengths, ys_pad, ys_lengths
train_dataset = QnADataset(data_path="./data/train_chatbot.txt",
vocab_path="./vocab.json")
valid_dataset = QnADataset(data_path="./data/valid_chatbot.txt",
vocab_path="./vocab.json")
# train_dataset[0]
batch_size = 32 # 4
train_loader = DataLoader(dataset=train_dataset,
batch_size=batch_size,
shuffle=True,
collate_fn=text_collate_fn,
drop_last=False)
valid_loader = DataLoader(dataset=valid_dataset,
batch_size=batch_size,
shuffle=False,
collate_fn=text_collate_fn,
drop_last=False)
for x, x_len, y, y_len in train_loader:
print(x, y)
print(x_len, y_len)
break
###Output
tensor([[ 2, 69, 936, ..., 0, 0, 0],
[ 2, 779, 478, ..., 0, 0, 0],
[ 2, 822, 444, ..., 0, 0, 0],
...,
[ 2, 205, 465, ..., 0, 0, 0],
[ 2, 1195, 773, ..., 0, 0, 0],
[ 2, 805, 268, ..., 0, 0, 0]]) tensor([[ 2, 932, 707, ..., 0, 0, 0],
[ 2, 704, 773, ..., 0, 0, 0],
[ 2, 648, 444, ..., 0, 0, 0],
...,
[ 2, 647, 908, ..., 0, 0, 0],
[ 2, 1195, 773, ..., 825, 10, 3],
[ 2, 129, 480, ..., 0, 0, 0]])
tensor([14, 14, 15, 15, 15, 12, 11, 14, 9, 11, 10, 8, 10, 16, 13, 40, 17, 13,
24, 11, 11, 4, 13, 8, 16, 35, 27, 20, 17, 19, 11, 12]) tensor([20, 18, 17, 10, 21, 17, 14, 24, 10, 13, 15, 14, 15, 12, 24, 20, 13, 22,
25, 12, 15, 13, 14, 24, 11, 22, 21, 30, 15, 10, 32, 19])
###Markdown
3. Seq2Seq Model 3-1. Encoder - src = [batch size. src len]- embedded = [batch size, src len, emb dim]- outputs = [batch size, src len, hid dim * n directions]- hidden = [batch size, n layers * n directions, hid dim]- cell = [batch size, n layers * n directions, hid dim]- outputs are always from the top hidden layer
###Code
class Encoder(nn.Module):
def __init__(self, input_dim, emb_dim, hid_dim, n_layers, dropout):
super().__init__()
self.hid_dim = hid_dim
self.n_layers = n_layers
self.embedding = nn.Embedding(input_dim, emb_dim)
self.rnn = nn.LSTM(emb_dim, hid_dim, n_layers, dropout=dropout, batch_first=True) # batch_first=True
self.dropout = nn.Dropout(dropout)
def forward(self, src):
embedded = self.dropout(self.embedding(src))
outputs, (hidden, cell) = self.rnn(embedded)
return hidden, cell
###Output
_____no_output_____
###Markdown
3-2. Decoder - input = [batch size]- hidden = [batch size, n layers * n directions, hid dim]- cell = [batch size, n layers * n directions, hid dim] - n directions in the decoder will both always be 1, therefore:- hidden = [batch size, n layers, hid dim]- context = [batch size, n layers, hid dim]- input = [batch size, 1]- embedded = [batch size, 1, emb dim]- prediction = [batch size, output dim]- output = [batch size, seq len, hid dim * n directions]- hidden = [batch size, n layers * n directions, hid dim]- cell = [batch size, n layers * n directions, hid dim] - seq len and n directions will always be 1 in the decoder, therefore:- output = [batch size, 1, hid dim]- hidden = [batch size, n layers, hid dim]- cell = [batch size, n layers, hid dim]
###Code
class Decoder(nn.Module):
def __init__(self, output_dim, emb_dim, hid_dim, n_layers, dropout):
super().__init__()
self.output_dim = output_dim
self.hid_dim = hid_dim
self.n_layers = n_layers
self.embedding = nn.Embedding(output_dim, emb_dim)
self.rnn = nn.LSTM(emb_dim, hid_dim, n_layers, dropout=dropout, batch_first=True) # batch_first=True
self.fc_out = nn.Linear(hid_dim, output_dim)
self.dropout = nn.Dropout(dropout)
def forward(self, input, hidden, cell):
input = input.unsqueeze(1)
embedded = self.dropout(self.embedding(input))
output, (hidden, cell) = self.rnn(embedded, (hidden, cell))
prediction = self.fc_out(output.squeeze(1))
return prediction, hidden, cell
###Output
_____no_output_____
###Markdown
3-3. Seq2Seq - src = [batch size, src len]- trg = [batch size, trg len]- teacher_forcing_ratio is probability to use teacher forcing- e.g. if teacher_forcing_ratio is 0.75 we use ground-truth inputs 75% of the time- tensor to store decoder outputs- last hidden state of the encoder is used as the initial hidden state of the decoder- first input to the decoder is the `` tokens- insert input token embedding, previous hidden and previous cell states- receive output tensor (predictions) and new hidden and cell states- place predictions in a tensor holding predictions for each token- decide if we are going to use teacher forcing or not- get the highest predicted token from our predictions- if teacher forcing, use actual next token as next input- if not, use predicted token
###Code
class Seq2Seq(nn.Module):
def __init__(self, encoder, decoder, device):
super().__init__()
self.encoder = encoder
self.decoder = decoder
self.device = device
assert encoder.hid_dim == decoder.hid_dim, \
"Hidden dimensions of encoder and decoder mu st be equal!"
assert encoder.n_layers == decoder.n_layers, \
"Encoder and decoder must have equal number of layers!"
def forward(self, src, trg, teacher_forcing_ratio=0.5):
batch_size = trg.shape[0]
trg_len = trg.shape[1]
trg_vocab_size = self.decoder.output_dim
outputs = torch.zeros(batch_size, trg_len, trg_vocab_size)
outputs = outputs.transpose(1, 0).to(self.device)
hidden, cell = self.encoder(src)
input = trg[:, 0]
for t in range(1, trg_len):
output, hidden, cell = self.decoder(input, hidden, cell)
outputs[t] = output
teacher_force = random.random() < teacher_forcing_ratio
top1 = output.argmax(1)
input = trg[:, t] if teacher_force else top1
return outputs.transpose(1, 0)
INPUT_DIM = train_dataset.vocab_size
OUTPUT_DIM = train_dataset.vocab_size
ENC_EMB_DIM = 256
DEC_EMB_DIM = 256
HID_DIM = 512
N_LAYERS = 2
ENC_DROPOUT = 0.5
DEC_DROPOUT = 0.5
enc = Encoder(INPUT_DIM, ENC_EMB_DIM, HID_DIM, N_LAYERS, ENC_DROPOUT)
dec = Decoder(OUTPUT_DIM, DEC_EMB_DIM, HID_DIM, N_LAYERS, DEC_DROPOUT)
model = Seq2Seq(enc, dec, device).to(device)
print(model)
###Output
Seq2Seq(
(encoder): Encoder(
(embedding): Embedding(1246, 256)
(rnn): LSTM(256, 512, num_layers=2, batch_first=True, dropout=0.5)
(dropout): Dropout(p=0.5, inplace=False)
)
(decoder): Decoder(
(embedding): Embedding(1246, 256)
(rnn): LSTM(256, 512, num_layers=2, batch_first=True, dropout=0.5)
(fc_out): Linear(in_features=512, out_features=1246, bias=True)
(dropout): Dropout(p=0.5, inplace=False)
)
)
###Markdown
4. Train - trg = [batch size, trg len]- output = [batch size, trg len, output dim]- trg = [(trg len - 1) * batch size]- output = [(trg len - 1) * batch size, output dim]- trg = [batch size, trg len]- output = [batch size, trg len, output dim]
###Code
learning_rate = 0.001
optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate, weight_decay=1e-5)
lr_scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.5, patience=1, verbose=True)
criterion = nn.CrossEntropyLoss(reduction='mean', ignore_index=PAD_TOKEN_ID).to(device)
def train(model, data_loader, optimizer, criterion, clip, epoch):
model.train()
epoch_loss = 0
for i, batch in enumerate(data_loader):
src, src_len, trg, trg_len = batch
src = src.to(device)
trg = trg.to(device)
optimizer.zero_grad()
output = model(src, trg)
output_dim = output.shape[-1]
output = output[1:].view(-1, output_dim)
trg = trg[1:].view(-1)
loss = criterion(output, trg)
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), clip)
optimizer.step()
epoch_loss += loss.item()
log_interval = 100
if i % log_interval == 0 and i >= 0:
print('| epoch {:3d} | {:5d}/{:5d} batches | loss {:.4f}'.format(epoch+1, i+1, len(data_loader), loss.detach().item()))
return epoch_loss / len(data_loader)
###Output
_____no_output_____
###Markdown
- trg = [batch size, trg len]- output = [batch size, trg len, output dim]- trg = [(trg len - 1) * batch size]- output = [(trg len - 1) * batch size, output dim]
###Code
def evaluate(model, data_loader, criterion):
model.eval()
epoch_loss = 0
with torch.no_grad():
for i, batch in enumerate(data_loader):
src, src_len, trg, trg_len = batch
src = src.to(device)
trg = trg.to(device)
output = model(src, trg, 0)
output_dim = output.shape[-1]
output = output[1:].view(-1, output_dim)
trg = trg[1:].view(-1)
loss = criterion(output, trg)
epoch_loss += loss.item()
return epoch_loss / len(data_loader)
def epoch_time(start_time, end_time):
elapsed_time = end_time - start_time
elapsed_mins = int(elapsed_time / 60)
elapsed_secs = int(elapsed_time - (elapsed_mins * 60))
return elapsed_mins, elapsed_secs
N_EPOCHS = 25
CLIP = 5
best_train_loss = float('inf')
best_valid_loss = float('inf')
for epoch in range(N_EPOCHS):
start_time = time.time()
train_loss = train(model, train_loader, optimizer, criterion, CLIP, epoch)
valid_loss = evaluate(model, valid_loader, criterion)
end_time = time.time()
epoch_mins, epoch_secs = epoch_time(start_time, end_time)
if train_loss < best_train_loss:
best_train_loss = train_loss
torch.save(model.state_dict(), './models/s2s/train.loss.best.pt')
print(f'Epoch: {epoch+1:02} | train.loss.best: {epoch+1}')
if valid_loss < best_valid_loss:
best_valid_loss = valid_loss
torch.save(model.state_dict(), './models/s2s/valid.loss.best.pt')
print(f'Epoch: {epoch+1:02} | valid.loss.best: {epoch+1}')
lr_scheduler.step(valid_loss)
print(f'Epoch: {epoch+1:02} | Time: {epoch_mins}m {epoch_secs}s')
print(f'\tTrain Loss: {train_loss:.4f} | Train PPL: {math.exp(train_loss):8.4f}')
print(f'\t Val. Loss: {valid_loss:.4f} | Val. PPL: {math.exp(valid_loss):8.4f}')
print("#"*100)
model.load_state_dict(torch.load('./models/s2s/train.loss.best.pt'))
test_loss = evaluate(model, valid_loader, criterion)
print(f'| Test Loss: {test_loss:.4f} | Test PPL: {math.exp(test_loss):8.4f} |')
###Output
| Test Loss: 4.5272 | Test PPL: 92.5031 |
###Markdown
5. Inference
###Code
def inference(model, q_sent="", a_sent=None, char2index=None, index2char=None):
model.eval()
with torch.no_grad():
src = [char2index.get(SOS_TOKEN)]
src += [char2index.get(token, UNK_TOKEN_ID) for token in q_sent]
src += [char2index.get(EOS_TOKEN)]
trg = [char2index.get(SOS_TOKEN)]
trg += [char2index.get(token, UNK_TOKEN_ID) for token in a_sent]
trg += [char2index.get(EOS_TOKEN)]
src = torch.LongTensor([src]).to(device)
trg = torch.LongTensor([trg]).to(device)
hyp_ys = model(src, trg, 1)
pred = torch.argmax(hyp_ys[0], dim=-1).detach().cpu().numpy()
pred_sent = [index2char[token_id] for token_id in pred[1:]]
pred_sent = ''.join(pred_sent)
print(pred_sent)
idx = np.random.randint(len(train_dataset), size=1)[0]
print("random idx : ", idx)
q_sent = train_dataset.data[idx][0]
a_sent = train_dataset.data[idx][1]
print("Q: ", q_sent)
print("A: ", a_sent)
inference(model, q_sent, a_sent, char2index=train_dataset.char2index, index2char=train_dataset.index2char)
###Output
random idx : 2732
Q: 사랑이 밥 먹여주나
A: 사랑이 밥은 먹여주지 않지만 행복을 줘요.
그랑 사어 세 않아 좋복해 해보.<eos>
|
scripts/archives/david_clean.ipynb | ###Markdown
pull discovery data into pandas
###Code
wt_disc_df = pd.read_excel('../Clinical_Data/TARGET_WT_ClinicalData_Discovery_20160714_public.xlsx')
aml_disc_df = pd.read_excel('../Clinical_Data/TARGET_AML_ClinicalData_20160714.xlsx')
nbl_disc_df = pd.read_excel('../Clinical_Data/TARGET_NBL_ClinicalData_20151124.xlsx')
WT_df = manifest_clinical_merge(manifest_df, wt_disc_df, 'TARGET-WT')
AML_df = manifest_clinical_merge(manifest_df, aml_disc_df, 'TARGET-AML')
NBL_df = manifest_clinical_merge(manifest_df, nbl_disc_df, 'TARGET-NBL')
WT_df.head()
pd.crosstab(WT_df['TARGET USI'][:16], WT_df['Histology Classification of Primary Tumor'])
pd.crosstab(WT_df['TARGET USI'][:16], WT_df['Stage'])
pd.crosstab(WT_df['TARGET USI'][:16], WT_df['Histology Classification of Primary Tumor'])
AML_df.head()
NBL_df.head()
NBL_df['Histology'].value_counts()
NBL_df['MKI'].value_counts()
NBL_df['Ethnicity'].value_counts()
NBL_df['MYCN status'].value_counts()
NBL_df['Grade'].value_counts()
manifest_df['project.project_id'].value_counts()
AML_df.to_csv('../Clinical_Data/AML_dataframe.csv')
NBL_df.to_csv('../Clinical_Data/NBL_dataframe.csv')
WT_df.to_csv('../Clinical_Data/WT_dataframe.csv')
###Output
_____no_output_____
###Markdown
TARGET_NBL_AML_...etc
###Code
assay_df = pd.read_csv('../TARGET_NBL_AML_RT_WT_HTSeq_Counts.csv')
assay_df.info()
assay_df.head()
assay_df.describe()
assay_df.head()
AML_df.head()
AML_df['TARGET USI'] = AML_df['TARGET USI'].apply(lambda x: x.replace('-', '.'))
###Output
_____no_output_____
###Markdown
now consistent with set up with assay_df
###Code
AML_df.head()
assay_df.head()
assay_pt_df = assay_df.T
assay_pt_df.head()
list(assay_pt_df.index)[0]
assay_pt_df['TARGET USI'] = list(assay_pt_df.index)
assay_pt_df['TARGET USI'] = assay_pt_df['TARGET USI'].apply(lambda x: x[0:16])
assay_pt_df['2nd ID'] = list(assay_pt_df.index)
assay_pt_df['2nd ID'] = assay_pt_df['2nd ID'].apply(lambda x: x[16:])
# assay_pt_df.columns = assay_pt_df.iloc[0]
assay_pt_df.loc['Genes', 'TARGET USI'] = 'TARGET USI'
assay_pt_df.loc['Genes', '2nd ID'] = '2nd ID'
assay_pt_df.head()
# assay_pt_df = assay_pt_df.iloc[1:]
AML_genes = AML_df.merge(assay_pt_df, how='left', on='TARGET USI')
AML_genes.head(20)
###Output
_____no_output_____
###Markdown
MERGE TEST
###Code
WT_df = manifest_clinical_merge(manifest_df, wt_disc_df, 'TARGET-WT')
AML_df = manifest_clinical_merge(manifest_df, aml_disc_df, 'TARGET-AML')
NBL_df = manifest_clinical_merge(manifest_df, nbl_disc_df, 'TARGET-NBL')
len(AML_df['entity_submitter_id'].unique())
from clean import assay_transpose
assay_df = pd.read_csv('../TARGET_NBL_AML_RT_WT_TMMCPM_log2_Norm_Counts.csv')
assay_t_df = assay_transpose(assay_df)
AML_df.head()
assay_t_df.head()
from clean import assay_clinical_merge
AML_genes = assay_clinical_merge(assay_t_df, AML_df)
AML_genes.info()
from model_comp import data_prep_columns
data_prep_columns(AML_genes, 'Max')
###Output
_____no_output_____ |
experiments/interaction/experiment_171201_1700-alpha_loss-best.ipynb | ###Markdown
Predictions
###Code
pred_df.describe()
_ = plt.hist2d(pred_df['ant1_x'], pred_df['ant1_y'], bins=40, range=((0, 199), (0, 199)))
_ = plt.hist2d(pred_df['ant2_x'], pred_df['ant2_y'], bins=40, range=((0, 199), (0, 199)))
pred_df['ant1_angle'].hist()
(pred_df['ant1_angle'] % 180).hist()
pred_df['ant2_angle'].hist()
(pred_df['ant2_angle'] % 180).hist()
###Output
_____no_output_____
###Markdown
Prediction Errors
###Code
# xy1_error = np.linalg.norm(toarray(y_test[['ant1_x', 'ant1_y']]) - toarray(pred[['ant1_x', 'ant1_y']]), 2, axis=1)
# xy2_error = np.linalg.norm(toarray(y_test[['ant2_x', 'ant2_y']]) - toarray(pred[['ant2_x', 'ant2_y']]), 2, axis=1)
# angle1_error, angle2_error = train_interactions.angle_absolute_error(toarray(y_test), toarray(pred), np)
# xy1_error_df = pd.DataFrame(xy1_error)
# xy2_error_df = pd.DataFrame(xy2_error)
# angle1_error_df = pd.DataFrame(angle1_error)
# angle2_error_df = pd.DataFrame(angle2_error)
# xy, angle, indices = train_interactions.match_pred_to_gt(pred, y_test, np)
# xy_errors = (xy[indices[:, 0], indices[:, 1]])
# angle_errors = (angle[indices[:, 0], indices[:, 1]])
# swap = indices[:, 0] == 1
# pred[swap, :5], pred[swap, 5:] = pred[swap, 5:], pred[swap, :5]
xy, angle, indices = train_interactions.match_pred_to_gt(pred, y_test, np)
xy_errors = (xy[indices[:, 0], indices[:, 1]])
angle_errors = (angle[indices[:, 0], indices[:, 1]])
# swap = indices[:, 0] == 1
# pred_swapped = pred.copy()
# pred_swapped[swap, :5], pred_swapped[swap, 5:] = pred_swapped[swap, 5:], pred_swapped[swap, :5]
df = pd.DataFrame.from_items([('xy (px)', [xy_errors.mean()]),
('angle (deg)', angle_errors.mean()),])
df.style.set_caption('MAE')
df
_ = plt.hist(xy_errors)
_ = plt.hist(angle_errors)
###Output
_____no_output_____
###Markdown
Model
###Code
from IPython.display import SVG
from keras.utils.vis_utils import model_to_dot
model = train_interactions.model()
SVG(model_to_dot(model, show_shapes=True).create(prog='dot', format='svg'))
# SVG(model_to_dot(model.get_layer('model_1'), show_shapes=True).create(prog='dot', format='svg'))
###Output
_____no_output_____ |
app/notebooks/labeling_shot_boundaries.ipynb | ###Markdown
Table of Contents **Imports and Setup. The initialization cell below should run automatically and print out "Done with initialization!"**
###Code
from esper.prelude import *
import numpy as np
from IPython.display import display, clear_output
import ipywidgets as widgets
import datetime
from rekall.interval_list import IntervalList
from rekall.temporal_predicates import overlaps, overlaps_before
from query.models import Labeler, Shot
try:
VIDEO
except NameError:
VIDEO = None
STARTING_FRAME = None
ENDING_FRAME = None
ESPER_WIDGET = None
SELECTED_HARD_CUTS = []
SELECTED_TRANSITION_FRAMES = []
def choose_random_segment():
video = Video.objects.filter(ignore_film=False).order_by('?')[0]
five_minutes = int(60 * 5 * video.fps)
one_minute = int(60 * video.fps)
starting_frame = np.random.randint(
five_minutes, video.num_frames - 2 * five_minutes)
global VIDEO, STARTING_FRAME, ENDING_FRAME
VIDEO = video
STARTING_FRAME = starting_frame
ENDING_FRAME = STARTING_FRAME + one_minute - 1
print('Selected film {} ({}), frames {}-{}'.format(
video.title, video.year, STARTING_FRAME, ENDING_FRAME))
# replaces qs_to_result
def frame_result(video_id, frame_nums):
materialized_result = []
for frame_num in frame_nums:
materialized_result.append({
'video': video_id,
'min_frame': frame_num,
'objects': []
})
return {'type': 'frames', 'count': 0, 'result': [{
'type': 'flat', 'label': '', 'elements': [mr]
} for mr in materialized_result]}
def cache_labels(b):
global SELECTED_HARD_CUTS, SELECTED_TRANSITION_FRAMES
SELECTED_HARD_CUTS = ESPER_WIDGET.selected
SELECTED_TRANSITION_FRAMES = ESPER_WIDGET.ignored
print("Saved {}".format(datetime.datetime.now()))
def label_segment():
global VIDEO, ESPER_WIDGET, STARTING_FRAME, ENDING_FRAME
frames = frame_result(VIDEO.id, range(STARTING_FRAME, ENDING_FRAME + 1))
save = widgets.Button(
description='Save Progress',
disabled=False,
button_style='success',
tooltip='Save Progress'
)
ESPER_WIDGET = esper_widget(
frames,
show_paging_buttons=True,
jupyter_keybindings=True,
results_per_page=48,
thumbnail_size=0.75,
selected_cached=SELECTED_HARD_CUTS,
ignored_cached=SELECTED_TRANSITION_FRAMES,
max_width=965
)
display(ESPER_WIDGET)
display(save)
save.on_click(cache_labels)
def inspect_hard_cuts():
global SELECTED_HARD_CUTS, STARTING_FRAME
frame_nums = [f + STARTING_FRAME for f in SELECTED_HARD_CUTS]
frames = frame_result(VIDEO.id, frame_nums)
update = widgets.Button(
description='Update',
disabled=False,
button_style='success',
tooltip='Update'
)
esp = esper_widget(
frames,
show_paging_buttons=True,
jupyter_keybindings=True,
results_per_page=48,
thumbnail_size=0.75,
max_width=965,
selected_cached=[],
ignored_cached=[]
)
display(esp)
display(update)
def update_hard_cuts(b):
global SELECTED_HARD_CUTS
deselected_frames = [
frame_nums[i]
for i in esp.ignored
]
hard_cuts_to_remove = [
selection
for frame_num, selection in zip(frame_nums, SELECTED_HARD_CUTS)
if frame_num in deselected_frames
]
SELECTED_HARD_CUTS = [
cut for cut in SELECTED_HARD_CUTS
if cut not in hard_cuts_to_remove
]
clear_output()
inspect_hard_cuts()
update.on_click(update_hard_cuts)
def inspect_transitions():
global SELECTED_TRANSITION_FRAMES, STARTING_FRAME
frame_nums = [f + STARTING_FRAME for f in SELECTED_TRANSITION_FRAMES]
frames = frame_result(VIDEO.id, frame_nums)
update = widgets.Button(
description='Update',
disabled=False,
button_style='success',
tooltip='Update'
)
esp = esper_widget(
frames,
show_paging_buttons=True,
jupyter_keybindings=True,
results_per_page=48,
thumbnail_size=0.75,
max_width=965,
selected_cached=[],
ignored_cached=[]
)
display(esp)
display(update)
def update_transitions(b):
global SELECTED_TRANSITION_FRAMES
deselected_frames = [
frame_nums[i]
for i in esp.ignored
]
transition_frames_to_remove = [
selection
for frame_num, selection in zip(frame_nums, SELECTED_TRANSITION_FRAMES)
if frame_num in deselected_frames
]
SELECTED_TRANSITION_FRAMES = [
cut for cut in SELECTED_TRANSITION_FRAMES
if cut not in transition_frames_to_remove
]
clear_output()
inspect_transitions()
update.on_click(update_transitions)
def prepare_orm_objects():
global STARTING_FRAME, SELECTED_HARD_CUTS, SELECTED_TRANSITION_FRAMES, VIDEO
selected_shot_boundaries = [
STARTING_FRAME + idx for idx in SELECTED_HARD_CUTS]
transition_frames = IntervalList([
(STARTING_FRAME + f, STARTING_FRAME + F, 0)
for f in SELECTED_TRANSITION_FRAMES
]).dilate(1).coalesce().dilate(-1)
selected_shot_boundaries = sorted(selected_shot_boundaries + [
int((transition.end + transition.start) / 2)
for transition in transition_frames.get_intervals()
])
shots = []
for i in range(0, len(selected_shot_boundaries) - 1):
shots.append(
(selected_shot_boundaries[i], selected_shot_boundaries[i+1] - 1, {}))
shots_intrvllist = IntervalList(shots)
shots_with_transition_info = shots_intrvllist.join(
transition_frames,
predicate=overlaps(),
merge_op=lambda shot, transition: (
shot.start, shot.end,
{'transition_start_max_frame': transition.end}
if overlaps_before()(transition, shot) else
{'transition_end_min_frame': transition.start}
)
).set_union(
shots_intrvllist
).coalesce(payload_merge_op=lambda p1, p2: {**p1, **p2})
labeler_name = 'shot-manual-{}'.format(
datetime.datetime.now().strftime('%Y-%m-%d-%H:%M:%S')
)
new_labeler, _ = Labeler.objects.get_or_create(name=labeler_name)
print('Labeler created:', labeler_name)
new_shots = []
for intrvl in shots_with_transition_info.get_intervals():
new_shot = Shot(
min_frame=intrvl.start,
max_frame=intrvl.end,
video=VIDEO,
labeler=new_labeler
)
if 'transition_start_max_frame' in intrvl.payload:
new_shot.transition_in_max_frame = intrvl.payload['transition_start_max_frame']
if 'transition_end_min_frame' in intrvl.payload:
new_shot.transition_out_min_frame = intrvl.payload['transition_end_min_frame']
new_shots.append(new_shot)
return new_labeler, new_shots
def save_orm_objects(shots):
print('Saving shots...')
with transaction.atomic():
Shot.objects.bulk_create(shots)
print('Done!')
def reset_notebook_state():
global VIDEO, STARTING_FRAME, ENDING_FRAME, \
ESPER_WIDGET, SELECTED_HARD_CUTS, SELECTED_TRANSITION_FRAMES
VIDEO = None
STARTING_FRAME = None
ENDING_FRAME = None
ESPER_WIDGET = None
SELECTED_HARD_CUTS = []
SELECTED_TRANSITION_FRAMES = []
print('Done with initialization!')
###Output
_____no_output_____
###Markdown
Step 1: Run the cell below to pick a random five-minute segment from a film to label.
###Code
choose_random_segment()
###Output
_____no_output_____
###Markdown
Step 2: Run the cell below to show the labeling interface.For **hard cuts**, hover over the frame and use `[` to mark the first frame of the new shot.For **fades/wipes/etc**, use `]` to mark all the frames in the transition (hover over the frames and press `]`).You can hover over a frame and use `=` to expand the frame to inspect it closer, or `Shift-P` to play the film starting from that frame.You can click the Save button at any time to locally cache your labels - these will persist across refreshes, but not across kernel deaths.When you're ready to move on, click the Save button.
###Code
label_segment()
###Output
_____no_output_____
###Markdown
Step 3: Run the cell below to inspect your hard cut labels.Use `]` to **deselect** any frames that you'd like to remove from your labelling pass. If you'd like to add more frames, go back to the previous cell. Your previous work should be cached.
###Code
inspect_hard_cuts()
###Output
_____no_output_____
###Markdown
Step 4: Run the cell below to inspect your transition labels.Use `]` to **deselect** any frames that you'd like to remove from your labelling pass. If you'd like to add more frames, go back to Step 2. Your previous work should be cached
###Code
inspect_transitions()
###Output
_____no_output_____
###Markdown
Step 5: Run the two cells below to commit your labels to the database!
###Code
labeler, shots = prepare_orm_objects()
save_orm_objects(shots)
###Output
_____no_output_____
###Markdown
Step 6: Run the cell below to reset the notebook state and start over with a new segment from Step 1!
###Code
reset_notebook_state()
###Output
_____no_output_____ |
numpy-data-science-essential-training/Ex_Files_NumPy_Data_EssT/Exercise Files/Ch 4/04_02/Finish/.ipynb_checkpoints/Figures and Subplots-checkpoint.ipynb | ###Markdown
Figures and Subplots- figure - container thats holds all elements of plot(s)- subplot - appears within a rectangular grid within a figure
###Code
import numpy as np
import matplotlib.pyplot as plt
my_first_figure = plt.figure("My First Figure")
subplot_1 = my_first_figure.add_subplot(2, 3, 1)
subplot_6 = my_first_figure.add_subplot(2, 3, 6)
plt.plot(np.random.rand(50).cumsum(), 'k--')
plt.show()
subplot_2 = my_first_figure.add_subplot(2, 3, 2)
plt.plot(np.random.rand(50), 'go')
subplot_6
plt.show()
###Output
_____no_output_____ |
immersion/guided_projects/guided_project_3_nlp_starter/keras_for_text_classification.ipynb | ###Markdown
Keras for Text Classification**Learning Objectives**1. Learn how to create a text classification datasets using BigQuery1. Learn how to tokenize and integerize a corpus of text for training in Keras1. Learn how to do one-hot-encodings in Keras1. Learn how to use embedding layers to represent words in Keras1. Learn about the bag-of-word representation for sentences1. Learn how to use DNN/CNN/RNN model to classify text in keras IntroductionIn this notebook, we will implement text models to recognize the probable source (Github, Tech-Crunch, or The New-York Times) of the titles we have in the title dataset we constructed in the first task of the lab.In the next step, we will load and pre-process the texts and labels so that they are suitable to be fed to a Keras model. For the texts of the titles we will learn how to split them into a list of tokens, and then how to map each token to an integer using the Keras Tokenizer class. What will be fed to our Keras models will be batches of padded list of integers representing the text. For the labels, we will learn how to one-hot-encode each of the 3 classes into a 3 dimensional basis vector.Then we will explore a few possible models to do the title classification. All models will be fed padded list of integers, and all models will start with a Keras Embedding layer that transforms the integer representing the words into dense vectors.The first model will be a simple bag-of-word DNN model that averages up the word vectors and feeds the tensor that results to further dense layers. Doing so means that we forget the word order (and hence that we consider sentences as a “bag-of-words”). In the second and in the third model we will keep the information about the word order using a simple RNN and a simple CNN allowing us to achieve the same performance as with the DNN model but in much fewer epochs.
###Code
import os
from google.cloud import bigquery
import pandas as pd
%load_ext google.cloud.bigquery
###Output
_____no_output_____
###Markdown
Replace the variable values in the cell below:
###Code
PROJECT = "qwiklabs-gcp-04-14242c0aa6a7" # Replace with your PROJECT
BUCKET = PROJECT # defaults to PROJECT
REGION = "us-central1" # Replace with your REGION
SEED = 0
###Output
_____no_output_____
###Markdown
Create a Dataset from BigQuery Hacker news headlines are available as a BigQuery public dataset. The [dataset](https://bigquery.cloud.google.com/table/bigquery-public-data:hacker_news.stories?tab=details) contains all headlines from the sites inception in October 2006 until October 2015. Here is a sample of the dataset:
###Code
%%bigquery --project $PROJECT
SELECT
url, title, score
FROM
`bigquery-public-data.hacker_news.stories`
WHERE
LENGTH(title) > 10
AND score > 10
AND LENGTH(url) > 0
LIMIT 10
###Output
_____no_output_____
###Markdown
Let's do some regular expression parsing in BigQuery to get the source of the newspaper article from the URL. For example, if the url is http://mobile.nytimes.com/...., I want to be left with nytimes
###Code
%%bigquery --project $PROJECT
SELECT
ARRAY_REVERSE(SPLIT(REGEXP_EXTRACT(url, '.*://(.[^/]+)/'), '.'))[OFFSET(1)] AS source,
COUNT(title) AS num_articles
FROM
`bigquery-public-data.hacker_news.stories`
WHERE
REGEXP_CONTAINS(REGEXP_EXTRACT(url, '.*://(.[^/]+)/'), '.com$')
AND LENGTH(title) > 10
GROUP BY
source
ORDER BY num_articles DESC
LIMIT 100
###Output
_____no_output_____
###Markdown
Now that we have good parsing of the URL to get the source, let's put together a dataset of source and titles. This will be our labeled dataset for machine learning.
###Code
regex = '.*://(.[^/]+)/'
sub_query = """
SELECT
title,
ARRAY_REVERSE(SPLIT(REGEXP_EXTRACT(url, '{0}'), '.'))[OFFSET(1)] AS source
FROM
`bigquery-public-data.hacker_news.stories`
WHERE
REGEXP_CONTAINS(REGEXP_EXTRACT(url, '{0}'), '.com$')
AND LENGTH(title) > 10
""".format(regex)
query = """
SELECT
LOWER(REGEXP_REPLACE(title, '[^a-zA-Z0-9 $.-]', ' ')) AS title,
source
FROM
({sub_query})
WHERE (source = 'github' OR source = 'nytimes' OR source = 'techcrunch')
""".format(sub_query=sub_query)
print(query)
###Output
_____no_output_____
###Markdown
For ML training, we usually need to split our dataset into training and evaluation datasets (and perhaps an independent test dataset if we are going to do model or feature selection based on the evaluation dataset). AutoML however figures out on its own how to create these splits, so we won't need to do that here.
###Code
bq = bigquery.Client(project=PROJECT)
title_dataset = bq.query(query).to_dataframe()
title_dataset.head()
###Output
_____no_output_____
###Markdown
AutoML for text classification requires that* the dataset be in csv form with * the first column being the texts to classify or a GCS path to the text * the last colum to be the text labelsThe dataset we pulled from BiqQuery satisfies these requirements.
###Code
print("The full dataset contains {n} titles".format(n=len(title_dataset)))
###Output
_____no_output_____
###Markdown
Let's make sure we have roughly the same number of labels for each of our three labels:
###Code
title_dataset.source.value_counts()
###Output
_____no_output_____
###Markdown
Finally we will save our data, which is currently in-memory, to disk.We will create a csv file containing the full dataset and another containing only 1000 articles for development.**Note:** It may take a long time to train AutoML on the full dataset, so we recommend to use the sample dataset for the purpose of learning the tool.
###Code
DATADIR = './data/'
if not os.path.exists(DATADIR):
os.makedirs(DATADIR)
FULL_DATASET_NAME = 'titles_full.csv'
FULL_DATASET_PATH = os.path.join(DATADIR, FULL_DATASET_NAME)
# Let's shuffle the data before writing it to disk.
title_dataset = title_dataset.sample(n=len(title_dataset))
title_dataset.to_csv(
FULL_DATASET_PATH, header=False, index=False, encoding='utf-8')
###Output
_____no_output_____
###Markdown
Now let's sample 1000 articles from the full dataset and make sure we have enough examples for each label in our sample dataset (see [here](https://cloud.google.com/natural-language/automl/docs/beginners-guide) for further details on how to prepare data for AutoML).
###Code
sample_title_dataset = title_dataset.sample(n=1000)
sample_title_dataset.source.value_counts()
###Output
_____no_output_____
###Markdown
Let's write the sample datatset to disk.
###Code
SAMPLE_DATASET_NAME = 'titles_sample.csv'
SAMPLE_DATASET_PATH = os.path.join(DATADIR, SAMPLE_DATASET_NAME)
sample_title_dataset.to_csv(
SAMPLE_DATASET_PATH, header=False, index=False, encoding='utf-8')
sample_title_dataset.head()
import os
import shutil
import pandas as pd
import tensorflow as tf
from tensorflow.keras.callbacks import TensorBoard, EarlyStopping
from tensorflow.keras.layers import (
Embedding,
Flatten,
GRU,
Conv1D,
Lambda,
Dense,
)
from tensorflow.keras.models import Sequential
from tensorflow.keras.preprocessing.sequence import pad_sequences
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras.utils import to_categorical
print(tf.__version__)
%matplotlib inline
###Output
_____no_output_____
###Markdown
Let's start by specifying where the information about the trained models will be saved as well as where our dataset is located:
###Code
LOGDIR = "./text_models"
DATA_DIR = "./data"
###Output
_____no_output_____
###Markdown
Loading the dataset Our dataset consists of titles of articles along with the label indicating from which source these articles have been taken from (GitHub, Tech-Crunch, or the New-York Times).
###Code
DATASET_NAME = "titles_full.csv"
TITLE_SAMPLE_PATH = os.path.join(DATA_DIR, DATASET_NAME)
COLUMNS = ['title', 'source']
titles_df = pd.read_csv(TITLE_SAMPLE_PATH, header=None, names=COLUMNS)
titles_df.head()
###Output
_____no_output_____
###Markdown
Integerize the texts The first thing we need to do is to find how many words we have in our dataset (`VOCAB_SIZE`), how many titles we have (`DATASET_SIZE`), and what the maximum length of the titles we have (`MAX_LEN`) is. Keras offers the `Tokenizer` class in its `keras.preprocessing.text` module to help us with that:
###Code
tokenizer = Tokenizer()
tokenizer.fit_on_texts(titles_df.title)
integerized_titles = tokenizer.texts_to_sequences(titles_df.title)
integerized_titles[:3]
VOCAB_SIZE = len(tokenizer.index_word)
VOCAB_SIZE
DATASET_SIZE = tokenizer.document_count
DATASET_SIZE
MAX_LEN = max(len(sequence) for sequence in integerized_titles)
MAX_LEN
###Output
_____no_output_____
###Markdown
Let's now implement a function `create_sequence` that will * take as input our titles as well as the maximum sentence length and * returns a list of the integers corresponding to our tokens padded to the sentence maximum lengthKeras has the helper functions `pad_sequence` for that on the top of the tokenizer methods.
###Code
# TODO 1
def create_sequences(texts, max_len=MAX_LEN):
sequences = tokenizer.texts_to_sequences(texts)
padded_sequences = pad_sequences(sequences, max_len, padding='post')
return padded_sequences
sequences = create_sequences(titles_df.title[:3])
sequences
titles_df.source[:4]
###Output
_____no_output_____
###Markdown
We now need to write a function that * takes a title source and* returns the corresponding one-hot encoded vectorKeras `to_categorical` is handy for that.
###Code
CLASSES = {
'github': 0,
'nytimes': 1,
'techcrunch': 2
}
N_CLASSES = len(CLASSES)
# TODO 2
def encode_labels(sources):
classes = [CLASSES[source] for source in sources]
one_hots = to_categorical(classes)
return one_hots
encode_labels(titles_df.source[:4])
###Output
_____no_output_____
###Markdown
Preparing the train/test splits Let's split our data into train and test splits:
###Code
N_TRAIN = int(DATASET_SIZE * 0.80)
titles_train, sources_train = (
titles_df.title[:N_TRAIN], titles_df.source[:N_TRAIN])
titles_valid, sources_valid = (
titles_df.title[N_TRAIN:], titles_df.source[N_TRAIN:])
###Output
_____no_output_____
###Markdown
To be on the safe side, we verify that the train and test splitshave roughly the same number of examples per classes.Since it is the case, accuracy will be a good metric to use to measurethe performance of our models.
###Code
sources_train.value_counts()
sources_valid.value_counts()
###Output
_____no_output_____
###Markdown
Using `create_sequence` and `encode_labels`, we can now prepare thetraining and validation data to feed our models.The features will bepadded list of integers and the labels will be one-hot-encoded 3D vectors.
###Code
X_train, Y_train = create_sequences(titles_train), encode_labels(sources_train)
X_valid, Y_valid = create_sequences(titles_valid), encode_labels(sources_valid)
X_train[:3]
Y_train[:3]
###Output
_____no_output_____
###Markdown
Building a DNN model The build_dnn_model function below returns a compiled Keras model that implements a simple embedding layer transforming the word integers into dense vectors, followed by a Dense softmax layer that returns the probabilities for each class.Note that we need to put a custom Keras Lambda layer in between the Embedding layer and the Dense softmax layer to do an average of the word vectors returned by the embedding layer. This is the average that's fed to the dense softmax layer. By doing so, we create a model that is simple but that loses information about the word order, creating a model that sees sentences as "bag-of-words".
###Code
def build_dnn_model(embed_dim):
model = Sequential([
Embedding(VOCAB_SIZE + 1, embed_dim, input_shape=[MAX_LEN]), # TODO 3
Lambda(lambda x: tf.reduce_mean(x, axis=1)), # TODO 4
Dense(N_CLASSES, activation='softmax') # TODO 5
])
model.compile(
optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy']
)
return model
###Output
_____no_output_____
###Markdown
Below we train the model on 100 epochs but adding an `EarlyStopping` callback that will stop the training as soon as the validation loss has not improved after a number of steps specified by `PATIENCE` . Note that we also give the `model.fit` method a Tensorboard callback so that we can later compare all the models using TensorBoard.
###Code
%%time
tf.random.set_seed(33)
MODEL_DIR = os.path.join(LOGDIR, 'dnn')
shutil.rmtree(MODEL_DIR, ignore_errors=True)
BATCH_SIZE = 300
EPOCHS = 100
EMBED_DIM = 10
PATIENCE = 0
dnn_model = build_dnn_model(embed_dim=EMBED_DIM)
dnn_history = dnn_model.fit(
X_train, Y_train,
epochs=EPOCHS,
batch_size=BATCH_SIZE,
validation_data=(X_valid, Y_valid),
callbacks=[EarlyStopping(patience=PATIENCE), TensorBoard(MODEL_DIR)],
)
pd.DataFrame(dnn_history.history)[['loss', 'val_loss']].plot()
pd.DataFrame(dnn_history.history)[['accuracy', 'val_accuracy']].plot()
dnn_model.summary()
###Output
_____no_output_____
###Markdown
Building a RNN model The `build_dnn_model` function below returns a compiled Keras model that implements a simple RNN model with a single `GRU` layer, which now takes into account the word order in the sentence.The first and last layers are the same as for the simple DNN model.Note that we set `mask_zero=True` in the `Embedding` layer so that the padded words (represented by a zero) are ignored by this and the subsequent layers.
###Code
def build_rnn_model(embed_dim, units):
model = Sequential([
Embedding(VOCAB_SIZE + 1, embed_dim, input_shape=[MAX_LEN], mask_zero=True), # TODO 3
GRU(units), # TODO 5
Dense(N_CLASSES, activation='softmax')
])
model.compile(
optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy']
)
return model
###Output
_____no_output_____
###Markdown
Let's train the model with early stoping as above. Observe that we obtain the same type of accuracy as with the DNN model, but in less epochs (~3 v.s. ~20 epochs):
###Code
%%time
tf.random.set_seed(33)
MODEL_DIR = os.path.join(LOGDIR, 'rnn')
shutil.rmtree(MODEL_DIR, ignore_errors=True)
EPOCHS = 100
BATCH_SIZE = 300
EMBED_DIM = 10
UNITS = 16
PATIENCE = 0
rnn_model = build_rnn_model(embed_dim=EMBED_DIM, units=UNITS)
history = rnn_model.fit(
X_train, Y_train,
epochs=EPOCHS,
batch_size=BATCH_SIZE,
validation_data=(X_valid, Y_valid),
callbacks=[EarlyStopping(patience=PATIENCE), TensorBoard(MODEL_DIR)],
)
pd.DataFrame(history.history)[['loss', 'val_loss']].plot()
pd.DataFrame(history.history)[['accuracy', 'val_accuracy']].plot()
rnn_model.summary()
###Output
_____no_output_____
###Markdown
Build a CNN model The `build_dnn_model` function below returns a compiled Keras model that implements a simple CNN model with a single `Conv1D` layer, which now takes into account the word order in the sentence.The first and last layers are the same as for the simple DNN model, but we need to add a `Flatten` layer betwen the convolution and the softmax layer.Note that we set `mask_zero=True` in the `Embedding` layer so that the padded words (represented by a zero) are ignored by this and the subsequent layers.
###Code
def build_cnn_model(embed_dim, filters, ksize, strides):
model = Sequential([
Embedding(
VOCAB_SIZE + 1,
embed_dim,
input_shape=[MAX_LEN],
mask_zero=True), # TODO 3
Conv1D( # TODO 5
filters=filters,
kernel_size=ksize,
strides=strides,
activation='relu',
),
Flatten(), # TODO 5
Dense(N_CLASSES, activation='softmax')
])
model.compile(
optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy']
)
return model
###Output
_____no_output_____
###Markdown
Let's train the model. Again we observe that we get the same kind of accuracy as with the DNN model but in many fewer steps.
###Code
%%time
tf.random.set_seed(33)
MODEL_DIR = os.path.join(LOGDIR, 'cnn')
shutil.rmtree(MODEL_DIR, ignore_errors=True)
EPOCHS = 100
BATCH_SIZE = 300
EMBED_DIM = 5
FILTERS = 200
STRIDES = 2
KSIZE = 3
PATIENCE = 0
cnn_model = build_cnn_model(
embed_dim=EMBED_DIM,
filters=FILTERS,
strides=STRIDES,
ksize=KSIZE,
)
cnn_history = cnn_model.fit(
X_train, Y_train,
epochs=EPOCHS,
batch_size=BATCH_SIZE,
validation_data=(X_valid, Y_valid),
callbacks=[EarlyStopping(patience=PATIENCE), TensorBoard(MODEL_DIR)],
)
pd.DataFrame(cnn_history.history)[['loss', 'val_loss']].plot()
pd.DataFrame(cnn_history.history)[['accuracy', 'val_accuracy']].plot()
cnn_model.summary()
###Output
_____no_output_____ |
tests/deep-learning/2.1-a-first-look-at-a-neural-network.ipynb | ###Markdown
A first look at a neural networkThis notebook contains the code samples found in Chapter 2, Section 1 of [Deep Learning with Python](https://www.manning.com/books/deep-learning-with-python?a_aid=keras&a_bid=76564dff). Note that the original text features far more content, in particular further explanations and figures: in this notebook, you will only find source code and related comments.----We will now take a look at a first concrete example of a neural network, which makes use of the Python library Keras to learn to classify hand-written digits. Unless you already have experience with Keras or similar libraries, you will not understand everything about this first example right away. You probably haven't even installed Keras yet. Don't worry, that is perfectly fine. In the next chapter, we will review each element in our example and explain them in detail. So don't worry if some steps seem arbitrary or look like magic to you! We've got to start somewhere.The problem we are trying to solve here is to classify grayscale images of handwritten digits (28 pixels by 28 pixels), into their 10 categories (0 to 9). The dataset we will use is the MNIST dataset, a classic dataset in the machine learning community, which has been around for almost as long as the field itself and has been very intensively studied. It's a set of 60,000 training images, plus 10,000 test images, assembled by the National Institute of Standards and Technology (the NIST in MNIST) in the 1980s. You can think of "solving" MNIST as the "Hello World" of deep learning -- it's what you do to verify that your algorithms are working as expected. As you become a machine learning practitioner, you will see MNIST come up over and over again, in scientific papers, blog posts, and so on. The MNIST dataset comes pre-loaded in Keras, in the form of a set of four Numpy arrays:
###Code
from keras.datasets import mnist
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
###Output
Downloading data from https://s3.amazonaws.com/img-datasets/mnist.npz
11493376/11490434 [==============================] - 2s 0us/step
###Markdown
`train_images` and `train_labels` form the "training set", the data that the model will learn from. The model will then be tested on the "test set", `test_images` and `test_labels`. Our images are encoded as Numpy arrays, and the labels are simply an array of digits, ranging from 0 to 9. There is a one-to-one correspondence between the images and the labels.Let's have a look at the training data:
###Code
train_images.shape
len(train_labels)
train_labels
###Output
_____no_output_____
###Markdown
Let's have a look at the test data:
###Code
test_images.shape
len(test_labels)
test_labels
###Output
_____no_output_____
###Markdown
Our workflow will be as follow: first we will present our neural network with the training data, `train_images` and `train_labels`. The network will then learn to associate images and labels. Finally, we will ask the network to produce predictions for `test_images`, and we will verify if these predictions match the labels from `test_labels`.Let's build our network -- again, remember that you aren't supposed to understand everything about this example just yet.
###Code
from keras import models
from keras import layers
network = models.Sequential()
network.add(layers.Dense(512, activation='relu', input_shape=(28 * 28,)))
network.add(layers.Dense(10, activation='softmax'))
###Output
_____no_output_____
###Markdown
The core building block of neural networks is the "layer", a data-processing module which you can conceive as a "filter" for data. Some data comes in, and comes out in a more useful form. Precisely, layers extract _representations_ out of the data fed into them -- hopefully representations that are more meaningful for the problem at hand. Most of deep learning really consists of chaining together simple layers which will implement a form of progressive "data distillation". A deep learning model is like a sieve for data processing, made of a succession of increasingly refined data filters -- the "layers".Here our network consists of a sequence of two `Dense` layers, which are densely-connected (also called "fully-connected") neural layers. The second (and last) layer is a 10-way "softmax" layer, which means it will return an array of 10 probability scores (summing to 1). Each score will be the probability that the current digit image belongs to one of our 10 digit classes.To make our network ready for training, we need to pick three more things, as part of "compilation" step:* A loss function: the is how the network will be able to measure how good a job it is doing on its training data, and thus how it will be able to steer itself in the right direction.* An optimizer: this is the mechanism through which the network will update itself based on the data it sees and its loss function.* Metrics to monitor during training and testing. Here we will only care about accuracy (the fraction of the images that were correctly classified).The exact purpose of the loss function and the optimizer will be made clear throughout the next two chapters.
###Code
network.compile(optimizer='rmsprop',
loss='categorical_crossentropy',
metrics=['accuracy'])
###Output
_____no_output_____
###Markdown
Before training, we will preprocess our data by reshaping it into the shape that the network expects, and scaling it so that all values are in the `[0, 1]` interval. Previously, our training images for instance were stored in an array of shape `(60000, 28, 28)` of type `uint8` with values in the `[0, 255]` interval. We transform it into a `float32` array of shape `(60000, 28 * 28)` with values between 0 and 1.
###Code
train_images = train_images.reshape((60000, 28 * 28))
train_images = train_images.astype('float32') / 255
test_images = test_images.reshape((10000, 28 * 28))
test_images = test_images.astype('float32') / 255
###Output
_____no_output_____
###Markdown
We also need to categorically encode the labels, a step which we explain in chapter 3:
###Code
from keras.utils import to_categorical
train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)
###Output
_____no_output_____
###Markdown
We are now ready to train our network, which in Keras is done via a call to the `fit` method of the network: we "fit" the model to its training data.
###Code
network.fit(train_images, train_labels, epochs=5, batch_size=128)
###Output
Epoch 1/5
60000/60000 [==============================] - 5s 81us/step - loss: 0.2589 - acc: 0.9247
Epoch 2/5
60000/60000 [==============================] - 4s 74us/step - loss: 0.1038 - acc: 0.9691
Epoch 3/5
60000/60000 [==============================] - 5s 81us/step - loss: 0.0699 - acc: 0.9790
Epoch 4/5
60000/60000 [==============================] - 5s 85us/step - loss: 0.0502 - acc: 0.9855
Epoch 5/5
60000/60000 [==============================] - 5s 79us/step - loss: 0.0389 - acc: 0.9884
###Markdown
Two quantities are being displayed during training: the "loss" of the network over the training data, and the accuracy of the network over the training data.We quickly reach an accuracy of 0.989 (i.e. 98.9%) on the training data. Now let's check that our model performs well on the test set too:
###Code
test_loss, test_acc = network.evaluate(test_images, test_labels)
print('test_acc:', test_acc)
###Output
test_acc: 0.98
###Markdown
Our test set accuracy turns out to be 97.8% -- that's quite a bit lower than the training set accuracy. This gap between training accuracy and test accuracy is an example of "overfitting", the fact that machine learning models tend to perform worse on new data than on their training data. Overfitting will be a central topic in chapter 3.This concludes our very first example -- you just saw how we could build and a train a neural network to classify handwritten digits, in less than 20 lines of Python code. In the next chapter, we will go in detail over every moving piece we just previewed, and clarify what is really going on behind the scenes. You will learn about "tensors", the data-storing objects going into the network, about tensor operations, which layers are made of, and about gradient descent, which allows our network to learn from its training examples.
###Code
done
###Output
_____no_output_____ |
TPHLCT/16x16/TPHLCT 3階の導関数を相殺.ipynb | ###Markdown
TPHLCT 3階の導関数を相殺する
###Code
import numpy as np
import scipy.misc
from scipy.fftpack import dct, idct
import sys
from PIL import Image
import matplotlib
import matplotlib.pyplot as plt
import random
from tqdm._tqdm_notebook import tqdm_notebook
from scipy.fftpack import dct, idct
import seaborn as sns
from skimage.metrics import structural_similarity as ssim
%matplotlib inline
class ImageLoader:
def __init__(self, FILE_PATH):
self.img = np.array(Image.open(FILE_PATH))
# 行数
self.row_blocks_count = self.img.shape[0] // 8
# 列数
self.col_blocks_count = self.img.shape[1] // 8
def get_points(self, POINT):
Row = random.randint(0, len(self.img) - POINT - 1)
Col = random.randint(0, len(self.img) - 1)
return self.img[Row : Row + POINT, Col]
def get_block(self, col, row):
return self.img[col * 8 : (col + 1) * 8, row * 8 : (row + 1) * 8]
# plt.rcParams['font.family'] ='sans-serif'#使用するフォント
# plt.rcParams["font.sans-serif"] = "Source Han Sans"
plt.rcParams["font.family"] = "Source Han Sans JP" # 使用するフォント
plt.rcParams["xtick.direction"] = "in" # x軸の目盛線が内向き('in')か外向き('out')か双方向か('inout')
plt.rcParams["ytick.direction"] = "in" # y軸の目盛線が内向き('in')か外向き('out')か双方向か('inout')
plt.rcParams["xtick.major.width"] = 1.0 # x軸主目盛り線の線幅
plt.rcParams["ytick.major.width"] = 1.0 # y軸主目盛り線の線幅
plt.rcParams["font.size"] = 12 # フォントの大きさ
plt.rcParams["axes.linewidth"] = 1.0 # 軸の線幅edge linewidth。囲みの太さ
matplotlib.font_manager._rebuild()
MONO_DIR_PATH = "../../Mono/"
AIRPLANE = ImageLoader(MONO_DIR_PATH + "airplane512.bmp")
BARBARA = ImageLoader(MONO_DIR_PATH + "barbara512.bmp")
BOAT = ImageLoader(MONO_DIR_PATH + "boat512.bmp")
GOLDHILL = ImageLoader(MONO_DIR_PATH + "goldhill512.bmp")
LENNA = ImageLoader(MONO_DIR_PATH + "lenna512.bmp")
MANDRILL = ImageLoader(MONO_DIR_PATH + "mandrill512.bmp")
MILKDROP = ImageLoader(MONO_DIR_PATH + "milkdrop512.bmp")
SAILBOAT = ImageLoader(MONO_DIR_PATH + "sailboat512.bmp")
N = 16
###Output
_____no_output_____
###Markdown
DCT 基底関数 $$\phi_k[i] = \begin{cases}\cfrac{1}{\sqrt{N}} \quad \quad \quad (k=0) \\\sqrt{\cfrac{2}{N}} \cos \left({\cfrac{\pi}{2N}(2i+1)k}\right) \quad (k=1,2,...,N-1) \end{cases}$$
###Code
class DCT:
def __init__(self, N):
self.N = N # データ数
# 1次元DCTの基底ベクトルの生成
self.phi_1d = np.array([self.phi(i) for i in range(self.N)])
# 2次元DCTの基底ベクトルの格納
self.phi_2d = np.zeros((N, N))
def phi(self, k):
""" 離散コサイン変換(DCT)の基底関数 """
# DCT-II
if k == 0:
return np.ones(self.N) / np.sqrt(self.N)
else:
return np.sqrt(2.0 / self.N) * np.cos(
(k * np.pi / (2 * self.N)) * (np.arange(self.N) * 2 + 1)
)
def dct(self, data):
""" 1次元離散コサイン変換を行う """
return self.phi_1d.dot(data)
def idct(self, c):
""" 1次元離散コサイン逆変換を行う """
return np.sum(self.phi_1d.T * c, axis=1)
def get_dct2_phi(self, y, x):
""" 2次元離散コサイン変換の基底を返す """
phi_x, phi_y = np.meshgrid(self.phi_1d[x], self.phi_1d[y])
return phi_x * phi_y
def get_dct2(self, y, x, data):
""" i,jの2次元DCT係数を返す """
phi_2d_phi = np.zeros((self.N, self.N))
phi_2d_phi = self.get_dct2_phi(y, x)
return np.sum(np.sum(phi_2d_phi * data))
def dct2(self, data):
""" 2次元離散コサイン変換を行う """
for y in range(self.N):
for x in range(self.N):
self.phi_2d[y, x] = self.get_dct2(y, x, data)
return self.phi_2d
def idct2(self, c):
""" 2次元離散コサイン逆変換を行う """
idct2_data = np.zeros((self.N, self.N))
phi_2d_phi = np.zeros((self.N, self.N))
for y in range(self.N):
for x in range(self.N):
phi_2d_phi = self.get_dct2_phi(y, x)
idct2_data += c[y,x] * phi_2d_phi
return idct2_data
###Output
_____no_output_____
###Markdown
MSDS
###Code
def msds(N,arr):
w_e = 0
e_e = 0
n_e = 0
s_e = 0
nw_e = 0
ne_e = 0
sw_e = 0
se_e = 0
for row in range(arr.shape[0] // N):
for col in range(arr.shape[1] // N):
f_block = arr[row * N : (row + 1) * N, col * N : (col + 1) * N]
# w
if col == 0:
w_block = np.fliplr(f_block)
else:
w_block = arr[row * N : (row + 1) * N, (col - 1) * N : col * N]
# e
if col == arr.shape[1] // N - 1:
e_block = np.fliplr(f_block)
else:
e_block = arr[row * N : (row + 1) * N, (col + 1) * N : (col + 2) * N]
# n
if row == 0:
n_block = np.flipud(f_block)
else:
n_block = arr[(row - 1) * N : row * N, col * N : (col + 1) * N]
# s
if row == arr.shape[0] // N - 1:
s_block = np.flipud(f_block)
else:
s_block = arr[(row + 1) * N : (row + 2) * N, col * N : (col + 1) * N]
w_d1 = f_block[:, 0] - w_block[:, N-1]
e_d1 = f_block[:, N-1] - e_block[:, 0]
n_d1 = f_block[0, :] - n_block[N-1, :]
s_d1 = f_block[N-1, :] - s_block[0, :]
w_d2 = (w_block[:, N-1] - w_block[:, N-2] + f_block[:, 1] - f_block[:, 0]) / 2
e_d2 = (e_block[:, 1] - e_block[:, 0] + f_block[:, N-1] - f_block[:, N-2]) / 2
n_d2 = (n_block[N-1, :] - n_block[N-2, :] + f_block[1, :] - f_block[0, :]) / 2
s_d2 = (s_block[1, :] - s_block[0, :] + f_block[N-1, :] - f_block[N-2, :]) / 2
w_e += np.sum((w_d1 - w_d2) ** 2 )
e_e += np.sum((e_d1 - e_d2) ** 2 )
n_e += np.sum((n_d1 - n_d2) ** 2)
s_e += np.sum((s_d1 - s_d2) ** 2)
# nw
if row == 0 or col == 0:
nw_block = np.flipud(np.fliplr(f_block))
else:
nw_block = arr[(row - 1) * N : row * N, (col - 1) * N : col * N]
# ne
if row == 0 or col == arr.shape[1] // N - 1:
ne_block = np.flipud(np.fliplr(f_block))
else:
ne_block = arr[(row-1) * N : row * N, (col + 1) * N : (col + 2) * N]
# sw
if row == arr.shape[0] // N -1 or col == 0:
sw_block = np.flipud(np.fliplr(f_block))
else:
sw_block = arr[row * N : (row+1) * N, (col-1) * N : col * N]
# se
if row == arr.shape[0]//N-1 or col == arr.shape[0] // N -1:
se_block = np.flipud(np.fliplr(f_block))
else:
se_block = arr[(row + 1) * N : (row + 2) * N, (col+1) * N : (col + 2) * N]
nw_g1 = f_block[0, 0] - nw_block[N-1, N-1]
ne_g1 = f_block[0, N-1] - ne_block[N-1, 0]
sw_g1 = f_block[N-1, 0] - sw_block[0, N-1]
se_g1 = f_block[N-1, N-1] - se_block[0, 0]
nw_g2 = (nw_block[N-1,N-1] - nw_block[N-2,N-2] + f_block[1,1] - f_block[0,0])/2
ne_g2 = (ne_block[N-1,0] - ne_block[N-2,1] + f_block[1,N-2] - f_block[0,N-1])/2
sw_g2 = (sw_block[0,N-1] - nw_block[1,N-2] + f_block[N-2,1] - f_block[N-1,0])/2
se_g2 = (nw_block[0,0] - nw_block[1,1] + f_block[N-2,N-2] - f_block[N-1,N-1])/2
nw_e += (nw_g1 - nw_g2) ** 2
ne_e += (ne_g1 - ne_g2) ** 2
sw_e += (sw_g1 - sw_g2) ** 2
se_e += (se_g1 - se_g2) ** 2
MSDSt = (w_e + e_e + n_e + s_e + nw_e + ne_e + sw_e + se_e)/ ((arr.shape[0]/N)**2)
MSDS1 = (w_e + e_e + n_e + s_e)/ ((arr.shape[0]/N)**2)
MSDS2 = (nw_e + ne_e + sw_e + se_e)/ ((arr.shape[0]/N)**2)
return MSDSt, MSDS1, MSDS2
###Output
_____no_output_____
###Markdown
係数の計算 $\alpha_k, \beta_k$を計算する。 1階導関数を相殺するような予測関数は $$u(x)=-\frac{f_x(0)}{2}(1-x^2)+\frac{f_x(1)}{2}x^2$$で与えられる。 そのとき、 $$\alpha_k = -\sqrt{\frac{2}{N}}\sum_{\ell=0}^{N-1}\frac{(1-x_\ell)^2}{2}\cos(\pi k x_\ell)$$ $$\beta_k = \sqrt{\frac{2}{N}}\sum_{\ell=0}^{N-1}\frac{x_\ell^2}{2}\cos(\pi k x_\ell)$$ $a_k, b_k, c_k, d_k$を計算する。 3階導関数を相殺するような予測関数は $$\begin{align}u(x) & =( -\frac{1}{2}f_x(0) + \frac{1}{12}f^{(3)}_x(0) )(1-x^2)\\ & -\frac{1}{24}f^{(3)}_x(0)(1-x)^4\\ & +( \frac{1}{2}f_x(1)-\frac{1}{12}f^{(3)}_x(1) )x^2\\ & + \frac{1}{24}f^{(3)}_x(1)x^4\end{align}$$で与えられる。 そのとき、 $$a_k = -\sqrt{\frac{2}{N}}\sum_{\ell=0}^{N-1}\frac{(1-x_\ell)^2}{2}\cos(\pi k x_\ell)$$ $$b_k= \sqrt{\frac{2}{N}}\sum_{\ell=0}^{N-1}( \frac{1}{24}-\frac{x_\ell^2}{6}+\frac{x_\ell^3}{6}-\frac{x_\ell^4}{24} )\cos(\pi k x_\ell)$$ $$c_k = \sqrt{\frac{2}{N}}\sum_{\ell=0}^{N-1}\frac{x_\ell^2}{2}\cos(\pi k x_\ell)$$$$d_k = \sqrt{\frac{2}{N}}\sum_{\ell=0}^{N-1}( -\frac{x_\ell^2}{12}+\frac{x_\ell^4}{24} )\cos(\pi k x_\ell)$$
###Code
sampling_x = (0.5 + np.arange(N)) / N
u_1 = (1 - sampling_x) ** 2 / 2
u_2 = 1 / 24 - sampling_x ** 2 / 6 + sampling_x ** 3 / 6 - sampling_x ** 4 / 24
u_3 = sampling_x ** 2 / 2
u_4 = -sampling_x ** 2 / 12 + sampling_x ** 4 / 24
plt.plot(u_1, label="u_1")
plt.plot(u_2, label="u_2")
plt.plot(u_3, label="u_3")
plt.plot(u_4, label="u_4")
plt.legend()
ak = - scipy.fftpack.dct(u_1,norm="ortho")
ak
bk = scipy.fftpack.dct(u_2,norm="ortho")
bk
ck = scipy.fftpack.dct(u_3,norm="ortho")
ck
dk = scipy.fftpack.dct(u_4,norm="ortho")
dk
alpha = ak
alpha
beta = ck
beta
Ak = (2 * ak - 16 * bk) / np.sqrt(N)
Ak
Bk = (2 * ck - 16 * dk) / np.sqrt(N)
Bk
Ck = (2 * ak - 32 * bk) / np.sqrt(N)
Ck
Dk = (2 * ck - 32 * dk) / np.sqrt(N)
Dk
###Output
_____no_output_____
###Markdown
DCTして残差を計算 $V_k = F_k - U_k\\V_k = F_k - A_k(F_0-F_0^L) -B_k(F_0^R-F_0)-C_k(F_1+F_1^L)-D_k(F_1^R+F_1)$
###Code
IMG = LENNA
Fk = np.zeros(IMG.img.shape)
###Output
_____no_output_____
###Markdown
DCT 縦方向 2次元入力信号を垂直方向の一次元信号が水平方向に並列に並んでいるものとみなし、各列において8画素単位の1次元DCTを適用する
###Code
for row in range(IMG.img.shape[0] // 16):
for col in range(IMG.img.shape[1]):
eight_points = IMG.img[16 * row : 16 * (row + 1), col]
c = scipy.fftpack.dct(eight_points,norm="ortho")
Fk[16 * row : 16 * (row + 1), col] = c
###Output
_____no_output_____
###Markdown
縦方向の残差 3階の導関数
###Code
for row in range(Fk.shape[0] // 16):
for col in range(Fk.shape[1]):
F = Fk[16 * row : 16 * (row + 1), col]
F_0_r = 0
F_1_r = 0
if row is not Fk.shape[0] // 16 - 1:
F_0_r = Fk[16 * (row + 1), col]
F_1_r = Fk[16 * (row + 1) + 1, col]
F_0_l = 0
F_1_l = 1
if row is not 0:
F_0_l = Fk[16 * (row - 1), col]
F_1_l = Fk[16 * (row - 1) + 1, col]
# 残差
F_0 = F[0]
F_1 = F[1]
F = (
F
- Ak * (F_0 - F_0_l)
- Bk * (F_0_r - F_0)
- Ck * (F_1 + F_1_l)
- Dk * (F_1_r + F_1)
)
# F_0, F_1は残す
F[0] = F_0
F[1] = F_1
# F_0 V_1 V_2 V_3 V_4 V_5 V_6 V_7
Fk[16 * row : 16 * (row + 1), col] = F
###Output
_____no_output_____
###Markdown
1階の導関数
###Code
for row in range(Fk.shape[0] // 16):
for col in range(Fk.shape[1]):
F = Fk[16 * row : 16 * (row + 1), col]
F_0_r = 0
if row is not Fk.shape[0] // 16 - 1:
F_0_r = Fk[16 * (row + 1), col]
F_0_l = 0
if row is not 0:
F_0_l = Fk[16 * (row - 1), col]
# 残差
F_0 = F[0]
F_temp = F - alpha * (F_0_r - F_0) / np.sqrt(N) - beta * (F_0 - F_0_l) / np.sqrt(N)
# F_0は残す
F[1] = F_temp[1]
# F_0 V_1 V_2 V_3 V_4 V_5 V_6 V_7
Fk[16 * row : 16 * (row + 1), col] = F
###Output
_____no_output_____
###Markdown
DCT 横方向
###Code
for row in range(Fk.shape[0]):
for col in range(Fk.shape[1] // 16):
eight_points = Fk[row, 16 * col : 16 * (col + 1)]
c = scipy.fftpack.dct(eight_points,norm="ortho")
Fk[row, 16 * col : 16 * (col + 1)] = c
###Output
_____no_output_____
###Markdown
横方向の残差 3階の導関数
###Code
for row in range(Fk.shape[0]):
for col in range(Fk.shape[1] // 16):
F = Fk[row, 16 * col : 16 * (col + 1)]
F_0_r = 0
F_1_r = 0
if col is not Fk.shape[1] // 16 - 1:
F_0_r = Fk[row, 16 * (col + 1)]
F_1_r = Fk[row, 16 * (col + 1) + 1]
F_0_l = 0
F_1_l = 0
if col is not 0:
F_0_l = Fk[row, 16 * (col - 1)]
F_1_l = Fk[row, 16 * (col - 1) + 1]
# 残差
F_0 = F[0]
F_1 = F[1]
F = (
F
- Ak * (F_0 - F_0_l)
- Bk * (F_0_r - F_0)
- Ck * (F_1 + F_1_l)
- Dk * (F_1_r + F_1)
)
# F_0は残す
F[0] = F_0
F[1] = F_1
# F_0 V_1 V_2 V_3 V_4 V_5 V_6 V_7
Fk[row, 16 * col : 16 * (col + 1)] = F
###Output
_____no_output_____
###Markdown
1階の導関数
###Code
for row in range(Fk.shape[0]):
for col in range(Fk.shape[1] // 16):
F = Fk[row, 16 * col : 16 * (col + 1)]
F_0_r = 0
if col is not Fk.shape[1] // 16 - 1:
F_0_r = Fk[row, 16 * (col + 1)]
F_0_l = 0
if col is not 0:
F_0_l = Fk[row, 16 * (col - 1)]
# 残差
F_0 = F[0]
F_temp = F - alpha * (F_0_r - F_0) / np.sqrt(N) - beta * (F_0 - F_0_l) / np.sqrt(N)
# F_0は残す
F[1] = F_temp[1]
# F_0 V_1 V_2 V_3 V_4 V_5 V_6 V_7
Fk[row, 16 * col : 16 * (col + 1)] = F
###Output
_____no_output_____
###Markdown
係数の確保
###Code
Fk_Ori = np.copy(Fk)
###Output
_____no_output_____
###Markdown
低域3成分 (0,1)(1,0)(1,1)の絶対値の和
###Code
low_3_value = 0
others_value = 0
for row in range(Fk.shape[0] // 16):
for col in range(Fk.shape[1] // 16):
block = Fk[row * 16 : (row + 1) * 16, col * 16 : (col + 1) * 16]
low_3_value += np.abs(block[0, 1]) + np.abs(block[1, 0]) + np.abs(block[1, 1])
others_value += (
np.sum(np.sum(np.abs(block)))
- np.abs(block[0, 0])
- np.abs(block[0, 1])
- np.abs(block[1, 0])
- np.abs(block[1, 1])
)
low_3_value
others_value
###Output
_____no_output_____
###Markdown
逆変換 $F_k = F_k + U_k\\F_k = V_k + A_k(F_0-F_0^L) +B_k(F_0^R-F_0)+C_k(F_1+F_1^L)+D_k(F_1^R+F_1)$
###Code
# recover = np.zeros(IMG.img.shape).astype("uint8")
recover = np.zeros(IMG.img.shape)
###Output
_____no_output_____
###Markdown
横方向の残差 1階の導関数
###Code
for row in range(Fk.shape[0]):
for col in range(Fk.shape[1] // 16):
F = Fk[row, 16 * col : 16 * col + 16]
F_0_r = 0
if col is not Fk.shape[1] // 16 - 1:
F_0_r = Fk[row, 16 * (col + 1)]
F_0_l = 0
if col is not 0:
F_0_l = Fk[row, 16 * (col - 1)]
# 残差
F_0 = F[0]
F_temp = F + alpha * (F_0_r - F_0) / np.sqrt(N) + beta * (F_0 - F_0_l) / np.sqrt(N)
# F_0は残す
F[1] = F_temp[1]
# F_0 V_1 V_2 V_3 V_4 V_5 V_6 V_7
Fk[row, 16 * col : 16 * col + 16] = F
###Output
_____no_output_____
###Markdown
3階の導関数
###Code
for row in range(Fk.shape[0]):
for col in range(Fk.shape[1] // 16):
F = Fk[row, 16 * col : 16 * (col + 1)]
F_0_r = 0
F_1_r = 0
if col is not Fk.shape[1] // 16 - 1:
F_0_r = Fk[row, 16 * (col + 1)]
F_1_r = Fk[row, 16 * (col + 1) + 1]
F_0_l = 0
F_1_l = 0
if col is not 0:
F_0_l = Fk[row, 16 * (col - 1)]
F_1_l = Fk[row, 16 * (col - 1) + 1]
# 残差
F_0 = F[0]
F_1 = F[1]
F = (
F
+ Ak * (F_0 - F_0_l)
+ Bk * (F_0_r - F_0)
+ Ck * (F_1 + F_1_l)
+ Dk * (F_1_r + F_1)
)
# F_0は残す
F[0] = F_0
F[1] = F_1
# F_0 V_1 V_2 V_3 V_4 V_5 V_6 V_7
Fk[row, 16 * col : 16 * (col + 1)] = F
###Output
_____no_output_____
###Markdown
IDCT 横方向
###Code
for row in range(Fk.shape[0]):
for col in range(Fk.shape[1] // 16):
F = Fk[row, 16 * col : 16 * col + 16]
data = scipy.fftpack.idct(F,norm="ortho")
# Fkに代入した後、縦方向に対して処理
Fk[row, 16 * col : 16 * col + 16] = data
# 復元画像
# recover[row, 16 * col : 16 * col + 16] = data
###Output
_____no_output_____
###Markdown
縦方向 1階の導関数
###Code
for row in range(Fk.shape[0] // 16):
for col in range(Fk.shape[1]):
F = Fk[16 * row : 16 * row + 16, col]
F_0_r = 0
if row is not Fk.shape[0] // 16 - 1:
F_0_r = Fk[16 * (row + 1), col]
F_0_l = 0
if row is not 0:
F_0_l = Fk[16 * (row - 1), col]
# 残差
F_0 = F[0]
F_temp = F + alpha * (F_0_r - F_0) / np.sqrt(N) + beta * (F_0 - F_0_l) / np.sqrt(N)
# F_0は残す
F[1] = F_temp[1]
# F_0 F_1 F_2 F_3 F_4 F_5 F_6 F_7
Fk[16 * row : 16 * row + 16, col] = F
###Output
_____no_output_____
###Markdown
3階の導関数
###Code
for row in range(Fk.shape[0] // 16):
for col in range(Fk.shape[1]):
F = Fk[16 * row : 16 * (row + 1), col]
F_0_r = 0
F_1_r = 0
if row is not Fk.shape[0] // 16 - 1:
F_0_r = Fk[16 * (row + 1), col]
F_1_r = Fk[16 * (row + 1) + 1, col]
F_0_l = 0
F_1_l = 1
if row is not 0:
F_0_l = Fk[16 * (row - 1), col]
F_1_l = Fk[16 * (row - 1) + 1, col]
# 残差
F_0 = F[0]
F_1 = F[1]
F = (
F
+ Ak * (F_0 - F_0_l)
+ Bk * (F_0_r - F_0)
+ Ck * (F_1 + F_1_l)
+ Dk * (F_1_r + F_1)
)
# F_0, F_1は残す
F[0] = F_0
F[1] = F_1
# F_0 V_1 V_2 V_3 V_4 V_5 V_6 V_7
Fk[16 * row : 16 * (row + 1), col] = F
###Output
_____no_output_____
###Markdown
縦方向IDCT
###Code
for row in range(Fk.shape[0] // 16):
for col in range(Fk.shape[1]):
F = Fk[16 * row : 16 * (row + 1), col]
data = scipy.fftpack.idct(F,norm="ortho")
# 復元画像
recover[16 * row : 16 * (row + 1), col] = data
# FKに代入した後、横方向に対して処理
# Fk[16 * row : 16 * (row + 1), col] = data
plt.imshow(np.round(recover), cmap="gray")
plt.imshow(IMG.img, cmap="gray")
recover[0, 0:10]
IMG.img[0, 0:10]
###Output
_____no_output_____
###Markdown
ちゃんと復元できた 量子化テーブル
###Code
Q = 38.5
Q_Luminance = np.ones((16,16)) * Q
###Output
_____no_output_____
###Markdown
量子化
###Code
Fk = np.copy(Fk_Ori)
plt.imshow(Fk)
Q_Fk = np.zeros(Fk.shape)
for row in range(IMG.img.shape[0] // 16):
for col in range(IMG.img.shape[1] // 16):
block = Fk[row * 16 : (row + 1) * 16, col * 16 : (col + 1) * 16]
# 量子化
block = np.round(block / Q_Luminance)
# 逆量子化
block = block * Q_Luminance
Q_Fk[row * 16 : (row+1)*16, col * 16 : (col+1)*16] = block
###Output
_____no_output_____
###Markdown
逆変換
###Code
Fk = np.copy(Q_Fk)
# Fk = np.copy(Fk_Ori)
Q_recover = np.zeros(Q_Fk.shape)
###Output
_____no_output_____
###Markdown
横方向の残差 1階の導関数
###Code
for row in range(Fk.shape[0]):
for col in range(Fk.shape[1] // 16):
F = Fk[row, 16 * col : 16 * col + 16]
F_0_r = 0
if col is not Fk.shape[1] // 16 - 1:
F_0_r = Fk[row, 16 * (col + 1)]
F_0_l = 0
if col is not 0:
F_0_l = Fk[row, 16 * (col - 1)]
# 残差
F_0 = F[0]
F_temp = F + alpha * (F_0_r - F_0) / np.sqrt(N) + beta * (F_0 - F_0_l) / np.sqrt(N)
# F_0は残す
F[1] = F_temp[1]
# F_0 V_1 V_2 V_3 V_4 V_5 V_6 V_7
Fk[row, 16 * col : 16 * col + 16] = F
###Output
_____no_output_____
###Markdown
3階の導関数
###Code
for row in range(Fk.shape[0]):
for col in range(Fk.shape[1] // 16):
F = Fk[row, 16 * col : 16 * (col + 1)]
F_0_r = 0
F_1_r = 0
if col is not Fk.shape[1] // 16 - 1:
F_0_r = Fk[row, 16 * (col + 1)]
F_1_r = Fk[row, 16 * (col + 1) + 1]
F_0_l = 0
F_1_l = 0
if col is not 0:
F_0_l = Fk[row, 16 * (col - 1)]
F_1_l = Fk[row, 16 * (col - 1) + 1]
# 残差
F_0 = F[0]
F_1 = F[1]
F = (
F
+ Ak * (F_0 - F_0_l)
+ Bk * (F_0_r - F_0)
+ Ck * (F_1 + F_1_l)
+ Dk * (F_1_r + F_1)
)
# F_0は残す
F[0] = F_0
F[1] = F_1
# F_0 V_1 V_2 V_3 V_4 V_5 V_6 V_7
Fk[row, 16 * col : 16 * (col + 1)] = F
###Output
_____no_output_____
###Markdown
IDCT 横方向
###Code
for row in range(Fk.shape[0]):
for col in range(Fk.shape[1] // 16):
F = Fk[row, 16 * col : 16 * col + 16]
data = scipy.fftpack.idct(F,norm="ortho")
# Fkに代入した後、縦方向に対して処理
Fk[row, 16 * col : 16 * col + 16] = data
# 復元画像
# recover[row, 16 * col : 16 * col + 16] = data
###Output
_____no_output_____
###Markdown
縦方向 1階の導関数
###Code
for row in range(Fk.shape[0] // 16):
for col in range(Fk.shape[1]):
F = Fk[16 * row : 16 * row + 16, col]
F_0_r = 0
if row is not Fk.shape[0] // 16 - 1:
F_0_r = Fk[16 * (row + 1), col]
F_0_l = 0
if row is not 0:
F_0_l = Fk[16 * (row - 1), col]
# 残差
F_0 = F[0]
F_temp[1] = F + alpha * (F_0_r - F_0) / np.sqrt(N) + beta * (F_0 - F_0_l) / np.sqrt(N)
# F_0は残す
F[1] = F_temp[1]
# F_0 F_1 F_2 F_3 F_4 F_5 F_6 F_7
Fk[16 * row : 16 * row + 16, col] = F
###Output
_____no_output_____
###Markdown
3階の導関数
###Code
for row in range(Fk.shape[0] // 16):
for col in range(Fk.shape[1]):
F = Fk[16 * row : 16 * (row + 1), col]
F_0_r = 0
F_1_r = 0
if row is not Fk.shape[0] // 16 - 1:
F_0_r = Fk[16 * (row + 1), col]
F_1_r = Fk[16 * (row + 1) + 1, col]
F_0_l = 0
F_1_l = 1
if row is not 0:
F_0_l = Fk[16 * (row - 1), col]
F_1_l = Fk[16 * (row - 1) + 1, col]
# 残差
F_0 = F[0]
F_1 = F[1]
F = (
F
+ Ak * (F_0 - F_0_l)
+ Bk * (F_0_r - F_0)
+ Ck * (F_1 + F_1_l)
+ Dk * (F_1_r + F_1)
)
# F_0, F_1は残す
F[0] = F_0
F[1] = F_1
# F_0 V_1 V_2 V_3 V_4 V_5 V_6 V_7
Fk[16 * row : 16 * (row + 1), col] = F
###Output
_____no_output_____
###Markdown
IDCT 縦方向
###Code
for row in range(Fk.shape[0] // 16):
for col in range(Fk.shape[1]):
F = Fk[16 * row : 16 * (row + 1), col]
data = scipy.fftpack.idct(F,norm="ortho")
# 復元画像
Q_recover[16 * row : 16 * (row + 1), col] = data
# FKに代入した後、横方向に対して処理
# Fk[16 * row : 16 * (row + 1), col] = data
Q_recover = np.round(Q_recover)
plt.imshow(Q_recover, cmap="gray")
plt.imsave("TPHLCT3_16x16_LENNA.png",Q_recover,cmap="gray")
###Output
_____no_output_____
###Markdown
情報量 $$S = - \sum ^{255}_{i=0} p_i log_2 p_i$$
###Code
import pandas as pd
qfk = pd.Series(Q_Fk.flatten())
pro = qfk.value_counts() / qfk.value_counts().sum()
pro.head()
S = 0
for pi in pro:
S -= pi * np.log2(pi)
S
###Output
_____no_output_____
###Markdown
PSNR $$PSNR = 10 log_{10} \frac{MAX^2}{MSE}$$ $${MSE = \frac{1}{m \, n} \sum^{m-1}_{i=0} \sum^{n-1}_{j=0} [ I(i,j) - K(i,j) ]^2}$$$I(i,j)$は原画像, $K(i,j)$は圧縮画像
###Code
MSE = np.sum(np.sum(np.power((IMG.img - Q_recover),2)))/(Q_recover.shape[0] * Q_recover.shape[1])
PSNR = 10 * np.log10(255 * 255 / MSE)
PSNR
###Output
_____no_output_____
###Markdown
MSSIM
###Code
MSSIM = ssim(IMG.img,Q_recover.astype(IMG.img.dtype),gaussian_weights=True,sigma=1.5,K1=0.01,K2=0.03)
MSSIM
###Output
_____no_output_____
###Markdown
MSDS
###Code
MSDSt, MSDS1, MSDS2 = msds(16,Q_recover)
MSDS1
MSDS2
###Output
_____no_output_____ |
Computer Labs/CL2/CL2.ipynb | ###Markdown
CL2 - Intro to Convolution Neural Networks in Keras In this computer lab we'll show you an example of how to define, train, and assess the performance of convolutional neural networks using Keras. For this task, we will use the MNIST dataset, which comprises of 70.000 28x28 grayscale images of handwritten digits (60k for training, 10k for testing).Our goal is to build a convolutional neural network that takes as input the grayscale image of a handwritten digit, and outputs its corresponding label. As usual, we start by importing the required packages.
###Code
# The package for importing the dataset (already provided by Keras)
from keras.datasets import mnist
# Packages for defining the architecture of our model
from keras.models import Sequential
from keras.layers import Dense, Flatten, BatchNormalization
from keras.layers.convolutional import Conv2D, MaxPooling2D
# One-hot encoding
from keras.utils import np_utils
# Callbacks for training
from keras.callbacks import TensorBoard, EarlyStopping
# Ploting
import matplotlib.pyplot as plt
%matplotlib inline
# Ndarray computations
import numpy as np
# Confusion matrix for assessment step
from sklearn.metrics import confusion_matrix
###Output
Using TensorFlow backend.
###Markdown
1. Loading and visualizing the data We can load the MNIST dataset using the function `load_data()`, which already splits it into training and test sets. If this is the first time you're running this cell, you will require internet access to download the dataset.
###Code
(X_train, y_train), (X_test, y_test) = mnist.load_data()
###Output
Downloading data from https://s3.amazonaws.com/img-datasets/mnist.npz
11493376/11490434 [==============================] - 3s 0us/step
###Markdown
We can see the range of pixel values by running the following cell:
###Code
print('Min:', X_train.min(), '\nMax:', X_train.max())
###Output
Min: 0
Max: 255
###Markdown
And also the shapes of the training set:
###Code
X_train.shape
y_train.shape
###Output
_____no_output_____
###Markdown
The shape of `X_train` can be interpreted as (samples, width, height). So we can see that the training set is comprised indeed of 60k images, each 28x28. Doing the same for the test set:
###Code
X_test.shape
y_test.shape
###Output
_____no_output_____
###Markdown
shows us that we have 10k images in the test set, also 28x28. We can take a look at one of the examples in the training set by simply indexing `X_train` in its first dimension:
###Code
X_train[10]
###Output
_____no_output_____
###Markdown
Which shows the 10th data point in the training set as a matrix of numbers. Since we know that each example is actually a grayscale image of a handwritten digit, is more conveninent to display it as an image instead:
###Code
plt.imshow(X_train[10], cmap='gray');
###Output
_____no_output_____
###Markdown
And we can see the corresponding ground truth label by indexing `y_train` with the same index.
###Code
y_train[10]
###Output
_____no_output_____
###Markdown
2. Preprocessing As we saw previously, the shape of the inputs is:
###Code
X_train.shape
X_train.shape
###Output
_____no_output_____
###Markdown
However, Keras expects input images to have their dimensions in the following format `[samples][width][height][channels]`. Although we have grayscale images (i.e. with only one channel, instead of 3 like RGB images), we should reshape the input to conform to this by adding a new dimension.
###Code
X_train = X_train.reshape(X_train.shape[0], 28, 28, 1)
X_test = X_test.reshape(X_test.shape[0], 28, 28, 1)
X_train.shape
###Output
_____no_output_____
###Markdown
And it's more convenient to work with `ndarray`s of floats, instead of integers.
###Code
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
###Output
_____no_output_____
###Markdown
We also want to normalize the pixel values to range from 0 to 1 (instead of 0 to 255),
###Code
X_train = X_train / 255
X_test = X_test / 255
###Output
_____no_output_____
###Markdown
And finally, one hot-encode the output labels.
###Code
y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)
num_classes = y_test.shape[1]
y_train[10]
###Output
_____no_output_____
###Markdown
3. Training Now that all the preprocessing steps were taken care of, we are ready to create a tentative model. The following code defines a model with the following layers, from input to output:- Convolutional layer, 30 filters of size 5x5.- ReLU- 2x2 MaxPooling layer- Fully connected layer with 128 neurons- ReLU- Fully connected layer with 10 neurons- Softmax
###Code
def base_model():
# create model
model = Sequential()
model.add(Conv2D(30, (5, 5), input_shape=(28, 28, 1), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dense(num_classes, activation='softmax'))
# Compile model
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
return model
###Output
_____no_output_____
###Markdown
Note that the convolutional layer was implemented using a [`Conv2D` layer](https://keras.io/layers/convolutional/conv2d) and the max pooling layer was implemented using a [`MaxPooling2D` layer](https://keras.io/layers/pooling/maxpooling2d). Take a look at Keras help page for these layers to obtain more information about them. Also, note that in order for Keras to connect the output of the MaxPooling layer (which has shape `(batch, width, heigth, channels)`) to the fully connected layer, it was necessary to first use a [`Flatten` layer](https://keras.io/layers/core/flatten), which "flattens" its input, squashing all dimensions aside from the batch dimension together. For example, if the input has shape `(32, 28, 28, 3)`, the output will have shape `(32,2352)`. Now that we defined the architecture, we can train it with the following cell.
###Code
# build the model
model = base_model()
# Fit the model
tb = TensorBoard(log_dir='./logs/initial_setting')
history = model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=15, batch_size=1024, callbacks=[tb])
###Output
Train on 60000 samples, validate on 10000 samples
Epoch 1/15
60000/60000 [==============================] - 37s 612us/step - loss: 0.5401 - acc: 0.8545 - val_loss: 0.2190 - val_acc: 0.9371
Epoch 2/15
60000/60000 [==============================] - 35s 591us/step - loss: 0.1781 - acc: 0.9480 - val_loss: 0.1290 - val_acc: 0.9630
Epoch 3/15
60000/60000 [==============================] - 36s 605us/step - loss: 0.1109 - acc: 0.9689 - val_loss: 0.0874 - val_acc: 0.9751
Epoch 4/15
60000/60000 [==============================] - 38s 641us/step - loss: 0.0789 - acc: 0.9782 - val_loss: 0.0656 - val_acc: 0.9801
Epoch 5/15
60000/60000 [==============================] - 36s 604us/step - loss: 0.0626 - acc: 0.9823 - val_loss: 0.0550 - val_acc: 0.9834
Epoch 6/15
60000/60000 [==============================] - 36s 601us/step - loss: 0.0521 - acc: 0.9849 - val_loss: 0.0494 - val_acc: 0.9845
Epoch 7/15
60000/60000 [==============================] - 40s 663us/step - loss: 0.0448 - acc: 0.9873 - val_loss: 0.0469 - val_acc: 0.9847
Epoch 8/15
60000/60000 [==============================] - 37s 610us/step - loss: 0.0386 - acc: 0.9892 - val_loss: 0.0437 - val_acc: 0.9856
Epoch 9/15
60000/60000 [==============================] - 37s 616us/step - loss: 0.0353 - acc: 0.9901 - val_loss: 0.0430 - val_acc: 0.9850
Epoch 10/15
60000/60000 [==============================] - 37s 615us/step - loss: 0.0309 - acc: 0.9910 - val_loss: 0.0394 - val_acc: 0.9870
Epoch 11/15
60000/60000 [==============================] - 39s 655us/step - loss: 0.0289 - acc: 0.9918 - val_loss: 0.0403 - val_acc: 0.9866
Epoch 12/15
60000/60000 [==============================] - 36s 607us/step - loss: 0.0256 - acc: 0.9927 - val_loss: 0.0365 - val_acc: 0.9878
Epoch 13/15
60000/60000 [==============================] - 38s 627us/step - loss: 0.0228 - acc: 0.9939 - val_loss: 0.0415 - val_acc: 0.9870
Epoch 14/15
60000/60000 [==============================] - 35s 590us/step - loss: 0.0210 - acc: 0.9942 - val_loss: 0.0345 - val_acc: 0.9883
Epoch 15/15
60000/60000 [==============================] - 35s 587us/step - loss: 0.0184 - acc: 0.9950 - val_loss: 0.0358 - val_acc: 0.9873
###Markdown
Try different architectures.
###Code
def more_layers_model():
model = Sequential()
model.add(Conv2D(30, (5, 5), input_shape=(28, 28, 1), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(30, (5, 5), input_shape=(28, 28, 1), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dense(num_classes, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
return model
def more_filters_model():
model = Sequential()
model.add(Conv2D(100, (5, 5), input_shape=(28, 28, 1), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dense(num_classes, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
return model
def more_neurons_model():
model = Sequential()
model.add(Conv2D(30, (5, 5), input_shape=(28, 28, 1), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(1024, activation='relu'))
model.add(Dense(num_classes, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
return model
def bnorm_model():
model = Sequential()
model.add(Conv2D(30, (5, 5), input_shape=(28, 28, 1), activation='relu'))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(BatchNormalization())
model.add(Dense(num_classes, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
return model
###Output
_____no_output_____
###Markdown
Train all of them and compare the results using [TensorBoard](https://www.tensorflow.org/guide/summaries_and_tensorboard). To see the tensorboard results, open a terminal in the directory where this notebook is, and type `tensorboard --logdir=logs`. This will start the TensorBoard server and show you its address. Follow that address to access its web interface.Note: if you're running a notebook from the cloud, follow the instructions inside the `Instructions` folder about how to use TensorBoard instead.
###Code
model_names = ['more_layers_model', 'more_filters_model', 'more_neurons_model', 'bnorm_model']
for name in model_names:
print('Training model:',name)
model = globals()[name]()
tb = TensorBoard(log_dir='./logs/'+name)
model.fit(X_train,
y_train,
validation_data=(X_test, y_test),
epochs=15,
batch_size=1024,
callbacks=[tb],
verbose=0)
print('Done!')
###Output
Training model: more_layers_model
###Markdown
Choose the best one and train longer. Here we also use [early stopping](https://en.wikipedia.org/wiki/Early_stoppingValidation-based_early_stopping).
###Code
model = base_model()
# Set callbacks
tb = TensorBoard(log_dir='./logs/final_model')
estop = EarlyStopping(monitor='val_acc', patience=5)
# Train the model
model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=50, batch_size=1024, callbacks=[tb, estop])
###Output
_____no_output_____
###Markdown
4. Assessment Once we found our best model, we can evaluate its performance on the test set. In our case, we would like to compute its accuracy:
###Code
scores = model.evaluate(X_test, y_test, verbose=0)
print("Test accuracy: %.2f%%" % (scores[1]*100))
temp = model.predict(X_test)
y_pred = np.argmax(temp, axis=1)
y_true = np.argmax(y_test, axis=1)
confusion_matrix(y_true, y_pred)
###Output
_____no_output_____
###Markdown
CL2 - Intro to CNNs in Keras Import necessary modules
###Code
# The dataset
from keras.datasets import mnist
# Building the model
from keras.models import Sequential
from keras.layers import Dense, Flatten, BatchNormalization
from keras.layers.convolutional import Conv2D, MaxPooling2D
# One-hot encoding
from keras.utils import np_utils
# Callbacks for training
from keras.callbacks import TensorBoard, EarlyStopping
# Ploting
import matplotlib.pyplot as plt
%matplotlib inline
# Ndarray computations
import numpy as np
###Output
_____no_output_____
###Markdown
1. Loading and visualizing the data Load the data intro training and test sets.
###Code
(X_train, y_train), (X_test, y_test) = mnist.load_data()
###Output
_____no_output_____
###Markdown
Check range.
###Code
print('Min:', X_train.min(), '\nMax:', X_train.max())
###Output
_____no_output_____
###Markdown
Check dimensions.
###Code
X_train.shape
###Output
_____no_output_____
###Markdown
Take a look at one example.
###Code
X_train[10]
###Output
_____no_output_____
###Markdown
Plot one example.
###Code
plt.imshow(X_train[10], cmap='gray')
y_train[10]
###Output
_____no_output_____
###Markdown
2. Preprocessing Reshape the input dimensions to be `[samples][width][height][channels]`
###Code
X_train = X_train.reshape(X_train.shape[0], 28, 28, 1).astype('float32')
X_test = X_test.reshape(X_test.shape[0], 28, 28, 1).astype('float32')
X_train.shape
###Output
_____no_output_____
###Markdown
Normalize inputs to 0-1.
###Code
X_train = X_train / 255
X_test = X_test / 255
###Output
_____no_output_____
###Markdown
One hot-encode output.
###Code
y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)
num_classes = y_test.shape[1]
y_train[10]
###Output
_____no_output_____
###Markdown
3. Training Create a tentative model.
###Code
def base_model():
# create model
model = Sequential()
model.add(Conv2D(30, (5, 5), input_shape=(28, 28, 1), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dense(num_classes, activation='softmax'))
# Compile model
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
return model
###Output
_____no_output_____
###Markdown
Train it using Keras.
###Code
# build the model
model = base_model()
# Fit the model
tb = TensorBoard(log_dir='./logs/initial_setting')
history = model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=15, batch_size=1024, callbacks=[tb])
###Output
_____no_output_____
###Markdown
Try different architectures.
###Code
def more_layers_model():
model = Sequential()
model.add(Conv2D(30, (5, 5), input_shape=(28, 28, 1), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(30, (5, 5), input_shape=(28, 28, 1), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dense(num_classes, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
return model
def more_filters_model():
model = Sequential()
model.add(Conv2D(100, (5, 5), input_shape=(28, 28, 1), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dense(num_classes, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
return model
def more_neurons_model():
model = Sequential()
model.add(Conv2D(30, (5, 5), input_shape=(28, 28, 1), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(1024, activation='relu'))
model.add(Dense(num_classes, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
return model
def bnorm_model():
model = Sequential()
model.add(Conv2D(30, (5, 5), input_shape=(28, 28, 1), activation='relu'))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(BatchNormalization())
model.add(Dense(num_classes, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
return model
###Output
_____no_output_____
###Markdown
Train all of them and compare the results using TensorBoard.
###Code
model_names = ['more_layers_model', 'more_filters_model', 'more_neurons_model', 'bnorm_model']
for name in model_names:
print('Training model:',name)
model = globals()[name]()
tb = TensorBoard(log_dir='./logs/'+name)
model.fit(X_train,
y_train,
validation_data=(X_test, y_test),
epochs=15,
batch_size=1024,
callbacks=[tb],
verbose=0)
print('Done!')
###Output
_____no_output_____
###Markdown
Choose the best one and train longer. Here we also use [early stopping](https://en.wikipedia.org/wiki/Early_stoppingValidation-based_early_stopping).
###Code
model = more_filters_model()
# Set callbacks
tb = TensorBoard(log_dir='./logs/final_model')
estop = EarlyStopping(monitor='val_acc', patience=5)
# Train the model
model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=50, batch_size=1024, callbacks=[tb, estop])
###Output
_____no_output_____
###Markdown
4. Assessment Evaluate accuracy on test set.
###Code
scores = model.evaluate(X_test, y_test, verbose=0)
print("Test accuracy: %.2f%%" % (scores[1]*100))
###Output
_____no_output_____
###Markdown
CL2 - Intro to Convolution Neural Networks in Keras In this computer lab we'll show you an example of how to define, train, and assess the performance of convolutional neural networks using Keras. For this task, we will use the MNIST dataset, which comprises of 70.000 28x28 grayscale images of handwritten digits (60k for training, 10k for testing).Our goal is to build a convolutional neural network that takes as input the grayscale image of a handwritten digit, and outputs its corresponding label. As usual, we start by importing the required packages.
###Code
# The package for importing the dataset (already provided by Keras)
from keras.datasets import mnist
# Packages for defining the architecture of our model
from keras.models import Sequential
from keras.layers import Dense, Flatten, BatchNormalization
from keras.layers.convolutional import Conv2D, MaxPooling2D
# One-hot encoding
from keras.utils import np_utils
# Callbacks for training
from keras.callbacks import TensorBoard, EarlyStopping
# Ploting
import matplotlib.pyplot as plt
%matplotlib inline
# Ndarray computations
import numpy as np
# Confusion matrix for assessment step
from sklearn.metrics import confusion_matrix
###Output
_____no_output_____
###Markdown
1. Loading and visualizing the data We can load the MNIST dataset using the function `load_data()`, which already splits it into training and test sets. If this is the first time you're running this cell, you will require internet access to download the dataset.
###Code
(X_train, y_train), (X_test, y_test) = mnist.load_data()
###Output
_____no_output_____
###Markdown
We can see the range of pixel values by running the following cell:
###Code
print('Min:', X_train.min(), '\nMax:', X_train.max())
###Output
_____no_output_____
###Markdown
And also the shapes of the training set:
###Code
X_train.shape
y_train.shape
###Output
_____no_output_____
###Markdown
The shape of `X_train` can be interpreted as (samples, width, height). So we can see that the training set is comprised indeed of 60k images, each 28x28. Doing the same for the test set:
###Code
X_test.shape
y_test.shape
###Output
_____no_output_____
###Markdown
shows us that we have 10k images in the test set, also 28x28. We can take a look at one of the examples in the training set by simply indexing `X_train` in its first dimension:
###Code
X_train[10]
###Output
_____no_output_____
###Markdown
Which shows the 10th data point in the training set as a matrix of numbers. Since we know that each example is actually a grayscale image of a handwritten digit, is more conveninent to display it as an image instead:
###Code
plt.imshow(X_train[10], cmap='gray');
###Output
_____no_output_____
###Markdown
And we can see the corresponding ground truth label by indexing `y_train` with the same index.
###Code
y_train[10]
###Output
_____no_output_____
###Markdown
2. Preprocessing As we saw previously, the shape of the inputs is:
###Code
X_train.shape
X_train.shape
###Output
_____no_output_____
###Markdown
However, Keras expects input images to have their dimensions in the following format `[samples][width][height][channels]`. Although we have grayscale images (i.e. with only one channel, instead of 3 like RGB images), we should reshape the input to conform to this by adding a new dimension.
###Code
X_train = X_train.reshape(X_train.shape[0], 28, 28, 1)
X_test = X_test.reshape(X_test.shape[0], 28, 28, 1)
X_train.shape
###Output
_____no_output_____
###Markdown
And it's more convenient to work with `ndarray`s of floats, instead of integers.
###Code
X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
###Output
_____no_output_____
###Markdown
We also want to normalize the pixel values to range from 0 to 1 (instead of 0 to 255),
###Code
X_train = X_train / 255
X_test = X_test / 255
###Output
_____no_output_____
###Markdown
And finally, one hot-encode the output labels.
###Code
y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)
num_classes = y_test.shape[1]
y_train[10]
###Output
_____no_output_____
###Markdown
3. Training Now that all the preprocessing steps were taken care of, we are ready to create a tentative model. The following code defines a model with the following layers, from input to output:- Convolutional layer, 30 filters of size 5x5.- ReLU- 2x2 MaxPooling layer- Fully connected layer with 128 neurons- ReLU- Fully connected layer with 10 neurons- Softmax
###Code
def base_model():
# create model
model = Sequential()
model.add(Conv2D(30, (5, 5), input_shape=(28, 28, 1), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dense(num_classes, activation='softmax'))
# Compile model
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
return model
###Output
_____no_output_____
###Markdown
Note that the convolutional layer was implemented using a [`Conv2D` layer](https://keras.io/layers/convolutional/conv2d) and the max pooling layer was implemented using a [`MaxPooling2D` layer](https://keras.io/layers/pooling/maxpooling2d). Take a look at Keras help page for these layers to obtain more information about them. Also, note that in order for Keras to connect the output of the MaxPooling layer (which has shape `(batch, width, heigth, channels)`) to the fully connected layer, it was necessary to first use a [`Flatten` layer](https://keras.io/layers/core/flatten), which "flattens" its input, squashing all dimensions aside from the batch dimension together. For example, if the input has shape `(32, 28, 28, 3)`, the output will have shape `(32,2352)`. Now that we defined the architecture, we can train it with the following cell.
###Code
# build the model
model = base_model()
# Fit the model
tb = TensorBoard(log_dir='./logs/initial_setting')
history = model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=15, batch_size=1024, callbacks=[tb])
###Output
_____no_output_____
###Markdown
Try different architectures.
###Code
def more_layers_model():
model = Sequential()
model.add(Conv2D(30, (5, 5), input_shape=(28, 28, 1), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Conv2D(30, (5, 5), input_shape=(28, 28, 1), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dense(num_classes, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
return model
def more_filters_model():
model = Sequential()
model.add(Conv2D(100, (5, 5), input_shape=(28, 28, 1), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dense(num_classes, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
return model
def more_neurons_model():
model = Sequential()
model.add(Conv2D(30, (5, 5), input_shape=(28, 28, 1), activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(1024, activation='relu'))
model.add(Dense(num_classes, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
return model
def bnorm_model():
model = Sequential()
model.add(Conv2D(30, (5, 5), input_shape=(28, 28, 1), activation='relu'))
model.add(BatchNormalization())
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(BatchNormalization())
model.add(Dense(num_classes, activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
return model
###Output
_____no_output_____
###Markdown
Train all of them and compare the results using [TensorBoard](https://www.tensorflow.org/guide/summaries_and_tensorboard). To see the tensorboard results, open a terminal in the directory where this notebook is, and type `tensorboard --logdir=logs`. This will start the TensorBoard server and show you its address. Follow that address to access its web interface.Note: if you're running a notebook from the cloud, follow the instructions inside the `Instructions` folder about how to use TensorBoard instead.
###Code
model_names = ['more_layers_model', 'more_filters_model', 'more_neurons_model', 'bnorm_model']
for name in model_names:
print('Training model:',name)
model = globals()[name]()
tb = TensorBoard(log_dir='./logs/'+name)
model.fit(X_train,
y_train,
validation_data=(X_test, y_test),
epochs=15,
batch_size=1024,
callbacks=[tb],
verbose=0)
print('Done!')
###Output
_____no_output_____
###Markdown
Choose the best one and train longer. Here we also use [early stopping](https://en.wikipedia.org/wiki/Early_stoppingValidation-based_early_stopping).
###Code
model = base_model()
# Set callbacks
tb = TensorBoard(log_dir='./logs/final_model')
estop = EarlyStopping(monitor='val_acc', patience=5)
# Train the model
model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=50, batch_size=1024, callbacks=[tb, estop])
###Output
_____no_output_____
###Markdown
4. Assessment Once we found our best model, we can evaluate its performance on the test set. In our case, we would like to compute its accuracy:
###Code
scores = model.evaluate(X_test, y_test, verbose=0)
print("Test accuracy: %.2f%%" % (scores[1]*100))
temp = model.predict(X_test)
y_pred = np.argmax(temp, axis=1)
y_true = np.argmax(y_test, axis=1)
confusion_matrix(y_true, y_pred)
###Output
_____no_output_____ |
data_analysis/Surveys/analyze_form_learn.ipynb | ###Markdown
Analyse survey Imports
###Code
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 16 13:02:17 2018
@author: macchini
"""
%load_ext autoreload
%autoreload 2
import os,sys
sys.path.insert(1, os.path.join(sys.path[0], '..'))
import my_plots
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mpl
import utils
from numpy.random import seed
from numpy.random import randn
from scipy.stats import kruskal
from collections import Counter
from matplotlib.pylab import savefig
# plot settings
lw = 1.5
fs = 13
params = {
'axes.labelsize': fs,
'font.size': fs,
'legend.fontsize': fs,
'xtick.labelsize': fs,
'ytick.labelsize': fs,
'text.usetex': False,
'figure.figsize': [4, 4],
'boxplot.boxprops.linewidth' : lw,
'boxplot.whiskerprops.linewidth' : lw,
'boxplot.capprops.linewidth' : lw,
'boxplot.medianprops.linewidth' : lw,
'text.usetex' : True,
'font.family' : 'serif',
}
mpl.rcParams.update(params)
###Output
_____no_output_____
###Markdown
Load file and create dataframe
###Code
folder = './Data'
csv = 'Bidirectional Interface - learning.csv'
answers_df = pd.read_csv(os.path.join(folder, csv))
answers_df_sim = answers_df.iloc[[8,9,11,12,17,18,19,20,21]]
answers_df_sim
answers_df_hw = answers_df.iloc[[13,14,15,16]]
# answers_df_sim
###Output
_____no_output_____
###Markdown
Separate questions
###Code
data_sim = {}
data_hw = {}
age = 'Age'
gender = 'Gender'
experience_controller = 'How experienced are you with the use of remote controllers?'
experience_controller_drone = 'How experienced are you with the use of remote controllers for controlling drones?'
easier_first = 'Which interface was easier to use in the FIRST run?'
easier_last = 'Which interface was easier to use in the LAST run?'
prefered = 'Which interface did you prefer?'
why = 'Why?'
feedback = 'Please give your personal feedback/impressions'
questions = [age, gender, experience_controller, experience_controller_drone, easier_first, easier_last, prefered, why, feedback]
for q in questions:
data_sim[q] = answers_df_sim[q].values
for q in questions:
data_hw[q] = answers_df_hw[q].values
###Output
_____no_output_____
###Markdown
Compute mean and average
###Code
def compute_stats(data):
stats = {}
mean_index = 0
std_index = 1
for q in [age, experience_controller, experience_controller_drone]:
stats[q] = [0, 0]
stats[q][mean_index] = np.mean(data[q])
stats[q][std_index] = np.std(data[q])
return stats
stats_sim = compute_stats(data_sim)
stats_hw = compute_stats(data_hw)
###Output
_____no_output_____
###Markdown
Results
###Code
# Stats (similarly for stats_hw for the hardware experiments) is a nested dictionnary containing the mean and std for each question of the survey, separated depending on the interface (remote or motion) and run (first or last)
# data (similarly data_hw) can be used to create boxplot for the distribution of answers.
resp_data = {}
resp_data[easier_first] = Counter(data_sim[easier_first])
resp_data[easier_last] = Counter(data_sim[easier_last])
resp_data[prefered] = Counter(data_sim[prefered])
resp_data[prefered]['Equivalent'] = 0
fig = plt.figure(figsize = (5,2))
qs = ['QL 1', 'QL 2', 'QL 3']
c1 = 'gray'
c2 = 'b'
c3 = 'r'
c = [c1, c2, c3]
for jdx, j in enumerate(resp_data):
ax = fig.add_subplot(1, len(resp_data), 1+jdx)
options = []
resp = []
for i in sorted(resp_data[j]):
options.append(i)
resp.append(resp_data[j][i])
for idx, i in enumerate(options):
lab = i if 'We' not in i else 'Wearable'
if 'Re' in i:
lab = 'Remote'
# lab = i if 'Remote' in i else 'Remote'
plt.bar(1+idx, resp[idx], label = lab, color = c[idx])
if jdx==0:
plt.legend(loc = 'upper left')
plt.yticks([0, 2, 4, 6, 8, 10])
else:
plt.yticks([0, 2, 4, 6, 8, 10], ['','','','','',''])
if jdx==1:
plt.title('Responses')
ax.yaxis.grid()
plt.ylim(0,10)
plt.xticks([2],[qs[jdx]], axes=ax)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
savefig('learn_quest.pdf', bbox_inches='tight')
resp_data = {}
resp_data[easier_first] = Counter(data_hw[easier_first])
resp_data[easier_last] = Counter(data_hw[easier_last])
resp_data[prefered] = Counter(data_hw[prefered])
resp_data[prefered]['Equvalent'] = 0
fig = plt.figure(figsize = (12,4))
qs = ['QL 1', 'QL 2', 'QL 3']
c1 = 'gray'
c2 = 'b'
c3 = 'r'
c = [c1, c2, c3]
for jdx, j in enumerate(resp_data):
ax = fig.add_subplot(1, len(resp_data), 1+jdx)
options = []
resp = []
for i in sorted(resp_data[j]):
options.append(i)
resp.append(resp_data[j][i])
for idx, i in enumerate(options):
lab = i if 'We' not in i else 'Motion-based'
plt.bar(1+idx, resp[idx], label = lab, color = c[idx])
if jdx==0:
plt.legend(loc = 'upper left')
plt.grid()
plt.ylim(0,10)
plt.xticks([2],[qs[jdx]], axes=ax)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
plt.ylabel('Responses')
savefig('learn_quest.pdf', bbox_inches='tight')
###Output
_____no_output_____
###Markdown
Interesting subjective feedback Questionnaires
###Code
why_answers = data_sim[why]
print('SIMULATION')
print('-----------')
print(why)
print('-----------')
print()
for w in why_answers:
print(w)
print()
print('-----------')
print(feedback)
print('-----------')
print()
feed_answers = data_sim[feedback]
for f in feed_answers:
print(f)
print()
###Output
SIMULATION
-----------
Why?
-----------
more fun, more intuitive (I did not have to think to the right handle to move as from the beginning)
The joystick had a mapping of the inputs/outputs which is not what I am used to with drones. Therefore, I needed to get used to it and then the task got easier. Instead, with the wearable, I expected immediately that if I moved my hand up the drone would go up etc.
I have much more experience with the remote control through video games and it was the first time I used motion control.
I had an easier time understanding the controls of the wearable than I did of the video game controller
Because with the wearable you could make much more smooth and precise movement than the remote controller which it felt like drone kept overshooting the position I wanted it to be in.
It seemed to be more natural after a while
It's easier to use it and to learn. The movements are smoother
Wearable is much more fun to use
more intuitive and more fun
-----------
Please give your personal feedback/impressions
-----------
I think that the gain of the wearable can be tuned better, but it seems very promosing :)
In my opinion, the main problem related to the wearable interface is getting used to the clutch and how its use impacts the task completion.
in the experiment, give more feedback about passing the gates. If a gate is successfully crossed, maybe change its colour to green
I never got the hang of the controller.
I found the task easier with multiple tries and this made using the remote easier as I used it after the wearable. I think the wearable is much more accurate and intuitive but if one wanted to maximize the speed at which you could complete the course, I believe the remote control would be easier with more practice, as you don`t need to keep re-clicking.
I prefer the wearable but it needs some effort for training and then it seems better choice
The test starts on the right and my impression was that it was more difficut to controle it in the sides
Wearable seemed more precise and definitely more fun, but a bit too tiring for me
the controller had some inertia that took some mental effort to take into account. The wearable controller is cool but I to move the drone on longer distances I had to do repetitive movements which took some time
###Markdown
Need to check out these Backup - pie charts
###Code
def plot_pies(data):
plt.figure(figsize = (12,12))
gender_pie_data = Counter(data[gender])
easier_first_pie_data = Counter(data[easier_first])
easier_last_pie_data = Counter(data[easier_last])
prefered_pie_data = Counter(data[prefered])
# ax1 = plt.subplot(221)
# ax1.pie(gender_pie_data.values(), labels=gender_pie_data.keys(), autopct='%1.1f%%', startangle=90)
# ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
# ax1.set_title(gender)
ax1 = plt.subplot(231)
ax1.pie(easier_first_pie_data.values(), labels=easier_first_pie_data.keys(), autopct='%1.1f%%', startangle=90)
ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
ax1.set_title(easier_first)
ax1 = plt.subplot(232)
ax1.pie(easier_last_pie_data.values(), labels=easier_last_pie_data.keys(), autopct='%1.1f%%', startangle=90)
ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
ax1.set_title(easier_last)
ax1 = plt.subplot(233)
ax1.pie(prefered_pie_data.values(), labels=prefered_pie_data.keys(), autopct='%1.1f%%', startangle=90)
ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
ax1.set_title(prefered)
plt.show()
plot_pies(data_sim)
plot_pies(data_hw)
# plot settings
lw = 1.5
fs = 13
params = {
'axes.labelsize': fs,
'font.size': fs,
'legend.fontsize': fs,
'xtick.labelsize': fs,
'ytick.labelsize': fs,
'text.usetex': False,
'figure.figsize': [4, 4],
'boxplot.boxprops.linewidth' : lw,
'boxplot.whiskerprops.linewidth' : lw,
'boxplot.capprops.linewidth' : lw,
'boxplot.medianprops.linewidth' : lw,
'text.usetex' : True,
'font.family' : 'serif',
}
mpl.rcParams.update(params)
w
###Output
_____no_output_____
###Markdown
Analyse survey Imports
###Code
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 16 13:02:17 2018
@author: macchini
"""
%load_ext autoreload
%autoreload 2
import os,sys
sys.path.insert(1, os.path.join(sys.path[0], '..'))
import my_plots
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mpl
import utils
from numpy.random import seed
from numpy.random import randn
from scipy.stats import kruskal
from statistics import print_p
from matplotlib.pylab import savefig
###Output
The autoreload extension is already loaded. To reload it, use:
%reload_ext autoreload
###Markdown
Load file and create dataframe
###Code
folder = './Data'
files = os.listdir(folder)
csv = 'NASA_TLX_learn_first (Risposte) - Risposte del modulo 1.csv'
answers_df = pd.read_csv(os.path.join(folder, csv))
# Separate hardware and simulation experiments
answers_df_hw = answers_df[answers_df['subject number'] >= 100]
answers_df_hw = answers_df_hw[answers_df_hw['subject number'] != 103]
answers_df = answers_df[answers_df['subject number'] < 100]
###Output
_____no_output_____
###Markdown
Separate dataframe depending on interface/run
###Code
types = ['remote-first', 'remote-last', 'motion-first', 'motion-last']
# Separate answers depending on interface and run
answers = {}
answers[types[0]] = answers_df[answers_df['Interface'] == 'Remote']
answers[types[0]] = answers[types[0]][answers[types[0]]['Run'] == 'First']
answers[types[1]] = answers_df[answers_df['Interface'] == 'Remote']
answers[types[1]] = answers[types[1]][answers[types[1]]['Run'] == 'Last']
answers[types[2]] = answers_df[answers_df['Interface'] == 'Motion']
answers[types[2]] = answers[types[2]][answers[types[2]]['Run'] == 'First']
answers[types[3]] = answers_df[answers_df['Interface'] == 'Motion']
answers[types[3]] = answers[types[3]][answers[types[3]]['Run'] == 'Last']
answers_hw = {}
answers_hw[types[0]] = answers_df_hw[answers_df_hw['Interface'] == 'Remote']
answers_hw[types[0]] = answers_hw[types[0]][answers_hw[types[0]]['Run'] == 'First']
answers_hw[types[1]] = answers_df_hw[answers_df_hw['Interface'] == 'Remote']
answers_hw[types[1]] = answers_hw[types[1]][answers_hw[types[1]]['Run'] == 'Last']
answers_hw[types[2]] = answers_df_hw[answers_df_hw['Interface'] == 'Motion']
answers_hw[types[2]] = answers_hw[types[2]][answers_hw[types[2]]['Run'] == 'First']
answers_hw[types[3]] = answers_df_hw[answers_df_hw['Interface'] == 'Motion']
answers_hw[types[3]] = answers_hw[types[3]][answers_hw[types[3]]['Run'] == 'Last']
###Output
_____no_output_____
###Markdown
Separate questions
###Code
data_NASA = {}
data_NASA_hw = {}
mentally_demanding = 'How mentally demanding was the test?'
physically_demanding = 'How physically demanding was the test?'
pace = 'How hurried or rushed was the pace of the task?'
successful = 'How successful were you in accomplishing what you were asked to do?'
insecure = 'How insecure, discouraged, irritated, stresses, and annoyed were you?'
questions_NASA = [mentally_demanding, physically_demanding, pace, successful, insecure]
for i in types:
data_NASA[i] = {}
data_NASA_hw[i] = {}
for q in questions_NASA:
data_NASA[i][q] = answers[i][q].values
data_NASA_hw[i][q] = answers_hw[i][q].values
print(data_NASA_hw)
###Output
{'remote-first': {'How mentally demanding was the test?': array([1, 1, 2, 3]), 'How physically demanding was the test?': array([1, 1, 1, 1]), 'How hurried or rushed was the pace of the task?': array([1, 1, 1, 1]), 'How successful were you in accomplishing what you were asked to do?': array([4, 5, 4, 4]), 'How insecure, discouraged, irritated, stresses, and annoyed were you?': array([1, 1, 1, 2])}, 'remote-last': {'How mentally demanding was the test?': array([1, 2, 2, 2]), 'How physically demanding was the test?': array([1, 1, 1, 1]), 'How hurried or rushed was the pace of the task?': array([1, 1, 1, 1]), 'How successful were you in accomplishing what you were asked to do?': array([5, 3, 4, 5]), 'How insecure, discouraged, irritated, stresses, and annoyed were you?': array([1, 1, 1, 1])}, 'motion-first': {'How mentally demanding was the test?': array([1, 1, 4, 1]), 'How physically demanding was the test?': array([2, 1, 1, 1]), 'How hurried or rushed was the pace of the task?': array([1, 1, 2, 1]), 'How successful were you in accomplishing what you were asked to do?': array([5, 5, 3, 4]), 'How insecure, discouraged, irritated, stresses, and annoyed were you?': array([1, 1, 3, 1])}, 'motion-last': {'How mentally demanding was the test?': array([1, 1, 3, 1]), 'How physically demanding was the test?': array([2, 1, 2, 2]), 'How hurried or rushed was the pace of the task?': array([1, 1, 2, 1]), 'How successful were you in accomplishing what you were asked to do?': array([4, 5, 4, 5]), 'How insecure, discouraged, irritated, stresses, and annoyed were you?': array([1, 1, 2, 1])}}
###Markdown
Compute mean and average
###Code
stats_NASA = {}
stats_NASA_hw = {}
mean_index = 0
std_index = 1
for i in types:
stats_NASA[i] = {}
stats_NASA_hw[i] = {}
for q in questions_NASA:
stats_NASA[i][q] = [0, 0]
stats_NASA[i][q][mean_index] = np.mean(data_NASA[i][q])
stats_NASA[i][q][std_index] = np.std(data_NASA[i][q])
stats_NASA_hw[i][q] = [0, 0]
stats_NASA_hw[i][q][mean_index] = np.mean(data_NASA_hw[i][q])
stats_NASA_hw[i][q][std_index] = np.std(data_NASA_hw[i][q])
print(stats_NASA)
###Output
{'remote-first': {'How mentally demanding was the test?': [3.0, 1.0954451150103321], 'How physically demanding was the test?': [1.1, 0.3], 'How hurried or rushed was the pace of the task?': [2.2, 1.2489995996796797], 'How successful were you in accomplishing what you were asked to do?': [3.3, 1.2688577540449522], 'How insecure, discouraged, irritated, stresses, and annoyed were you?': [2.1, 1.044030650891055]}, 'remote-last': {'How mentally demanding was the test?': [2.7, 0.9], 'How physically demanding was the test?': [1.1, 0.3], 'How hurried or rushed was the pace of the task?': [2.4, 1.42828568570857], 'How successful were you in accomplishing what you were asked to do?': [3.5, 0.806225774829855], 'How insecure, discouraged, irritated, stresses, and annoyed were you?': [1.7, 1.004987562112089]}, 'motion-first': {'How mentally demanding was the test?': [2.1, 0.5385164807134505], 'How physically demanding was the test?': [1.7, 0.7810249675906655], 'How hurried or rushed was the pace of the task?': [1.7, 0.9], 'How successful were you in accomplishing what you were asked to do?': [3.4, 0.8], 'How insecure, discouraged, irritated, stresses, and annoyed were you?': [1.6, 0.66332495807108]}, 'motion-last': {'How mentally demanding was the test?': [1.7, 0.6403124237432849], 'How physically demanding was the test?': [1.6, 1.0198039027185568], 'How hurried or rushed was the pace of the task?': [1.8, 1.2489995996796797], 'How successful were you in accomplishing what you were asked to do?': [3.8, 0.7483314773547882], 'How insecure, discouraged, irritated, stresses, and annoyed were you?': [1.2, 0.4]}}
###Markdown
Results Stats (similarly for stats_hw for the hardware experiments) is a nested dictionnary containing the mean and std for each question of the survey, separated depending on the interface (remote or motion) and run (first or last)data (similarly data_hw) can be used to create boxplot for the distribution of answers.
###Code
def t_test_kruskal(X, Y):
# Kruskal-Wallis H-test
# seed the random number generator
seed(1)
# compare samples
stat, p = kruskal(X, Y)
return [stat, p]
for idx,i in enumerate(types):
for j in types[idx+1:]:
print()
for q in questions_NASA:
if i != j:
# also, compare only first-last for same interface or first-first, last-last for different ones
if ('first' in i and 'first' in j) or ('last' in i and 'last' in j) or ('remote' in i and 'remote' in j) or ('motion' in i and 'motion' in j):
t, p = t_test_kruskal(data_NASA[i][q],data_NASA[j][q])
print(i,j,q)
print_p(p)
plt.figure(figsize=(16,4))
vals = []
errors = []
for idx, s in enumerate(stats_NASA):
# print(stats[s])
means = [stats_NASA[s][q][0] for q in questions_NASA]
stds = [stats_NASA[s][q][1] for q in questions_NASA]
# print(means)
# print(stds)
ax = plt.subplot(141+idx)
ax.bar([0, 1, 2, 3, 4],
means,
yerr=stds)
plt.title(s)
vals.append(means[0:2])
errors.append(stds[0:2])
lighter = 0.4
c1 = [0,0,1]
c2 = [lighter,lighter,1]
c3 = [1,0,0]
c4 = [1,lighter,lighter]
col = [c1, c2, c3, c4]
plt.figure(figsize=(2,2))
ax = plt.subplot(111)
ax = my_plots.bar_multi(vals, errors, legend = ['R-1','R-5','M-1','M-5'], xlabels = ['Q 1', 'Q 2'], w =0.15, xlim = [0.5,2.5], yticks = [1,2,3,4,5], save = True, where = 'learn_NASA.pdf', colors = col)
plt.yticks([1,2,3,4,5])
plt.xlim(0.5,2.5)
ax.xaxis.grid()
savefig('learn_NASA.pdf', bbox_inches='tight')
###Output
[[0, 0, 1], [0.4, 0.4, 1], [1, 0, 0], [1, 0.4, 0.4]]
###Markdown
Interesting statistics (see below) remote-first motion-first How physically demanding was the test? p = 0.0488888176268915 remote-last motion-last How physically demanding was the test? p = 0.23390621098854886 remote-last motion-last How mentally demanding was the test? p = 0.01913961955875495 motion-first remote-first How mentally demanding was the test? p = 0.03344653009997241
###Code
for idx,i in enumerate(types):
for j in types[idx+1:]:
print()
for q in questions_NASA:
if i != j:
# also, compare only first-last for same interface or first-first, last-last for different ones
if ('first' in i and 'first' in j) or ('last' in i and 'last' in j) or ('remote' in i and 'remote' in j) or ('motion' in i and 'motion' in j):
t, p = t_test_kruskal(data_NASA[i][q],data_NASA_hw[j][q])
print(i,j,q)
print_p(p)
plt.figure(figsize=(16,4))
vals = []
errors = []
for idx, s in enumerate(stats_NASA_hw):
# print(stats[s])
means = [stats_NASA_hw[s][q][0] for q in questions_NASA]
stds = [stats_NASA_hw[s][q][1] for q in questions_NASA]
# print(means)
# print(stds)
ax = plt.subplot(141+idx)
ax.bar([0, 1, 2, 3, 4],
means,
yerr=stds)
plt.title(s)
vals.append(means)
errors.append(stds)
lighter = 0.4
c1 = [0,0,1]
c2 = [lighter,lighter,1]
c3 = [1,0,0]
c4 = [1,lighter,lighter]
col = [c1, c2, c3, c4]
plt.figure(figsize=(2,3))
ax = plt.subplot(111)
ax = my_plots.bar_multi(vals, errors, legend = ['R-1','R-5','M-1','M-5'], xlabels = ['Q 1', 'Q 2'], w =0.15, xlim = [0.5,2.5], yticks = [1,2,3,4,5], save = True, where = 'learn_NASA.pdf', colors = col)
plt.yticks([1,2,3,4,5])
plt.xlim(0.5,2.5)
ax.xaxis.grid()
###Output
[[0, 0, 1], [0.4, 0.4, 1], [1, 0, 0], [1, 0.4, 0.4]]
###Markdown
FINAL PLOTS
###Code
resp_data = {}
resp_data[easier_first] = Counter(data_sim[easier_first])
resp_data[easier_last] = Counter(data_sim[easier_last])
resp_data[prefered] = Counter(data_sim[prefered])
resp_data[prefered]['Equivalent'] = 0
fig = plt.figure(figsize = (7,2))
qs = ['QL 1', 'QL 2', 'QL 3']
c1 = 'gray'
c2 = 'b'
c3 = 'r'
c = [c1, c2, c3]
for jdx, j in enumerate(resp_data):
ax = fig.add_subplot(1, 4, 1+jdx)
options = []
resp = []
for i in sorted(resp_data[j]):
options.append(i)
resp.append(resp_data[j][i])
for idx, i in enumerate(options):
lab = i if 'We' not in i else 'Wearable'
if 'Re' in i:
lab = 'Remote'
# lab = i if 'Remote' in i else 'Remote'
plt.bar(1+idx, resp[idx], label = lab, color = c[idx])
if jdx==0:
# plt.legend(loc = 'upper left')
plt.yticks([2, 4, 6, 8, 10])
plt.title('Simulation')
else:
plt.yticks([2, 4, 6, 8, 10], ['','','','','',''])
if jdx==1:
pass
# plt.title('Responses')
ax.yaxis.grid()
plt.ylim(0,10)
plt.xticks([2],[qs[jdx]], axes=ax)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
vals = []
errors = []
for idx, s in enumerate(stats_NASA):
# print(stats[s])
means = [stats_NASA[s][q][0] for q in questions_NASA]
stds = [stats_NASA[s][q][1] for q in questions_NASA]
# print(means)
# print(stds)
# ax = plt.subplot(141+idx)
# ax.bar([0, 1, 2, 3, 4],
# means,
# yerr=stds)
# plt.title(s)
vals.append(means[0:2])
errors.append(stds[0:2])
lighter = 0.4
c1 = [0,0,1]
c2 = [lighter,lighter,1]
c3 = [1,0,0]
c4 = [1,lighter,lighter]
col = [c1, c2, c3, c4]
ax = plt.subplot(1, 4, 4)
ax = my_plots.bar_multi(vals, errors, ax = ax, xlabels = ['Q 1', 'Q 2'], w =0.15, xlim = [0.5,2.5], yticks = [1,2,3,4,5], save = True, where = 'learn_NASA.pdf', colors = col)
plt.yticks([1,2,3,4,5])
plt.xlim(0.5,2.5)
ax.xaxis.grid()
savefig('learn_quest.pdf', bbox_inches='tight')
resp_data = {}
resp_data[easier_first] = Counter(data_hw[easier_first])
resp_data[easier_last] = Counter(data_hw[easier_last])
resp_data[prefered] = Counter(data_hw[prefered])
resp_data[easier_first]['Equivalent'] = 1
resp_data[easier_first]['Remote controller'] = 2
resp_data[easier_first]['Wearable'] = 1
resp_data[easier_last]['Equivalent'] = 1
resp_data[easier_last]['Remote controller'] = 1
resp_data[easier_last]['Wearable'] = 2
resp_data[prefered]['Equivalent'] = 0
resp_data[prefered]['Remote controller'] = 1
resp_data[prefered]['Werable'] = 3
fig = plt.figure(figsize = (7,2))
qs = ['QL 1', 'QL 2', 'QL 3']
c1 = 'gray'
c2 = 'b'
c3 = 'r'
c = [c1, c2, c3]
for jdx, j in enumerate(resp_data):
ax = fig.add_subplot(1, 4, 1+jdx)
options = []
resp = []
for i in sorted(resp_data[j]):
options.append(i)
resp.append(resp_data[j][i])
for idx, i in enumerate(options):
lab = i if 'We' not in i else 'Wearable'
if 'Re' in i:
lab = 'Remote'
# lab = i if 'Remote' in i else 'Remote'
plt.bar(1+idx, resp[idx], label = lab, color = c[idx])
if jdx==0:
plt.legend(loc = 'upper left')
plt.title('Hardware')
plt.yticks([2, 4, 6, 8, 10])
else:
plt.yticks([2, 4, 6, 8, 10], ['','','',''])
if jdx==1:
pass
# plt.title('Responses')
ax.yaxis.grid()
plt.ylim(0,10)
plt.xticks([2],[qs[jdx]], axes=ax)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
vals = []
errors = []
for idx, s in enumerate(stats_NASA_hw):
# print(stats[s])
means = [stats_NASA_hw[s][q][0] for q in questions_NASA]
stds = [stats_NASA_hw[s][q][1] for q in questions_NASA]
# print(means)
# print(stds)
# ax = plt.subplot(141+idx)
# ax.bar([0, 1, 2, 3, 4],
# means,
# yerr=stds)
# plt.title(s)
vals.append(means[0:2])
errors.append(stds[0:2])
lighter = 0.4
c1 = [0,0,1]
c2 = [lighter,lighter,1]
c3 = [1,0,0]
c4 = [1,lighter,lighter]
col = [c1, c2, c3, c4]
ax = plt.subplot(1, 4, 4)
ax = my_plots.bar_multi(vals, errors, legend = ['R1','R5','W1','W5'], ax = ax, xlabels = ['Q 1', 'Q 2'], w =0.15, xlim = [0.5,2.5], yticks = [1,2,3,4,5], save = True, where = 'learn_NASA.pdf', colors = col)
plt.yticks([1,2,3,4,5])
plt.xlim(0.5,2.5)
ax.xaxis.grid()
savefig('learn_quest_HW.pdf', bbox_inches='tight')
print(resp_data)
# print(stats_NASA_hw)
data_hw
###Output
_____no_output_____
###Markdown
Analyse survey Imports
###Code
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 16 13:02:17 2018
@author: macchini
"""
%load_ext autoreload
%autoreload 2
import os,sys
sys.path.insert(1, os.path.join(sys.path[0], '..'))
import my_plots
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mpl
import utils
from numpy.random import seed
from numpy.random import randn
from scipy.stats import kruskal
from collections import Counter
from matplotlib.pylab import savefig
# plot settings
lw = 1.5
fs = 13
params = {
'axes.labelsize': fs,
'font.size': fs,
'legend.fontsize': fs,
'xtick.labelsize': fs,
'ytick.labelsize': fs,
'text.usetex': False,
'figure.figsize': [4, 4],
'boxplot.boxprops.linewidth' : lw,
'boxplot.whiskerprops.linewidth' : lw,
'boxplot.capprops.linewidth' : lw,
'boxplot.medianprops.linewidth' : lw,
'text.usetex' : True,
'font.family' : 'serif',
}
mpl.rcParams.update(params)
###Output
_____no_output_____
###Markdown
Load file and create dataframe
###Code
folder = './Data'
csv = 'Bidirectional Interface - learning.csv'
answers_df = pd.read_csv(os.path.join(folder, csv))
answers_df_sim = answers_df.iloc[[8,9,11,12,17,18,19,20,21]]
answers_df_sim
answers_df_hw = answers_df.iloc[[13,14,15,16]]
# answers_df_sim
###Output
_____no_output_____
###Markdown
Separate questions
###Code
data_sim = {}
data_hw = {}
age = 'Age'
gender = 'Gender'
experience_controller = 'How experienced are you with the use of remote controllers?'
experience_controller_drone = 'How experienced are you with the use of remote controllers for controlling drones?'
easier_first = 'Which interface was easier to use in the FIRST run?'
easier_last = 'Which interface was easier to use in the LAST run?'
prefered = 'Which interface did you prefer?'
why = 'Why?'
feedback = 'Please give your personal feedback/impressions'
questions = [age, gender, experience_controller, experience_controller_drone, easier_first, easier_last, prefered, why, feedback]
for q in questions:
data_sim[q] = answers_df_sim[q].values
for q in questions:
data_hw[q] = answers_df_hw[q].values
###Output
_____no_output_____
###Markdown
Compute mean and average
###Code
def compute_stats(data):
stats = {}
mean_index = 0
std_index = 1
for q in [age, experience_controller, experience_controller_drone]:
stats[q] = [0, 0]
stats[q][mean_index] = np.mean(data[q])
stats[q][std_index] = np.std(data[q])
return stats
stats_sim = compute_stats(data_sim)
stats_hw = compute_stats(data_hw)
###Output
_____no_output_____
###Markdown
Results
###Code
# Stats (similarly for stats_hw for the hardware experiments) is a nested dictionnary containing the mean and std for each question of the survey, separated depending on the interface (remote or motion) and run (first or last)
# data (similarly data_hw) can be used to create boxplot for the distribution of answers.
resp_data = {}
resp_data[easier_first] = Counter(data_sim[easier_first])
resp_data[easier_last] = Counter(data_sim[easier_last])
resp_data[prefered] = Counter(data_sim[prefered])
resp_data[prefered]['Equivalent'] = 0
fig = plt.figure(figsize = (5,2))
qs = ['QL 1', 'QL 2', 'QL 3']
c1 = 'gray'
c2 = 'b'
c3 = 'r'
c = [c1, c2, c3]
for jdx, j in enumerate(resp_data):
ax = fig.add_subplot(1, len(resp_data), 1+jdx)
options = []
resp = []
for i in sorted(resp_data[j]):
options.append(i)
resp.append(resp_data[j][i])
for idx, i in enumerate(options):
lab = i if 'We' not in i else 'Wearable'
if 'Re' in i:
lab = 'Remote'
# lab = i if 'Remote' in i else 'Remote'
plt.bar(1+idx, resp[idx], label = lab, color = c[idx])
if jdx==0:
plt.legend(loc = 'upper left')
plt.yticks([0, 2, 4, 6, 8, 10])
else:
plt.yticks([0, 2, 4, 6, 8, 10], ['','','','','',''])
if jdx==1:
plt.title('Responses')
ax.yaxis.grid()
plt.ylim(0,10)
plt.xticks([2],[qs[jdx]], axes=ax)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
savefig('learn_quest.pdf', bbox_inches='tight')
resp_data = {}
resp_data[easier_first] = Counter(data_hw[easier_first])
resp_data[easier_last] = Counter(data_hw[easier_last])
resp_data[prefered] = Counter(data_hw[prefered])
resp_data[prefered]['Equvalent'] = 0
fig = plt.figure(figsize = (12,4))
qs = ['QL 1', 'QL 2', 'QL 3']
c1 = 'gray'
c2 = 'b'
c3 = 'r'
c = [c1, c2, c3]
for jdx, j in enumerate(resp_data):
ax = fig.add_subplot(1, len(resp_data), 1+jdx)
options = []
resp = []
for i in sorted(resp_data[j]):
options.append(i)
resp.append(resp_data[j][i])
for idx, i in enumerate(options):
lab = i if 'We' not in i else 'Motion-based'
plt.bar(1+idx, resp[idx], label = lab, color = c[idx])
if jdx==0:
plt.legend(loc = 'upper left')
plt.grid()
plt.ylim(0,10)
plt.xticks([2],[qs[jdx]], axes=ax)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
plt.ylabel('Responses')
savefig('learn_quest.pdf', bbox_inches='tight')
###Output
_____no_output_____
###Markdown
Interesting subjective feedback Questionnaires
###Code
why_answers = data_sim[why]
print('SIMULATION')
print('-----------')
print(why)
print('-----------')
print()
for w in why_answers:
print(w)
print()
print('-----------')
print(feedback)
print('-----------')
print()
feed_answers = data_sim[feedback]
for f in feed_answers:
print(f)
print()
###Output
SIMULATION
-----------
Why?
-----------
more fun, more intuitive (I did not have to think to the right handle to move as from the beginning)
The joystick had a mapping of the inputs/outputs which is not what I am used to with drones. Therefore, I needed to get used to it and then the task got easier. Instead, with the wearable, I expected immediately that if I moved my hand up the drone would go up etc.
I have much more experience with the remote control through video games and it was the first time I used motion control.
I had an easier time understanding the controls of the wearable than I did of the video game controller
Because with the wearable you could make much more smooth and precise movement than the remote controller which it felt like drone kept overshooting the position I wanted it to be in.
It seemed to be more natural after a while
It's easier to use it and to learn. The movements are smoother
Wearable is much more fun to use
more intuitive and more fun
-----------
Please give your personal feedback/impressions
-----------
I think that the gain of the wearable can be tuned better, but it seems very promosing :)
In my opinion, the main problem related to the wearable interface is getting used to the clutch and how its use impacts the task completion.
in the experiment, give more feedback about passing the gates. If a gate is successfully crossed, maybe change its colour to green
I never got the hang of the controller.
I found the task easier with multiple tries and this made using the remote easier as I used it after the wearable. I think the wearable is much more accurate and intuitive but if one wanted to maximize the speed at which you could complete the course, I believe the remote control would be easier with more practice, as you don`t need to keep re-clicking.
I prefer the wearable but it needs some effort for training and then it seems better choice
The test starts on the right and my impression was that it was more difficut to controle it in the sides
Wearable seemed more precise and definitely more fun, but a bit too tiring for me
the controller had some inertia that took some mental effort to take into account. The wearable controller is cool but I to move the drone on longer distances I had to do repetitive movements which took some time
###Markdown
Need to check out these Backup - pie charts
###Code
def plot_pies(data):
plt.figure(figsize = (12,12))
gender_pie_data = Counter(data[gender])
easier_first_pie_data = Counter(data[easier_first])
easier_last_pie_data = Counter(data[easier_last])
prefered_pie_data = Counter(data[prefered])
# ax1 = plt.subplot(221)
# ax1.pie(gender_pie_data.values(), labels=gender_pie_data.keys(), autopct='%1.1f%%', startangle=90)
# ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
# ax1.set_title(gender)
ax1 = plt.subplot(231)
ax1.pie(easier_first_pie_data.values(), labels=easier_first_pie_data.keys(), autopct='%1.1f%%', startangle=90)
ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
ax1.set_title(easier_first)
ax1 = plt.subplot(232)
ax1.pie(easier_last_pie_data.values(), labels=easier_last_pie_data.keys(), autopct='%1.1f%%', startangle=90)
ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
ax1.set_title(easier_last)
ax1 = plt.subplot(233)
ax1.pie(prefered_pie_data.values(), labels=prefered_pie_data.keys(), autopct='%1.1f%%', startangle=90)
ax1.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
ax1.set_title(prefered)
plt.show()
plot_pies(data_sim)
plot_pies(data_hw)
# plot settings
lw = 1.5
fs = 13
params = {
'axes.labelsize': fs,
'font.size': fs,
'legend.fontsize': fs,
'xtick.labelsize': fs,
'ytick.labelsize': fs,
'text.usetex': False,
'figure.figsize': [4, 4],
'boxplot.boxprops.linewidth' : lw,
'boxplot.whiskerprops.linewidth' : lw,
'boxplot.capprops.linewidth' : lw,
'boxplot.medianprops.linewidth' : lw,
'text.usetex' : True,
'font.family' : 'serif',
}
mpl.rcParams.update(params)
w
###Output
_____no_output_____
###Markdown
Analyse survey Imports
###Code
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 16 13:02:17 2018
@author: macchini
"""
%load_ext autoreload
%autoreload 2
import os,sys
sys.path.insert(1, os.path.join(sys.path[0], '..'))
import my_plots
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mpl
import utils
from numpy.random import seed
from numpy.random import randn
from scipy.stats import kruskal
from statistics import print_p
from matplotlib.pylab import savefig
###Output
The autoreload extension is already loaded. To reload it, use:
%reload_ext autoreload
###Markdown
Load file and create dataframe
###Code
folder = './Data'
files = os.listdir(folder)
csv = 'NASA_TLX_learn_first (Risposte) - Risposte del modulo 1.csv'
answers_df = pd.read_csv(os.path.join(folder, csv))
# Separate hardware and simulation experiments
answers_df_hw = answers_df[answers_df['subject number'] >= 100]
answers_df_hw = answers_df_hw[answers_df_hw['subject number'] != 103]
answers_df = answers_df[answers_df['subject number'] < 100]
###Output
_____no_output_____
###Markdown
Separate dataframe depending on interface/run
###Code
types = ['remote-first', 'remote-last', 'motion-first', 'motion-last']
# Separate answers depending on interface and run
answers = {}
answers[types[0]] = answers_df[answers_df['Interface'] == 'Remote']
answers[types[0]] = answers[types[0]][answers[types[0]]['Run'] == 'First']
answers[types[1]] = answers_df[answers_df['Interface'] == 'Remote']
answers[types[1]] = answers[types[1]][answers[types[1]]['Run'] == 'Last']
answers[types[2]] = answers_df[answers_df['Interface'] == 'Motion']
answers[types[2]] = answers[types[2]][answers[types[2]]['Run'] == 'First']
answers[types[3]] = answers_df[answers_df['Interface'] == 'Motion']
answers[types[3]] = answers[types[3]][answers[types[3]]['Run'] == 'Last']
answers_hw = {}
answers_hw[types[0]] = answers_df_hw[answers_df_hw['Interface'] == 'Remote']
answers_hw[types[0]] = answers_hw[types[0]][answers_hw[types[0]]['Run'] == 'First']
answers_hw[types[1]] = answers_df_hw[answers_df_hw['Interface'] == 'Remote']
answers_hw[types[1]] = answers_hw[types[1]][answers_hw[types[1]]['Run'] == 'Last']
answers_hw[types[2]] = answers_df_hw[answers_df_hw['Interface'] == 'Motion']
answers_hw[types[2]] = answers_hw[types[2]][answers_hw[types[2]]['Run'] == 'First']
answers_hw[types[3]] = answers_df_hw[answers_df_hw['Interface'] == 'Motion']
answers_hw[types[3]] = answers_hw[types[3]][answers_hw[types[3]]['Run'] == 'Last']
###Output
_____no_output_____
###Markdown
Separate questions
###Code
data_NASA = {}
data_NASA_hw = {}
mentally_demanding = 'How mentally demanding was the test?'
physically_demanding = 'How physically demanding was the test?'
pace = 'How hurried or rushed was the pace of the task?'
successful = 'How successful were you in accomplishing what you were asked to do?'
insecure = 'How insecure, discouraged, irritated, stresses, and annoyed were you?'
questions_NASA = [mentally_demanding, physically_demanding, pace, successful, insecure]
for i in types:
data_NASA[i] = {}
data_NASA_hw[i] = {}
for q in questions_NASA:
data_NASA[i][q] = answers[i][q].values
data_NASA_hw[i][q] = answers_hw[i][q].values
print(data_NASA_hw)
###Output
{'remote-first': {'How mentally demanding was the test?': array([1, 1, 2, 3]), 'How physically demanding was the test?': array([1, 1, 1, 1]), 'How hurried or rushed was the pace of the task?': array([1, 1, 1, 1]), 'How successful were you in accomplishing what you were asked to do?': array([4, 5, 4, 4]), 'How insecure, discouraged, irritated, stresses, and annoyed were you?': array([1, 1, 1, 2])}, 'remote-last': {'How mentally demanding was the test?': array([1, 2, 2, 2]), 'How physically demanding was the test?': array([1, 1, 1, 1]), 'How hurried or rushed was the pace of the task?': array([1, 1, 1, 1]), 'How successful were you in accomplishing what you were asked to do?': array([5, 3, 4, 5]), 'How insecure, discouraged, irritated, stresses, and annoyed were you?': array([1, 1, 1, 1])}, 'motion-first': {'How mentally demanding was the test?': array([1, 1, 4, 1]), 'How physically demanding was the test?': array([2, 1, 1, 1]), 'How hurried or rushed was the pace of the task?': array([1, 1, 2, 1]), 'How successful were you in accomplishing what you were asked to do?': array([5, 5, 3, 4]), 'How insecure, discouraged, irritated, stresses, and annoyed were you?': array([1, 1, 3, 1])}, 'motion-last': {'How mentally demanding was the test?': array([1, 1, 3, 1]), 'How physically demanding was the test?': array([2, 1, 2, 2]), 'How hurried or rushed was the pace of the task?': array([1, 1, 2, 1]), 'How successful were you in accomplishing what you were asked to do?': array([4, 5, 4, 5]), 'How insecure, discouraged, irritated, stresses, and annoyed were you?': array([1, 1, 2, 1])}}
###Markdown
Compute mean and average
###Code
stats_NASA = {}
stats_NASA_hw = {}
mean_index = 0
std_index = 1
for i in types:
stats_NASA[i] = {}
stats_NASA_hw[i] = {}
for q in questions_NASA:
stats_NASA[i][q] = [0, 0]
stats_NASA[i][q][mean_index] = np.mean(data_NASA[i][q])
stats_NASA[i][q][std_index] = np.std(data_NASA[i][q])
stats_NASA_hw[i][q] = [0, 0]
stats_NASA_hw[i][q][mean_index] = np.mean(data_NASA_hw[i][q])
stats_NASA_hw[i][q][std_index] = np.std(data_NASA_hw[i][q])
print(stats_NASA)
###Output
{'remote-first': {'How mentally demanding was the test?': [3.0, 1.0954451150103321], 'How physically demanding was the test?': [1.1, 0.3], 'How hurried or rushed was the pace of the task?': [2.2, 1.2489995996796797], 'How successful were you in accomplishing what you were asked to do?': [3.3, 1.2688577540449522], 'How insecure, discouraged, irritated, stresses, and annoyed were you?': [2.1, 1.044030650891055]}, 'remote-last': {'How mentally demanding was the test?': [2.7, 0.9], 'How physically demanding was the test?': [1.1, 0.3], 'How hurried or rushed was the pace of the task?': [2.4, 1.42828568570857], 'How successful were you in accomplishing what you were asked to do?': [3.5, 0.806225774829855], 'How insecure, discouraged, irritated, stresses, and annoyed were you?': [1.7, 1.004987562112089]}, 'motion-first': {'How mentally demanding was the test?': [2.1, 0.5385164807134505], 'How physically demanding was the test?': [1.7, 0.7810249675906655], 'How hurried or rushed was the pace of the task?': [1.7, 0.9], 'How successful were you in accomplishing what you were asked to do?': [3.4, 0.8], 'How insecure, discouraged, irritated, stresses, and annoyed were you?': [1.6, 0.66332495807108]}, 'motion-last': {'How mentally demanding was the test?': [1.7, 0.6403124237432849], 'How physically demanding was the test?': [1.6, 1.0198039027185568], 'How hurried or rushed was the pace of the task?': [1.8, 1.2489995996796797], 'How successful were you in accomplishing what you were asked to do?': [3.8, 0.7483314773547882], 'How insecure, discouraged, irritated, stresses, and annoyed were you?': [1.2, 0.4]}}
###Markdown
Results Stats (similarly for stats_hw for the hardware experiments) is a nested dictionnary containing the mean and std for each question of the survey, separated depending on the interface (remote or motion) and run (first or last)data (similarly data_hw) can be used to create boxplot for the distribution of answers.
###Code
def t_test_kruskal(X, Y):
# Kruskal-Wallis H-test
# seed the random number generator
seed(1)
# compare samples
stat, p = kruskal(X, Y)
return [stat, p]
for idx,i in enumerate(types):
for j in types[idx+1:]:
print()
for q in questions_NASA:
if i != j:
# also, compare only first-last for same interface or first-first, last-last for different ones
if ('first' in i and 'first' in j) or ('last' in i and 'last' in j) or ('remote' in i and 'remote' in j) or ('motion' in i and 'motion' in j):
t, p = t_test_kruskal(data_NASA[i][q],data_NASA[j][q])
print(i,j,q)
print_p(p)
plt.figure(figsize=(16,4))
vals = []
errors = []
for idx, s in enumerate(stats_NASA):
# print(stats[s])
means = [stats_NASA[s][q][0] for q in questions_NASA]
stds = [stats_NASA[s][q][1] for q in questions_NASA]
# print(means)
# print(stds)
ax = plt.subplot(141+idx)
ax.bar([0, 1, 2, 3, 4],
means,
yerr=stds)
plt.title(s)
vals.append(means[0:2])
errors.append(stds[0:2])
lighter = 0.4
c1 = [0,0,1]
c2 = [lighter,lighter,1]
c3 = [1,0,0]
c4 = [1,lighter,lighter]
col = [c1, c2, c3, c4]
plt.figure(figsize=(2,2))
ax = plt.subplot(111)
ax = my_plots.bar_multi(vals, errors, legend = ['R-1','R-5','M-1','M-5'], xlabels = ['Q 1', 'Q 2'], w =0.15, xlim = [0.5,2.5], yticks = [1,2,3,4,5], save = True, where = 'learn_NASA.pdf', colors = col)
plt.yticks([1,2,3,4,5])
plt.xlim(0.5,2.5)
ax.xaxis.grid()
savefig('learn_NASA.pdf', bbox_inches='tight')
###Output
[[0, 0, 1], [0.4, 0.4, 1], [1, 0, 0], [1, 0.4, 0.4]]
###Markdown
Interesting statistics (see below) remote-first motion-first How physically demanding was the test? p = 0.0488888176268915 remote-last motion-last How physically demanding was the test? p = 0.23390621098854886 remote-last motion-last How mentally demanding was the test? p = 0.01913961955875495 motion-first remote-first How mentally demanding was the test? p = 0.03344653009997241
###Code
for idx,i in enumerate(types):
for j in types[idx+1:]:
print()
for q in questions_NASA:
if i != j:
# also, compare only first-last for same interface or first-first, last-last for different ones
if ('first' in i and 'first' in j) or ('last' in i and 'last' in j) or ('remote' in i and 'remote' in j) or ('motion' in i and 'motion' in j):
t, p = t_test_kruskal(data_NASA[i][q],data_NASA_hw[j][q])
print(i,j,q)
print_p(p)
plt.figure(figsize=(16,4))
vals = []
errors = []
for idx, s in enumerate(stats_NASA_hw):
# print(stats[s])
means = [stats_NASA_hw[s][q][0] for q in questions_NASA]
stds = [stats_NASA_hw[s][q][1] for q in questions_NASA]
# print(means)
# print(stds)
ax = plt.subplot(141+idx)
ax.bar([0, 1, 2, 3, 4],
means,
yerr=stds)
plt.title(s)
vals.append(means)
errors.append(stds)
lighter = 0.4
c1 = [0,0,1]
c2 = [lighter,lighter,1]
c3 = [1,0,0]
c4 = [1,lighter,lighter]
col = [c1, c2, c3, c4]
plt.figure(figsize=(2,3))
ax = plt.subplot(111)
ax = my_plots.bar_multi(vals, errors, legend = ['R-1','R-5','M-1','M-5'], xlabels = ['Q 1', 'Q 2'], w =0.15, xlim = [0.5,2.5], yticks = [1,2,3,4,5], save = True, where = 'learn_NASA.pdf', colors = col)
plt.yticks([1,2,3,4,5])
plt.xlim(0.5,2.5)
ax.xaxis.grid()
###Output
[[0, 0, 1], [0.4, 0.4, 1], [1, 0, 0], [1, 0.4, 0.4]]
###Markdown
FINAL PLOTS
###Code
resp_data = {}
resp_data[easier_first] = Counter(data_sim[easier_first])
resp_data[easier_last] = Counter(data_sim[easier_last])
resp_data[prefered] = Counter(data_sim[prefered])
resp_data[prefered]['Equivalent'] = 0
fig = plt.figure(figsize = (7,2))
qs = ['QL 1', 'QL 2', 'QL 3']
c1 = 'gray'
c2 = 'b'
c3 = 'r'
c = [c1, c2, c3]
for jdx, j in enumerate(resp_data):
ax = fig.add_subplot(1, 4, 1+jdx)
options = []
resp = []
for i in sorted(resp_data[j]):
options.append(i)
resp.append(resp_data[j][i])
for idx, i in enumerate(options):
lab = i if 'We' not in i else 'Wearable'
if 'Re' in i:
lab = 'Remote'
# lab = i if 'Remote' in i else 'Remote'
plt.bar(1+idx, resp[idx], label = lab, color = c[idx])
if jdx==0:
# plt.legend(loc = 'upper left')
plt.yticks([2, 4, 6, 8, 10])
plt.title('Simulation')
else:
plt.yticks([2, 4, 6, 8, 10], ['','','','','',''])
if jdx==1:
pass
# plt.title('Responses')
ax.yaxis.grid()
plt.ylim(0,10)
plt.xticks([2],[qs[jdx]], axes=ax)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
vals = []
errors = []
for idx, s in enumerate(stats_NASA):
# print(stats[s])
means = [stats_NASA[s][q][0] for q in questions_NASA]
stds = [stats_NASA[s][q][1] for q in questions_NASA]
# print(means)
# print(stds)
# ax = plt.subplot(141+idx)
# ax.bar([0, 1, 2, 3, 4],
# means,
# yerr=stds)
# plt.title(s)
vals.append(means[0:2])
errors.append(stds[0:2])
lighter = 0.4
c1 = [0,0,1]
c2 = [lighter,lighter,1]
c3 = [1,0,0]
c4 = [1,lighter,lighter]
col = [c1, c2, c3, c4]
ax = plt.subplot(1, 4, 4)
ax = my_plots.bar_multi(vals, errors, ax = ax, xlabels = ['Q 1', 'Q 2'], w =0.15, xlim = [0.5,2.5], yticks = [1,2,3,4,5], save = True, where = 'learn_NASA.pdf', colors = col)
plt.yticks([1,2,3,4,5])
plt.xlim(0.5,2.5)
ax.xaxis.grid()
savefig('learn_quest.pdf', bbox_inches='tight')
resp_data = {}
resp_data[easier_first] = Counter(data_hw[easier_first])
resp_data[easier_last] = Counter(data_hw[easier_last])
resp_data[prefered] = Counter(data_hw[prefered])
resp_data[easier_first]['Equivalent'] = 1
resp_data[easier_first]['Remote controller'] = 2
resp_data[easier_first]['Wearable'] = 1
resp_data[easier_last]['Equivalent'] = 1
resp_data[easier_last]['Remote controller'] = 1
resp_data[easier_last]['Wearable'] = 2
resp_data[prefered]['Equivalent'] = 0
resp_data[prefered]['Remote controller'] = 1
resp_data[prefered]['Werable'] = 3
fig = plt.figure(figsize = (7,2))
qs = ['QL 1', 'QL 2', 'QL 3']
c1 = 'gray'
c2 = 'b'
c3 = 'r'
c = [c1, c2, c3]
for jdx, j in enumerate(resp_data):
ax = fig.add_subplot(1, 4, 1+jdx)
options = []
resp = []
for i in sorted(resp_data[j]):
options.append(i)
resp.append(resp_data[j][i])
for idx, i in enumerate(options):
lab = i if 'We' not in i else 'Wearable'
if 'Re' in i:
lab = 'Remote'
# lab = i if 'Remote' in i else 'Remote'
plt.bar(1+idx, resp[idx], label = lab, color = c[idx])
if jdx==0:
plt.legend(loc = 'upper left')
plt.title('Hardware')
plt.yticks([2, 4, 6, 8, 10])
else:
plt.yticks([2, 4, 6, 8, 10], ['','','',''])
if jdx==1:
pass
# plt.title('Responses')
ax.yaxis.grid()
plt.ylim(0,10)
plt.xticks([2],[qs[jdx]], axes=ax)
ax.spines['right'].set_visible(False)
ax.spines['top'].set_visible(False)
vals = []
errors = []
for idx, s in enumerate(stats_NASA_hw):
# print(stats[s])
means = [stats_NASA_hw[s][q][0] for q in questions_NASA]
stds = [stats_NASA_hw[s][q][1] for q in questions_NASA]
# print(means)
# print(stds)
# ax = plt.subplot(141+idx)
# ax.bar([0, 1, 2, 3, 4],
# means,
# yerr=stds)
# plt.title(s)
vals.append(means[0:2])
errors.append(stds[0:2])
lighter = 0.4
c1 = [0,0,1]
c2 = [lighter,lighter,1]
c3 = [1,0,0]
c4 = [1,lighter,lighter]
col = [c1, c2, c3, c4]
ax = plt.subplot(1, 4, 4)
ax = my_plots.bar_multi(vals, errors, legend = ['R1','R5','W1','W5'], ax = ax, xlabels = ['Q 1', 'Q 2'], w =0.15, xlim = [0.5,2.5], yticks = [1,2,3,4,5], save = True, where = 'learn_NASA.pdf', colors = col)
plt.yticks([1,2,3,4,5])
plt.xlim(0.5,2.5)
ax.xaxis.grid()
savefig('learn_quest_HW.pdf', bbox_inches='tight')
print(resp_data)
# print(stats_NASA_hw)
data_hw
###Output
_____no_output_____ |
1_exercise/DTSense_EDA.ipynb | ###Markdown
__Load Data__
###Code
import pandas as pd
import numpy as np
data = pd.read_csv('https://raw.githubusercontent.com/DTSense/Webinar_EDA_Seaborn/main/1_exercise/house_price.csv')
data.head()
for col in data.columns:
print(col, ':', data[col].dtypes)
###Output
Id : int64
MSSubClass : int64
MSZoning : object
LotFrontage : float64
LotArea : int64
Street : object
Alley : object
LotShape : object
LandContour : object
Utilities : object
LotConfig : object
LandSlope : object
Neighborhood : object
Condition1 : object
Condition2 : object
BldgType : object
HouseStyle : object
OverallQual : int64
OverallCond : int64
YearBuilt : int64
YearRemodAdd : int64
RoofStyle : object
RoofMatl : object
Exterior1st : object
Exterior2nd : object
MasVnrType : object
MasVnrArea : float64
ExterQual : object
ExterCond : object
Foundation : object
BsmtQual : object
BsmtCond : object
BsmtExposure : object
BsmtFinType1 : object
BsmtFinSF1 : int64
BsmtFinType2 : object
BsmtFinSF2 : int64
BsmtUnfSF : int64
TotalBsmtSF : int64
Heating : object
HeatingQC : object
CentralAir : object
Electrical : object
1stFlrSF : int64
2ndFlrSF : int64
LowQualFinSF : int64
GrLivArea : int64
BsmtFullBath : int64
BsmtHalfBath : int64
FullBath : int64
HalfBath : int64
BedroomAbvGr : int64
KitchenAbvGr : int64
KitchenQual : object
TotRmsAbvGrd : int64
Functional : object
Fireplaces : int64
FireplaceQu : object
GarageType : object
GarageYrBlt : float64
GarageFinish : object
GarageCars : int64
GarageArea : int64
GarageQual : object
GarageCond : object
PavedDrive : object
WoodDeckSF : int64
OpenPorchSF : int64
EnclosedPorch : int64
3SsnPorch : int64
ScreenPorch : int64
PoolArea : int64
PoolQC : object
Fence : object
MiscFeature : object
MiscVal : int64
MoSold : int64
YrSold : int64
SaleType : object
SaleCondition : object
SalePrice : int64
###Markdown
Non-graphical EDA
###Code
data.____()
###Output
_____no_output_____
###Markdown
Univariate Central tendency Mean
###Code
data['LotArea'].___()
###Output
_____no_output_____
###Markdown
Median
###Code
data['LotArea'].___()
###Output
_____no_output_____
###Markdown
Mode
###Code
data['LotArea'].___()
###Output
_____no_output_____
###Markdown
Spread tendency Variance
###Code
data['LotArea'].___()
###Output
_____no_output_____
###Markdown
Std. Deviation
###Code
data['LotArea'].___()
###Output
_____no_output_____
###Markdown
Range
###Code
data['LotArea'].___()
data['LotArea'].___()
###Output
_____no_output_____
###Markdown
IQR Range
###Code
data['LotArea'].___(q=___)
data['LotArea'].___(q=___)
###Output
_____no_output_____
###Markdown
Multivariate Covariance
###Code
np.___(data['LotArea'], data['OverallQual'])
###Output
_____no_output_____
###Markdown
Correlation
###Code
np.___(data['LotArea'], data['OverallQual'])
###Output
_____no_output_____
###Markdown
--- Graphical EDA Import library
###Code
import ___ as sns
###Output
_____no_output_____
###Markdown
Univariate Histogram
###Code
sns.___(x='YearBuilt', kde=___, data=___)
sns.histplot(x='YearBuilt', data=___)
###Output
_____no_output_____
###Markdown
Box plot
###Code
sns.___(x='YearBuilt', data=___)
sns.___(x='YearBuilt', y='SaleCondition', data=___)
###Output
_____no_output_____
###Markdown
Violin Plot
###Code
sns.___(x='YearBuilt', data=___)
sns.___(x='YearBuilt', y='CentralAir', data=___)
###Output
_____no_output_____
###Markdown
Bar plot
###Code
sns.___(x='SaleCondition', data=___)
sns.___(x='SaleCondition', hue='CentralAir', data=___)
###Output
_____no_output_____
###Markdown
Line plot
###Code
# ambil hanya 100 data pertama dari data
sns.___(x=___.loc[0:100].index, y='MSSubClass', data=___.loc[0:100])
###Output
_____no_output_____
###Markdown
--- Multivariate Scatter plot
###Code
sns.___(x="LotFrontage", y="SalePrice", data=___)
sns.___(x="LotFrontage", y="SalePrice", hue="CentralAir", data=___)
###Output
_____no_output_____
###Markdown
Bubble plot
###Code
sns.___(x="LotFrontage", y="SalePrice", data=___, size="YearBuilt")
###Output
_____no_output_____
###Markdown
Pair plot
###Code
sns.___(data=data[['LotFrontage', 'SalePrice', 'YearBuilt']])
sns.___(data=data[['LotFrontage', 'SalePrice', 'YearBuilt', 'CentralAir']], hue='CentralAir')
###Output
_____no_output_____
###Markdown
Joint Plot
###Code
sns.___(x='SalePrice', y='YearBuilt', data=___)
sns.___(x='SalePrice', y='YearBuilt', data=___, hue='CentralAir')
###Output
_____no_output_____
###Markdown
Heat map
###Code
heat_data = pd.pivot_table(data, index='MoSold', columns='YrSold', aggfunc=np.count_nonzero)['SalePrice'].fillna(0)
heat_data
sns.___(heat_data)
# melihat correlation map
sub_data = data[['LotArea','LotFrontage','1stFlrSF','2ndFlrSF']]
sns.___(sub_data.___())
###Output
_____no_output_____ |
site/en-snapshot/lite/tutorials/model_maker_question_answer.ipynb | ###Markdown
Copyright 2020 The TensorFlow Authors.
###Code
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###Output
_____no_output_____
###Markdown
Question Answer with TensorFlow Lite Model Maker View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook The TensorFlow Lite Model Maker library simplifies the process of adapting and converting a TensorFlow model to particular input data when deploying this model for on-device ML applications.This notebook shows an end-to-end example that utilizes the Model Maker library to illustrate the adaptation and conversion of a commonly-used question answer model for question answer task. Introduction to Question Answer Task The supported task in this library is extractive question answer task, which means given a passage and a question, the answer is the span in the passage. The image below shows an example for question answer. Answers are spans in the passage (image credit: SQuAD blog) As for the model of question answer task, the inputs should be the passage and question pair that are already preprocessed, the outputs should be the start logits and end logits for each token in the passage.The size of input could be set and adjusted according to the length of passage and question. End-to-End Overview The following code snippet demonstrates how to get the model within a few lines of code. The overall process includes 5 steps: (1) choose a model, (2) load data, (3) retrain the model, (4) evaluate, and (5) export it to TensorFlow Lite format. ```python Chooses a model specification that represents the model.spec = model_spec.get('mobilebert_qa') Gets the training data and validation data.train_data = QuestionAnswerDataLoader.from_squad(train_data_path, spec, is_training=True)validation_data = QuestionAnswerDataLoader.from_squad(validation_data_path, spec, is_training=False) Fine-tunes the model.model = question_answer.create(train_data, model_spec=spec) Gets the evaluation result.metric = model.evaluate(validation_data) Exports the model to the TensorFlow Lite format in the export directory.model.export(export_dir)``` The following sections explain the code in more detail. PrerequisitesTo run this example, install the required packages, including the Model Maker package from the [GitHub repo](https://github.com/tensorflow/examples/tree/master/tensorflow_examples/lite/model_maker).
###Code
!pip install tflite-model-maker
###Output
_____no_output_____
###Markdown
Import the required packages.
###Code
import numpy as np
import os
import tensorflow as tf
assert tf.__version__.startswith('2')
from tflite_model_maker import configs
from tflite_model_maker import model_spec
from tflite_model_maker import question_answer
from tflite_model_maker import QuestionAnswerDataLoader
###Output
_____no_output_____
###Markdown
The "End-to-End Overview" demonstrates a simple end-to-end example. The following sections walk through the example step by step to show more detail. Choose a model_spec that represents a model for question answerEach `model_spec` object represents a specific model for question answer. The Model Maker currently supports MobileBERT and BERT-Base models.Supported Model | Name of model_spec | Model Description--- | --- | ---[MobileBERT](https://arxiv.org/pdf/2004.02984.pdf) | 'mobilebert_qa' | 4.3x smaller and 5.5x faster than BERT-Base while achieving competitive results, suitable for on-device scenario.[MobileBERT-SQuAD](https://arxiv.org/pdf/2004.02984.pdf) | 'mobilebert_qa_squad' | Same model architecture as MobileBERT model and the initial model is already retrained on [SQuAD1.1](https://rajpurkar.github.io/SQuAD-explorer/).[BERT-Base](https://arxiv.org/pdf/1810.04805.pdf) | 'bert_qa' | Standard BERT model that widely used in NLP tasks.In this tutorial, [MobileBERT-SQuAD](https://arxiv.org/pdf/2004.02984.pdf) is used as an example. Since the model is already retrained on [SQuAD1.1](https://rajpurkar.github.io/SQuAD-explorer/), it could coverage faster for question answer task.
###Code
spec = model_spec.get('mobilebert_qa_squad')
###Output
_____no_output_____
###Markdown
Load Input Data Specific to an On-device ML App and Preprocess the DataThe [TriviaQA](https://nlp.cs.washington.edu/triviaqa/) is a reading comprehension dataset containing over 650K question-answer-evidence triples. In this tutorial, you will use a subset of this dataset to learn how to use the Model Maker library.To load the data, convert the TriviaQA dataset to the [SQuAD1.1](https://rajpurkar.github.io/SQuAD-explorer/) format by running the [converter Python script](https://github.com/mandarjoshi90/triviaqamiscellaneous) with `--sample_size=8000` and a set of `web` data. Modify the conversion code a little bit by:* Skipping the samples that couldn't find any answer in the context document;* Getting the original answer in the context without uppercase or lowercase.Download the archived version of the already converted dataset.
###Code
train_data_path = tf.keras.utils.get_file(
fname='triviaqa-web-train-8000.json',
origin='https://storage.googleapis.com/download.tensorflow.org/models/tflite/dataset/triviaqa-web-train-8000.json')
validation_data_path = tf.keras.utils.get_file(
fname='triviaqa-verified-web-dev.json',
origin='https://storage.googleapis.com/download.tensorflow.org/models/tflite/dataset/triviaqa-verified-web-dev.json')
###Output
_____no_output_____
###Markdown
You can also train the MobileBERT model with your own dataset. If you are running this notebook on Colab, upload your data by using the left sidebar.If you prefer not to upload your data to the cloud, you can also run the library offline by following the [guide](https://github.com/tensorflow/examples/tree/master/tensorflow_examples/lite/model_maker). Use the `QuestionAnswerDataLoader.from_squad` method to load and preprocess the [SQuAD format](https://rajpurkar.github.io/SQuAD-explorer/) data according to a specific `model_spec`. You can use either SQuAD2.0 or SQuAD1.1 formats. Setting parameter `version_2_with_negative` as `True` means the formats is SQuAD2.0. Otherwise, the format is SQuAD1.1. By default, `version_2_with_negative` is `False`.
###Code
train_data = QuestionAnswerDataLoader.from_squad(train_data_path, spec, is_training=True)
validation_data = QuestionAnswerDataLoader.from_squad(validation_data_path, spec, is_training=False)
###Output
_____no_output_____
###Markdown
Customize the TensorFlow ModelCreate a custom question answer model based on the loaded data. The `create` function comprises the following steps:1. Creates the model for question answer according to `model_spec`.2. Train the question answer model. The default epochs and the default batch size are set according to two variables `default_training_epochs` and `default_batch_size` in the `model_spec` object.
###Code
model = question_answer.create(train_data, model_spec=spec)
###Output
_____no_output_____
###Markdown
Have a look at the detailed model structure.
###Code
model.summary()
###Output
_____no_output_____
###Markdown
Evaluate the Customized ModelEvaluate the model on the validation data and get a dict of metrics including `f1` score and `exact match` etc. Note that metrics are different for SQuAD1.1 and SQuAD2.0.
###Code
model.evaluate(validation_data)
###Output
_____no_output_____
###Markdown
Export to TensorFlow Lite ModelConvert the existing model to TensorFlow Lite model format that you can later use in an on-device ML application. Since MobileBERT is too big for on-device applications, use dynamic range quantization on the model to compress MobileBERT by 4x with the minimal loss of performance. First, define the quantization configuration:
###Code
config = configs.QuantizationConfig.create_dynamic_range_quantization(optimizations=[tf.lite.Optimize.OPTIMIZE_FOR_LATENCY])
config._experimental_new_quantizer = True
###Output
_____no_output_____
###Markdown
Export the quantized TFLite model according to the quantization config and save the vocabulary to a vocab file. The default TFLite model filename is `model.tflite`, and the default vocab filename is `vocab`.
###Code
model.export(export_dir='.', quantization_config=config)
###Output
_____no_output_____
###Markdown
You can use the TensorFlow Lite model file and vocab file in the [bert_qa](https://github.com/tensorflow/examples/tree/master/lite/examples/bert_qa/android) reference app by downloading it from the left sidebar on Colab. You can also evalute the tflite model with the `evaluate_tflite` method. This step is expected to take a long time.
###Code
model.evaluate_tflite('model.tflite', validation_data)
###Output
_____no_output_____
###Markdown
Advanced UsageThe `create` function is the critical part of this library in which the `model_spec` parameter defines the model specification. The `BertQAModelSpec` class is currently supported. There are 2 models: MobileBERT model, BERT-Base model. The `create` function comprises the following steps:1. Creates the model for question answer according to `model_spec`.2. Train the question answer model.This section describes several advanced topics, including adjusting the model, tuning the training hyperparameters etc. Adjust the modelYou can adjust the model infrastructure like parameters `seq_len` and `query_len` in the `BertQAModelSpec` class.Adjustable parameters for model:* `seq_len`: Length of the passage to feed into the model.* `query_len`: Length of the question to feed into the model.* `doc_stride`: The stride when doing a sliding window approach to take chunks of the documents.* `initializer_range`: The stdev of the truncated_normal_initializer for initializing all weight matrices.* `trainable`: Boolean, whether pre-trained layer is trainable.Adjustable parameters for training pipeline:* `model_dir`: The location of the model checkpoint files. If not set, temporary directory will be used.* `dropout_rate`: The rate for dropout.* `learning_rate`: The initial learning rate for Adam.* `predict_batch_size`: Batch size for prediction.* `tpu`: TPU address to connect to. Only used if using tpu. For example, you can train the model with a longer sequence length. If you change the model, you must first construct a new `model_spec`.
###Code
new_spec = model_spec.get('mobilebert_qa')
new_spec.seq_len = 512
###Output
_____no_output_____
###Markdown
Copyright 2020 The TensorFlow Authors.
###Code
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###Output
_____no_output_____
###Markdown
BERT Question Answer with TensorFlow Lite Model Maker View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook The TensorFlow Lite Model Maker library simplifies the process of adapting and converting a TensorFlow model to particular input data when deploying this model for on-device ML applications.This notebook shows an end-to-end example that utilizes the Model Maker library to illustrate the adaptation and conversion of a commonly-used question answer model for question answer task. Introduction to BERT Question Answer Task The supported task in this library is extractive question answer task, which means given a passage and a question, the answer is the span in the passage. The image below shows an example for question answer. Answers are spans in the passage (image credit: SQuAD blog) As for the model of question answer task, the inputs should be the passage and question pair that are already preprocessed, the outputs should be the start logits and end logits for each token in the passage.The size of input could be set and adjusted according to the length of passage and question. End-to-End Overview The following code snippet demonstrates how to get the model within a few lines of code. The overall process includes 5 steps: (1) choose a model, (2) load data, (3) retrain the model, (4) evaluate, and (5) export it to TensorFlow Lite format. ```python Chooses a model specification that represents the model.spec = model_spec.get('mobilebert_qa') Gets the training data and validation data.train_data = DataLoader.from_squad(train_data_path, spec, is_training=True)validation_data = DataLoader.from_squad(validation_data_path, spec, is_training=False) Fine-tunes the model.model = question_answer.create(train_data, model_spec=spec) Gets the evaluation result.metric = model.evaluate(validation_data) Exports the model to the TensorFlow Lite format with metadata in the export directory.model.export(export_dir)``` The following sections explain the code in more detail. PrerequisitesTo run this example, install the required packages, including the Model Maker package from the [GitHub repo](https://github.com/tensorflow/examples/tree/master/tensorflow_examples/lite/model_maker).
###Code
!pip install -q tflite-model-maker
###Output
_____no_output_____
###Markdown
Import the required packages.
###Code
import numpy as np
import os
import tensorflow as tf
assert tf.__version__.startswith('2')
from tflite_model_maker import model_spec
from tflite_model_maker import question_answer
from tflite_model_maker.config import ExportFormat
from tflite_model_maker.config import QuantizationConfig
from tflite_model_maker.question_answer import DataLoader
###Output
_____no_output_____
###Markdown
The "End-to-End Overview" demonstrates a simple end-to-end example. The following sections walk through the example step by step to show more detail. Choose a model_spec that represents a model for question answerEach `model_spec` object represents a specific model for question answer. The Model Maker currently supports MobileBERT and BERT-Base models.Supported Model | Name of model_spec | Model Description--- | --- | ---[MobileBERT](https://arxiv.org/pdf/2004.02984.pdf) | 'mobilebert_qa' | 4.3x smaller and 5.5x faster than BERT-Base while achieving competitive results, suitable for on-device scenario.[MobileBERT-SQuAD](https://arxiv.org/pdf/2004.02984.pdf) | 'mobilebert_qa_squad' | Same model architecture as MobileBERT model and the initial model is already retrained on [SQuAD1.1](https://rajpurkar.github.io/SQuAD-explorer/).[BERT-Base](https://arxiv.org/pdf/1810.04805.pdf) | 'bert_qa' | Standard BERT model that widely used in NLP tasks.In this tutorial, [MobileBERT-SQuAD](https://arxiv.org/pdf/2004.02984.pdf) is used as an example. Since the model is already retrained on [SQuAD1.1](https://rajpurkar.github.io/SQuAD-explorer/), it could coverage faster for question answer task.
###Code
spec = model_spec.get('mobilebert_qa_squad')
###Output
_____no_output_____
###Markdown
Load Input Data Specific to an On-device ML App and Preprocess the DataThe [TriviaQA](https://nlp.cs.washington.edu/triviaqa/) is a reading comprehension dataset containing over 650K question-answer-evidence triples. In this tutorial, you will use a subset of this dataset to learn how to use the Model Maker library.To load the data, convert the TriviaQA dataset to the [SQuAD1.1](https://rajpurkar.github.io/SQuAD-explorer/) format by running the [converter Python script](https://github.com/mandarjoshi90/triviaqamiscellaneous) with `--sample_size=8000` and a set of `web` data. Modify the conversion code a little bit by:* Skipping the samples that couldn't find any answer in the context document;* Getting the original answer in the context without uppercase or lowercase.Download the archived version of the already converted dataset.
###Code
train_data_path = tf.keras.utils.get_file(
fname='triviaqa-web-train-8000.json',
origin='https://storage.googleapis.com/download.tensorflow.org/models/tflite/dataset/triviaqa-web-train-8000.json')
validation_data_path = tf.keras.utils.get_file(
fname='triviaqa-verified-web-dev.json',
origin='https://storage.googleapis.com/download.tensorflow.org/models/tflite/dataset/triviaqa-verified-web-dev.json')
###Output
_____no_output_____
###Markdown
You can also train the MobileBERT model with your own dataset. If you are running this notebook on Colab, upload your data by using the left sidebar.If you prefer not to upload your data to the cloud, you can also run the library offline by following the [guide](https://github.com/tensorflow/examples/tree/master/tensorflow_examples/lite/model_maker). Use the `DataLoader.from_squad` method to load and preprocess the [SQuAD format](https://rajpurkar.github.io/SQuAD-explorer/) data according to a specific `model_spec`. You can use either SQuAD2.0 or SQuAD1.1 formats. Setting parameter `version_2_with_negative` as `True` means the formats is SQuAD2.0. Otherwise, the format is SQuAD1.1. By default, `version_2_with_negative` is `False`.
###Code
train_data = DataLoader.from_squad(train_data_path, spec, is_training=True)
validation_data = DataLoader.from_squad(validation_data_path, spec, is_training=False)
###Output
_____no_output_____
###Markdown
Customize the TensorFlow ModelCreate a custom question answer model based on the loaded data. The `create` function comprises the following steps:1. Creates the model for question answer according to `model_spec`.2. Train the question answer model. The default epochs and the default batch size are set according to two variables `default_training_epochs` and `default_batch_size` in the `model_spec` object.
###Code
model = question_answer.create(train_data, model_spec=spec)
###Output
_____no_output_____
###Markdown
Have a look at the detailed model structure.
###Code
model.summary()
###Output
_____no_output_____
###Markdown
Evaluate the Customized ModelEvaluate the model on the validation data and get a dict of metrics including `f1` score and `exact match` etc. Note that metrics are different for SQuAD1.1 and SQuAD2.0.
###Code
model.evaluate(validation_data)
###Output
_____no_output_____
###Markdown
Export to TensorFlow Lite ModelConvert the existing model to TensorFlow Lite model format that you can later use in an on-device ML application. Since MobileBERT is too big for on-device applications, use dynamic range quantization on the model to compress MobileBERT by 4x with the minimal loss of performance. First, define the quantization configuration:
###Code
config = QuantizationConfig.for_dynamic()
config.experimental_new_quantizer = True
###Output
_____no_output_____
###Markdown
Export the quantized TFLite model according to the quantization config with [metadata](https://www.tensorflow.org/lite/convert/metadata). The default TFLite model filename is `model.tflite`.
###Code
model.export(export_dir='.', quantization_config=config)
###Output
_____no_output_____
###Markdown
You can use the TensorFlow Lite model file in the [bert_qa](https://github.com/tensorflow/examples/tree/master/lite/examples/bert_qa/android) reference app using [BertQuestionAnswerer API](https://www.tensorflow.org/lite/inference_with_metadata/task_library/bert_question_answerer) in [TensorFlow Lite Task Library](https://www.tensorflow.org/lite/inference_with_metadata/task_library/overview) by downloading it from the left sidebar on Colab. The allowed export formats can be one or a list of the following:* `ExportFormat.TFLITE`* `ExportFormat.VOCAB`* `ExportFormat.SAVED_MODEL`By default, it just exports TensorFlow Lite model with metadata. You can also selectively export different files. For instance, exporting only the vocab file as follows:
###Code
model.export(export_dir='.', export_format=ExportFormat.VOCAB)
###Output
_____no_output_____
###Markdown
You can also evaluate the tflite model with the `evaluate_tflite` method. This step is expected to take a long time.
###Code
model.evaluate_tflite('model.tflite', validation_data)
###Output
_____no_output_____
###Markdown
Advanced UsageThe `create` function is the critical part of this library in which the `model_spec` parameter defines the model specification. The `BertQASpec` class is currently supported. There are 2 models: MobileBERT model, BERT-Base model. The `create` function comprises the following steps:1. Creates the model for question answer according to `model_spec`.2. Train the question answer model.This section describes several advanced topics, including adjusting the model, tuning the training hyperparameters etc. Adjust the modelYou can adjust the model infrastructure like parameters `seq_len` and `query_len` in the `BertQASpec` class.Adjustable parameters for model:* `seq_len`: Length of the passage to feed into the model.* `query_len`: Length of the question to feed into the model.* `doc_stride`: The stride when doing a sliding window approach to take chunks of the documents.* `initializer_range`: The stdev of the truncated_normal_initializer for initializing all weight matrices.* `trainable`: Boolean, whether pre-trained layer is trainable.Adjustable parameters for training pipeline:* `model_dir`: The location of the model checkpoint files. If not set, temporary directory will be used.* `dropout_rate`: The rate for dropout.* `learning_rate`: The initial learning rate for Adam.* `predict_batch_size`: Batch size for prediction.* `tpu`: TPU address to connect to. Only used if using tpu. For example, you can train the model with a longer sequence length. If you change the model, you must first construct a new `model_spec`.
###Code
new_spec = model_spec.get('mobilebert_qa')
new_spec.seq_len = 512
###Output
_____no_output_____
###Markdown
Copyright 2020 The TensorFlow Authors.
###Code
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###Output
_____no_output_____
###Markdown
Question Answer with TensorFlow Lite Model Maker View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook The TensorFlow Lite Model Maker library simplifies the process of adapting and converting a TensorFlow model to particular input data when deploying this model for on-device ML applications.This notebook shows an end-to-end example that utilizes the Model Maker library to illustrate the adaptation and conversion of a commonly-used question answer model for question answer task. Introduction to Question Answer Task The supported task in this library is extractive question answer task, which means given a passage and a question, the answer is the span in the passage. The image below shows an example for question answer. Answers are spans in the passage (image credit: SQuAD blog) As for the model of question answer task, the inputs should be the passage and question pair that are already preprocessed, the outputs should be the start logits and end logits for each token in the passage.The size of input could be set and adjusted according to the length of passage and question. End-to-End Overview The following code snippet demonstrates how to get the model within a few lines of code. The overall process includes 5 steps: (1) choose a model, (2) load data, (3) retrain the model, (4) evaluate, and (5) export it to TensorFlow Lite format. ```python Chooses a model specification that represents the model.spec = model_spec.get('mobilebert_qa') Gets the training data and validation data.train_data = QuestionAnswerDataLoader.from_squad(train_data_path, spec, is_training=True)validation_data = QuestionAnswerDataLoader.from_squad(validation_data_path, spec, is_training=False) Fine-tunes the model.model = question_answer.create(train_data, model_spec=spec) Gets the evaluation result.metric = model.evaluate(validation_data) Exports the model to the TensorFlow Lite format with metadata in the export directory.model.export(export_dir)``` The following sections explain the code in more detail. PrerequisitesTo run this example, install the required packages, including the Model Maker package from the [GitHub repo](https://github.com/tensorflow/examples/tree/master/tensorflow_examples/lite/model_maker).
###Code
!pip install tflite-model-maker
###Output
Collecting tflite-model-maker
[?25l Downloading https://files.pythonhosted.org/packages/13/bc/4c23b9cb9ef612a1f48bac5543bd531665de5eab8f8231111aac067f8c30/tflite_model_maker-0.1.2-py3-none-any.whl (104kB)
[K |███▏ | 10kB 28.4MB/s eta 0:00:01
[K |██████▎ | 20kB 1.8MB/s eta 0:00:01
[K |█████████▍ | 30kB 2.4MB/s eta 0:00:01
[K |████████████▋ | 40kB 2.7MB/s eta 0:00:01
[K |███████████████▊ | 51kB 2.1MB/s eta 0:00:01
[K |██████████████████▉ | 61kB 2.4MB/s eta 0:00:01
[K |██████████████████████ | 71kB 2.7MB/s eta 0:00:01
[K |█████████████████████████▏ | 81kB 2.9MB/s eta 0:00:01
[K |████████████████████████████▎ | 92kB 3.1MB/s eta 0:00:01
[K |███████████████████████████████▌| 102kB 3.0MB/s eta 0:00:01
[K |████████████████████████████████| 112kB 3.0MB/s
[?25hRequirement already satisfied: absl-py in /usr/local/lib/python3.6/dist-packages (from tflite-model-maker) (0.10.0)
Collecting tf-nightly
[?25l Downloading https://files.pythonhosted.org/packages/33/d4/61c47ae889b490b9c5f07f4f61bdc057c158a1a1979c375fa019d647a19e/tf_nightly-2.4.0.dev20200914-cp36-cp36m-manylinux2010_x86_64.whl (390.1MB)
[K |████████████████████████████████| 390.2MB 43kB/s
[?25hRequirement already satisfied: numpy>=1.17.3 in /usr/local/lib/python3.6/dist-packages (from tflite-model-maker) (1.18.5)
Requirement already satisfied: pillow in /usr/local/lib/python3.6/dist-packages (from tflite-model-maker) (7.0.0)
Collecting tf-models-nightly
[?25l Downloading https://files.pythonhosted.org/packages/d3/e9/c4e5a451c268a5a75a27949562364f6086f6bb33b226a065a8beceefa9ba/tf_models_nightly-2.3.0.dev20200914-py2.py3-none-any.whl (993kB)
[K |████████████████████████████████| 1.0MB 57.6MB/s
[?25hCollecting flatbuffers==1.12
Downloading https://files.pythonhosted.org/packages/eb/26/712e578c5f14e26ae3314c39a1bdc4eb2ec2f4ddc89b708cf8e0a0d20423/flatbuffers-1.12-py2.py3-none-any.whl
Requirement already satisfied: tensorflow-hub>=0.8.0 in /usr/local/lib/python3.6/dist-packages (from tflite-model-maker) (0.9.0)
Collecting fire
[?25l Downloading https://files.pythonhosted.org/packages/34/a7/0e22e70778aca01a52b9c899d9c145c6396d7b613719cd63db97ffa13f2f/fire-0.3.1.tar.gz (81kB)
[K |████████████████████████████████| 81kB 11.5MB/s
[?25hCollecting sentencepiece
[?25l Downloading https://files.pythonhosted.org/packages/d4/a4/d0a884c4300004a78cca907a6ff9a5e9fe4f090f5d95ab341c53d28cbc58/sentencepiece-0.1.91-cp36-cp36m-manylinux1_x86_64.whl (1.1MB)
[K |████████████████████████████████| 1.1MB 50.9MB/s
[?25hCollecting tflite-support==0.1.0rc3.dev2
[?25l Downloading https://files.pythonhosted.org/packages/fa/c5/5e9ee3abd5b4ef8294432cd714407f49a66befa864905b66ee8bdc612795/tflite_support-0.1.0rc3.dev2-cp36-cp36m-manylinux2010_x86_64.whl (1.0MB)
[K |████████████████████████████████| 1.0MB 50.9MB/s
[?25hRequirement already satisfied: tensorflow-datasets>=2.1.0 in /usr/local/lib/python3.6/dist-packages (from tflite-model-maker) (2.1.0)
Requirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from absl-py->tflite-model-maker) (1.15.0)
Requirement already satisfied: termcolor>=1.1.0 in /usr/local/lib/python3.6/dist-packages (from tf-nightly->tflite-model-maker) (1.1.0)
Requirement already satisfied: opt-einsum>=2.3.2 in /usr/local/lib/python3.6/dist-packages (from tf-nightly->tflite-model-maker) (3.3.0)
Collecting tb-nightly<3.0.0a0,>=2.4.0a0
[?25l Downloading https://files.pythonhosted.org/packages/fc/cb/4dfe0d65bffb5e9663261ff664e6f5a2d37672b31dae27a0f14721ac00d3/tb_nightly-2.4.0a20200914-py3-none-any.whl (10.1MB)
[K |████████████████████████████████| 10.1MB 51.4MB/s
[?25hRequirement already satisfied: typing-extensions>=3.7.4.2 in /usr/local/lib/python3.6/dist-packages (from tf-nightly->tflite-model-maker) (3.7.4.3)
Requirement already satisfied: wheel>=0.26 in /usr/local/lib/python3.6/dist-packages (from tf-nightly->tflite-model-maker) (0.35.1)
Collecting tf-estimator-nightly
[?25l Downloading https://files.pythonhosted.org/packages/bd/9a/3bfb9994eda11e426c809ebdf434e2ac5824a0784d980018bb53fd1620ec/tf_estimator_nightly-2.4.0.dev2020091401-py2.py3-none-any.whl (460kB)
[K |████████████████████████████████| 460kB 36.0MB/s
[?25hRequirement already satisfied: google-pasta>=0.1.8 in /usr/local/lib/python3.6/dist-packages (from tf-nightly->tflite-model-maker) (0.2.0)
Requirement already satisfied: h5py<2.11.0,>=2.10.0 in /usr/local/lib/python3.6/dist-packages (from tf-nightly->tflite-model-maker) (2.10.0)
Requirement already satisfied: keras-preprocessing<1.2,>=1.1.1 in /usr/local/lib/python3.6/dist-packages (from tf-nightly->tflite-model-maker) (1.1.2)
Requirement already satisfied: wrapt>=1.11.1 in /usr/local/lib/python3.6/dist-packages (from tf-nightly->tflite-model-maker) (1.12.1)
Requirement already satisfied: grpcio>=1.8.6 in /usr/local/lib/python3.6/dist-packages (from tf-nightly->tflite-model-maker) (1.32.0)
Requirement already satisfied: protobuf>=3.9.2 in /usr/local/lib/python3.6/dist-packages (from tf-nightly->tflite-model-maker) (3.12.4)
Requirement already satisfied: gast==0.3.3 in /usr/local/lib/python3.6/dist-packages (from tf-nightly->tflite-model-maker) (0.3.3)
Requirement already satisfied: astunparse==1.6.3 in /usr/local/lib/python3.6/dist-packages (from tf-nightly->tflite-model-maker) (1.6.3)
Requirement already satisfied: scipy>=0.19.1 in /usr/local/lib/python3.6/dist-packages (from tf-models-nightly->tflite-model-maker) (1.4.1)
Collecting pyyaml>=5.1
[?25l Downloading https://files.pythonhosted.org/packages/64/c2/b80047c7ac2478f9501676c988a5411ed5572f35d1beff9cae07d321512c/PyYAML-5.3.1.tar.gz (269kB)
[K |████████████████████████████████| 276kB 59.8MB/s
[?25hCollecting tensorflow-model-optimization>=0.4.1
[?25l Downloading https://files.pythonhosted.org/packages/55/38/4fd48ea1bfcb0b6e36d949025200426fe9c3a8bfae029f0973d85518fa5a/tensorflow_model_optimization-0.5.0-py2.py3-none-any.whl (172kB)
[K |████████████████████████████████| 174kB 51.0MB/s
[?25hRequirement already satisfied: pandas>=0.22.0 in /usr/local/lib/python3.6/dist-packages (from tf-models-nightly->tflite-model-maker) (1.0.5)
Requirement already satisfied: dataclasses in /usr/local/lib/python3.6/dist-packages (from tf-models-nightly->tflite-model-maker) (0.7)
Requirement already satisfied: Cython in /usr/local/lib/python3.6/dist-packages (from tf-models-nightly->tflite-model-maker) (0.29.21)
Collecting opencv-python-headless
[?25l Downloading https://files.pythonhosted.org/packages/b6/2a/496e06fd289c01dc21b11970be1261c87ce1cc22d5340c14b516160822a7/opencv_python_headless-4.4.0.42-cp36-cp36m-manylinux2014_x86_64.whl (36.6MB)
[K |████████████████████████████████| 36.6MB 83kB/s
[?25hRequirement already satisfied: kaggle>=1.3.9 in /usr/local/lib/python3.6/dist-packages (from tf-models-nightly->tflite-model-maker) (1.5.8)
Requirement already satisfied: pycocotools in /usr/local/lib/python3.6/dist-packages (from tf-models-nightly->tflite-model-maker) (2.0.2)
Requirement already satisfied: oauth2client in /usr/local/lib/python3.6/dist-packages (from tf-models-nightly->tflite-model-maker) (4.1.3)
Requirement already satisfied: matplotlib in /usr/local/lib/python3.6/dist-packages (from tf-models-nightly->tflite-model-maker) (3.2.2)
Collecting tf-slim>=1.1.0
[?25l Downloading https://files.pythonhosted.org/packages/02/97/b0f4a64df018ca018cc035d44f2ef08f91e2e8aa67271f6f19633a015ff7/tf_slim-1.1.0-py2.py3-none-any.whl (352kB)
[K |████████████████████████████████| 358kB 55.9MB/s
[?25hCollecting seqeval
Downloading https://files.pythonhosted.org/packages/34/91/068aca8d60ce56dd9ba4506850e876aba5e66a6f2f29aa223224b50df0de/seqeval-0.0.12.tar.gz
Requirement already satisfied: psutil>=5.4.3 in /usr/local/lib/python3.6/dist-packages (from tf-models-nightly->tflite-model-maker) (5.4.8)
Collecting py-cpuinfo>=3.3.0
[?25l Downloading https://files.pythonhosted.org/packages/f6/f5/8e6e85ce2e9f6e05040cf0d4e26f43a4718bcc4bce988b433276d4b1a5c1/py-cpuinfo-7.0.0.tar.gz (95kB)
[K |████████████████████████████████| 102kB 13.5MB/s
[?25hRequirement already satisfied: google-api-python-client>=1.6.7 in /usr/local/lib/python3.6/dist-packages (from tf-models-nightly->tflite-model-maker) (1.7.12)
Requirement already satisfied: gin-config in /usr/local/lib/python3.6/dist-packages (from tf-models-nightly->tflite-model-maker) (0.3.0)
Requirement already satisfied: tensorflow-addons in /usr/local/lib/python3.6/dist-packages (from tf-models-nightly->tflite-model-maker) (0.8.3)
Requirement already satisfied: google-cloud-bigquery>=0.31.0 in /usr/local/lib/python3.6/dist-packages (from tf-models-nightly->tflite-model-maker) (1.21.0)
Collecting pybind11>=2.4
[?25l Downloading https://files.pythonhosted.org/packages/89/e3/d576f6f02bc75bacbc3d42494e8f1d063c95617d86648dba243c2cb3963e/pybind11-2.5.0-py2.py3-none-any.whl (296kB)
[K |████████████████████████████████| 296kB 47.9MB/s
[?25hRequirement already satisfied: promise in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets>=2.1.0->tflite-model-maker) (2.3)
Requirement already satisfied: tensorflow-metadata in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets>=2.1.0->tflite-model-maker) (0.24.0)
Requirement already satisfied: requests>=2.19.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets>=2.1.0->tflite-model-maker) (2.23.0)
Requirement already satisfied: dill in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets>=2.1.0->tflite-model-maker) (0.3.2)
Requirement already satisfied: attrs>=18.1.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets>=2.1.0->tflite-model-maker) (20.2.0)
Requirement already satisfied: tqdm in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets>=2.1.0->tflite-model-maker) (4.41.1)
Requirement already satisfied: future in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets>=2.1.0->tflite-model-maker) (0.16.0)
Requirement already satisfied: werkzeug>=0.11.15 in /usr/local/lib/python3.6/dist-packages (from tb-nightly<3.0.0a0,>=2.4.0a0->tf-nightly->tflite-model-maker) (1.0.1)
Requirement already satisfied: setuptools>=41.0.0 in /usr/local/lib/python3.6/dist-packages (from tb-nightly<3.0.0a0,>=2.4.0a0->tf-nightly->tflite-model-maker) (50.3.0)
Requirement already satisfied: tensorboard-plugin-wit>=1.6.0 in /usr/local/lib/python3.6/dist-packages (from tb-nightly<3.0.0a0,>=2.4.0a0->tf-nightly->tflite-model-maker) (1.7.0)
Requirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /usr/local/lib/python3.6/dist-packages (from tb-nightly<3.0.0a0,>=2.4.0a0->tf-nightly->tflite-model-maker) (0.4.1)
Requirement already satisfied: google-auth<2,>=1.6.3 in /usr/local/lib/python3.6/dist-packages (from tb-nightly<3.0.0a0,>=2.4.0a0->tf-nightly->tflite-model-maker) (1.17.2)
Requirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.6/dist-packages (from tb-nightly<3.0.0a0,>=2.4.0a0->tf-nightly->tflite-model-maker) (3.2.2)
Requirement already satisfied: dm-tree~=0.1.1 in /usr/local/lib/python3.6/dist-packages (from tensorflow-model-optimization>=0.4.1->tf-models-nightly->tflite-model-maker) (0.1.5)
Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.6/dist-packages (from pandas>=0.22.0->tf-models-nightly->tflite-model-maker) (2018.9)
Requirement already satisfied: python-dateutil>=2.6.1 in /usr/local/lib/python3.6/dist-packages (from pandas>=0.22.0->tf-models-nightly->tflite-model-maker) (2.8.1)
Requirement already satisfied: certifi in /usr/local/lib/python3.6/dist-packages (from kaggle>=1.3.9->tf-models-nightly->tflite-model-maker) (2020.6.20)
Requirement already satisfied: python-slugify in /usr/local/lib/python3.6/dist-packages (from kaggle>=1.3.9->tf-models-nightly->tflite-model-maker) (4.0.1)
Requirement already satisfied: slugify in /usr/local/lib/python3.6/dist-packages (from kaggle>=1.3.9->tf-models-nightly->tflite-model-maker) (0.0.1)
Requirement already satisfied: urllib3<1.25,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from kaggle>=1.3.9->tf-models-nightly->tflite-model-maker) (1.24.3)
Requirement already satisfied: pyasn1>=0.1.7 in /usr/local/lib/python3.6/dist-packages (from oauth2client->tf-models-nightly->tflite-model-maker) (0.4.8)
Requirement already satisfied: rsa>=3.1.4 in /usr/local/lib/python3.6/dist-packages (from oauth2client->tf-models-nightly->tflite-model-maker) (4.6)
Requirement already satisfied: httplib2>=0.9.1 in /usr/local/lib/python3.6/dist-packages (from oauth2client->tf-models-nightly->tflite-model-maker) (0.17.4)
Requirement already satisfied: pyasn1-modules>=0.0.5 in /usr/local/lib/python3.6/dist-packages (from oauth2client->tf-models-nightly->tflite-model-maker) (0.2.8)
Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib->tf-models-nightly->tflite-model-maker) (1.2.0)
Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib->tf-models-nightly->tflite-model-maker) (2.4.7)
Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.6/dist-packages (from matplotlib->tf-models-nightly->tflite-model-maker) (0.10.0)
Requirement already satisfied: Keras>=2.2.4 in /usr/local/lib/python3.6/dist-packages (from seqeval->tf-models-nightly->tflite-model-maker) (2.4.3)
Requirement already satisfied: google-auth-httplib2>=0.0.3 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client>=1.6.7->tf-models-nightly->tflite-model-maker) (0.0.4)
Requirement already satisfied: uritemplate<4dev,>=3.0.0 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client>=1.6.7->tf-models-nightly->tflite-model-maker) (3.0.1)
Requirement already satisfied: typeguard in /usr/local/lib/python3.6/dist-packages (from tensorflow-addons->tf-models-nightly->tflite-model-maker) (2.7.1)
Requirement already satisfied: google-cloud-core<2.0dev,>=1.0.3 in /usr/local/lib/python3.6/dist-packages (from google-cloud-bigquery>=0.31.0->tf-models-nightly->tflite-model-maker) (1.0.3)
Requirement already satisfied: google-resumable-media!=0.4.0,<0.5.0dev,>=0.3.1 in /usr/local/lib/python3.6/dist-packages (from google-cloud-bigquery>=0.31.0->tf-models-nightly->tflite-model-maker) (0.4.1)
Requirement already satisfied: googleapis-common-protos<2,>=1.52.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow-metadata->tensorflow-datasets>=2.1.0->tflite-model-maker) (1.52.0)
Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests>=2.19.0->tensorflow-datasets>=2.1.0->tflite-model-maker) (3.0.4)
Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests>=2.19.0->tensorflow-datasets>=2.1.0->tflite-model-maker) (2.10)
Requirement already satisfied: requests-oauthlib>=0.7.0 in /usr/local/lib/python3.6/dist-packages (from google-auth-oauthlib<0.5,>=0.4.1->tb-nightly<3.0.0a0,>=2.4.0a0->tf-nightly->tflite-model-maker) (1.3.0)
Requirement already satisfied: cachetools<5.0,>=2.0.0 in /usr/local/lib/python3.6/dist-packages (from google-auth<2,>=1.6.3->tb-nightly<3.0.0a0,>=2.4.0a0->tf-nightly->tflite-model-maker) (4.1.1)
Requirement already satisfied: importlib-metadata; python_version < "3.8" in /usr/local/lib/python3.6/dist-packages (from markdown>=2.6.8->tb-nightly<3.0.0a0,>=2.4.0a0->tf-nightly->tflite-model-maker) (1.7.0)
Requirement already satisfied: text-unidecode>=1.3 in /usr/local/lib/python3.6/dist-packages (from python-slugify->kaggle>=1.3.9->tf-models-nightly->tflite-model-maker) (1.3)
Requirement already satisfied: google-api-core<2.0.0dev,>=1.14.0 in /usr/local/lib/python3.6/dist-packages (from google-cloud-core<2.0dev,>=1.0.3->google-cloud-bigquery>=0.31.0->tf-models-nightly->tflite-model-maker) (1.16.0)
Requirement already satisfied: oauthlib>=3.0.0 in /usr/local/lib/python3.6/dist-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tb-nightly<3.0.0a0,>=2.4.0a0->tf-nightly->tflite-model-maker) (3.1.0)
Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.6/dist-packages (from importlib-metadata; python_version < "3.8"->markdown>=2.6.8->tb-nightly<3.0.0a0,>=2.4.0a0->tf-nightly->tflite-model-maker) (3.1.0)
Building wheels for collected packages: fire, pyyaml, seqeval, py-cpuinfo
Building wheel for fire (setup.py) ... [?25l[?25hdone
Created wheel for fire: filename=fire-0.3.1-py2.py3-none-any.whl size=111005 sha256=f0b82e6b31e21d6db3591478a37188c727533acefe415b16b456c85ef9bef47c
Stored in directory: /root/.cache/pip/wheels/c1/61/df/768b03527bf006b546dce284eb4249b185669e65afc5fbb2ac
Building wheel for pyyaml (setup.py) ... [?25l[?25hdone
Created wheel for pyyaml: filename=PyYAML-5.3.1-cp36-cp36m-linux_x86_64.whl size=44619 sha256=cdbc63ead8369d7403f47b1adff163ebde2636c9f0c2a5ebd6413d156b2b7a9f
Stored in directory: /root/.cache/pip/wheels/a7/c1/ea/cf5bd31012e735dc1dfea3131a2d5eae7978b251083d6247bd
Building wheel for seqeval (setup.py) ... [?25l[?25hdone
Created wheel for seqeval: filename=seqeval-0.0.12-cp36-none-any.whl size=7423 sha256=3ac4a1cc3b88a9b1a1ed8217f2b8d3abb7f936e853383025888b94019d98a856
Stored in directory: /root/.cache/pip/wheels/4f/32/0a/df3b340a82583566975377d65e724895b3fad101a3fb729f68
Building wheel for py-cpuinfo (setup.py) ... [?25l[?25hdone
Created wheel for py-cpuinfo: filename=py_cpuinfo-7.0.0-cp36-none-any.whl size=20071 sha256=b5491e6fcabbf9ae464c0def53ec6ec27bbf01230ff96f4e34c6a7c44d55d5c9
Stored in directory: /root/.cache/pip/wheels/f1/93/7b/127daf0c3a5a49feb2fecd468d508067c733fba5192f726ad1
Successfully built fire pyyaml seqeval py-cpuinfo
Installing collected packages: tb-nightly, flatbuffers, tf-estimator-nightly, tf-nightly, pyyaml, tensorflow-model-optimization, opencv-python-headless, sentencepiece, tf-slim, seqeval, py-cpuinfo, tf-models-nightly, fire, pybind11, tflite-support, tflite-model-maker
Found existing installation: PyYAML 3.13
Uninstalling PyYAML-3.13:
Successfully uninstalled PyYAML-3.13
Successfully installed fire-0.3.1 flatbuffers-1.12 opencv-python-headless-4.4.0.42 py-cpuinfo-7.0.0 pybind11-2.5.0 pyyaml-5.3.1 sentencepiece-0.1.91 seqeval-0.0.12 tb-nightly-2.4.0a20200914 tensorflow-model-optimization-0.5.0 tf-estimator-nightly-2.4.0.dev2020091401 tf-models-nightly-2.3.0.dev20200914 tf-nightly-2.4.0.dev20200914 tf-slim-1.1.0 tflite-model-maker-0.1.2 tflite-support-0.1.0rc3.dev2
###Markdown
Import the required packages.
###Code
import numpy as np
import os
import tensorflow as tf
assert tf.__version__.startswith('2')
from tflite_model_maker import configs
from tflite_model_maker import ExportFormat
from tflite_model_maker import model_spec
from tflite_model_maker import question_answer
from tflite_model_maker import QuestionAnswerDataLoader
###Output
_____no_output_____
###Markdown
The "End-to-End Overview" demonstrates a simple end-to-end example. The following sections walk through the example step by step to show more detail. Choose a model_spec that represents a model for question answerEach `model_spec` object represents a specific model for question answer. The Model Maker currently supports MobileBERT and BERT-Base models.Supported Model | Name of model_spec | Model Description--- | --- | ---[MobileBERT](https://arxiv.org/pdf/2004.02984.pdf) | 'mobilebert_qa' | 4.3x smaller and 5.5x faster than BERT-Base while achieving competitive results, suitable for on-device scenario.[MobileBERT-SQuAD](https://arxiv.org/pdf/2004.02984.pdf) | 'mobilebert_qa_squad' | Same model architecture as MobileBERT model and the initial model is already retrained on [SQuAD1.1](https://rajpurkar.github.io/SQuAD-explorer/).[BERT-Base](https://arxiv.org/pdf/1810.04805.pdf) | 'bert_qa' | Standard BERT model that widely used in NLP tasks.In this tutorial, [MobileBERT-SQuAD](https://arxiv.org/pdf/2004.02984.pdf) is used as an example. Since the model is already retrained on [SQuAD1.1](https://rajpurkar.github.io/SQuAD-explorer/), it could coverage faster for question answer task.
###Code
spec = model_spec.get('mobilebert_qa_squad')
###Output
_____no_output_____
###Markdown
Load Input Data Specific to an On-device ML App and Preprocess the DataThe [TriviaQA](https://nlp.cs.washington.edu/triviaqa/) is a reading comprehension dataset containing over 650K question-answer-evidence triples. In this tutorial, you will use a subset of this dataset to learn how to use the Model Maker library.To load the data, convert the TriviaQA dataset to the [SQuAD1.1](https://rajpurkar.github.io/SQuAD-explorer/) format by running the [converter Python script](https://github.com/mandarjoshi90/triviaqamiscellaneous) with `--sample_size=8000` and a set of `web` data. Modify the conversion code a little bit by:* Skipping the samples that couldn't find any answer in the context document;* Getting the original answer in the context without uppercase or lowercase.Download the archived version of the already converted dataset.
###Code
train_data_path = tf.keras.utils.get_file(
fname='triviaqa-web-train-8000.json',
origin='https://storage.googleapis.com/download.tensorflow.org/models/tflite/dataset/triviaqa-web-train-8000.json')
validation_data_path = tf.keras.utils.get_file(
fname='triviaqa-verified-web-dev.json',
origin='https://storage.googleapis.com/download.tensorflow.org/models/tflite/dataset/triviaqa-verified-web-dev.json')
###Output
Downloading data from https://storage.googleapis.com/download.tensorflow.org/models/tflite/dataset/triviaqa-web-train-8000.json
32571392/32570663 [==============================] - 1s 0us/step
Downloading data from https://storage.googleapis.com/download.tensorflow.org/models/tflite/dataset/triviaqa-verified-web-dev.json
1171456/1167744 [==============================] - 0s 0us/step
###Markdown
You can also train the MobileBERT model with your own dataset. If you are running this notebook on Colab, upload your data by using the left sidebar.If you prefer not to upload your data to the cloud, you can also run the library offline by following the [guide](https://github.com/tensorflow/examples/tree/master/tensorflow_examples/lite/model_maker). Use the `QuestionAnswerDataLoader.from_squad` method to load and preprocess the [SQuAD format](https://rajpurkar.github.io/SQuAD-explorer/) data according to a specific `model_spec`. You can use either SQuAD2.0 or SQuAD1.1 formats. Setting parameter `version_2_with_negative` as `True` means the formats is SQuAD2.0. Otherwise, the format is SQuAD1.1. By default, `version_2_with_negative` is `False`.
###Code
train_data = QuestionAnswerDataLoader.from_squad(train_data_path, spec, is_training=True)
validation_data = QuestionAnswerDataLoader.from_squad(validation_data_path, spec, is_training=False)
###Output
_____no_output_____
###Markdown
Customize the TensorFlow ModelCreate a custom question answer model based on the loaded data. The `create` function comprises the following steps:1. Creates the model for question answer according to `model_spec`.2. Train the question answer model. The default epochs and the default batch size are set according to two variables `default_training_epochs` and `default_batch_size` in the `model_spec` object.
###Code
model = question_answer.create(train_data, model_spec=spec)
###Output
INFO:tensorflow:Retraining the models...
###Markdown
Have a look at the detailed model structure.
###Code
model.summary()
###Output
_____no_output_____
###Markdown
Evaluate the Customized ModelEvaluate the model on the validation data and get a dict of metrics including `f1` score and `exact match` etc. Note that metrics are different for SQuAD1.1 and SQuAD2.0.
###Code
model.evaluate(validation_data)
###Output
_____no_output_____
###Markdown
Export to TensorFlow Lite ModelConvert the existing model to TensorFlow Lite model format that you can later use in an on-device ML application. Since MobileBERT is too big for on-device applications, use dynamic range quantization on the model to compress MobileBERT by 4x with the minimal loss of performance. First, define the quantization configuration:
###Code
config = configs.QuantizationConfig.create_dynamic_range_quantization(optimizations=[tf.lite.Optimize.OPTIMIZE_FOR_LATENCY])
config._experimental_new_quantizer = True
###Output
_____no_output_____
###Markdown
Export the quantized TFLite model according to the quantization config with [metadata](https://www.tensorflow.org/lite/convert/metadata). The default TFLite model filename is `model.tflite`.
###Code
model.export(export_dir='.', quantization_config=config)
###Output
_____no_output_____
###Markdown
You can use the TensorFlow Lite model file in the [bert_qa](https://github.com/tensorflow/examples/tree/master/lite/examples/bert_qa/android) reference app using [BertQuestionAnswerer API](https://www.tensorflow.org/lite/inference_with_metadata/task_library/bert_question_answerer) in [TensorFlow Lite Task Library](https://www.tensorflow.org/lite/inference_with_metadata/task_library/overview) by downloading it from the left sidebar on Colab. The allowed export formats can be one or a list of the following:* `ExportFormat.TFLITE`* `ExportFormat.VOCAB`* `ExportFormat.SAVED_MODEL`By default, it just exports TensorFlow Lite model with metadata. You can also selectively export different files. For instance, exporting only the vocab file as follows:
###Code
model.export(export_dir='.', export_format=ExportFormat.VOCAB)
###Output
_____no_output_____
###Markdown
You can also evaluate the tflite model with the `evaluate_tflite` method. This step is expected to take a long time.
###Code
model.evaluate_tflite('model.tflite', validation_data)
###Output
_____no_output_____
###Markdown
Advanced UsageThe `create` function is the critical part of this library in which the `model_spec` parameter defines the model specification. The `BertQAModelSpec` class is currently supported. There are 2 models: MobileBERT model, BERT-Base model. The `create` function comprises the following steps:1. Creates the model for question answer according to `model_spec`.2. Train the question answer model.This section describes several advanced topics, including adjusting the model, tuning the training hyperparameters etc. Adjust the modelYou can adjust the model infrastructure like parameters `seq_len` and `query_len` in the `BertQAModelSpec` class.Adjustable parameters for model:* `seq_len`: Length of the passage to feed into the model.* `query_len`: Length of the question to feed into the model.* `doc_stride`: The stride when doing a sliding window approach to take chunks of the documents.* `initializer_range`: The stdev of the truncated_normal_initializer for initializing all weight matrices.* `trainable`: Boolean, whether pre-trained layer is trainable.Adjustable parameters for training pipeline:* `model_dir`: The location of the model checkpoint files. If not set, temporary directory will be used.* `dropout_rate`: The rate for dropout.* `learning_rate`: The initial learning rate for Adam.* `predict_batch_size`: Batch size for prediction.* `tpu`: TPU address to connect to. Only used if using tpu. For example, you can train the model with a longer sequence length. If you change the model, you must first construct a new `model_spec`.
###Code
new_spec = model_spec.get('mobilebert_qa')
new_spec.seq_len = 512
###Output
_____no_output_____
###Markdown
Copyright 2020 The TensorFlow Authors.
###Code
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###Output
_____no_output_____
###Markdown
Question Answer with TensorFlow Lite Model Maker View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook The TensorFlow Lite Model Maker library simplifies the process of adapting and converting a TensorFlow model to particular input data when deploying this model for on-device ML applications.This notebook shows an end-to-end example that utilizes the Model Maker library to illustrate the adaptation and conversion of a commonly-used question answer model for question answer task. Introduction to Question Answer Task The supported task in this library is extractive question answer task, which means given a passage and a question, the answer is the span in the passage. The image below shows an example for question answer. Answers are spans in the passage (image credit: SQuAD blog) As for the model of question answer task, the inputs should be the passage and question pair that are already preprocessed, the outputs should be the start logits and end logits for each token in the passage.The size of input could be set and adjusted according to the length of passage and question. End-to-End Overview The following code snippet demonstrates how to get the model within a few lines of code. The overall process includes 5 steps: (1) choose a model, (2) load data, (3) retrain the model, (4) evaluate, and (5) export it to TensorFlow Lite format. ```python Chooses a model specification that represents the model.spec = model_spec.get('mobilebert_qa') Gets the training data and validation data.train_data = QuestionAnswerDataLoader.from_squad(train_data_path, spec, is_training=True)validation_data = QuestionAnswerDataLoader.from_squad(validation_data_path, spec, is_training=False) Fine-tunes the model.model = question_answer.create(train_data, model_spec=spec) Gets the evaluation result.metric = model.evaluate(validation_data) Exports the model to the TensorFlow Lite format in the export directory.model.export(export_dir)``` The following sections explain the code in more detail. PrerequisitesTo run this example, install the required packages, including the Model Maker package from the [GitHub repo](https://github.com/tensorflow/examples/tree/master/tensorflow_examples/lite/model_maker).
###Code
!pip install tflite-model-maker
###Output
_____no_output_____
###Markdown
Import the required packages.
###Code
import numpy as np
import os
import tensorflow as tf
assert tf.__version__.startswith('2')
from tflite_model_maker import configs
from tflite_model_maker import model_spec
from tflite_model_maker import question_answer
from tflite_model_maker import QuestionAnswerDataLoader
###Output
_____no_output_____
###Markdown
The "End-to-End Overview" demonstrates a simple end-to-end example. The following sections walk through the example step by step to show more detail. Choose a model_spec that represents a model for question answerEach `model_spec` object represents a specific model for question answer. The Model Maker currently supports MobileBERT and BERT-Base models.Supported Model | Name of model_spec | Model Description--- | --- | ---[MobileBERT](https://arxiv.org/pdf/2004.02984.pdf) | 'mobilebert_qa' | 4.3x smaller and 5.5x faster than BERT-Base while achieving competitive results, suitable for on-device scenario.[MobileBERT-SQuAD](https://arxiv.org/pdf/2004.02984.pdf) | 'mobilebert_qa_squad' | Same model architecture as MobileBERT model and the initial model is already retrained on [SQuAD1.1](https://rajpurkar.github.io/SQuAD-explorer/).[BERT-Base](https://arxiv.org/pdf/1810.04805.pdf) | 'bert_qa' | Standard BERT model that widely used in NLP tasks.In this tutorial, [MobileBERT-SQuAD](https://arxiv.org/pdf/2004.02984.pdf) is used as an example. Since the model is already retrained on [SQuAD1.1](https://rajpurkar.github.io/SQuAD-explorer/), it could coverage faster for question answer task.
###Code
spec = model_spec.get('mobilebert_qa_squad')
###Output
_____no_output_____
###Markdown
Load Input Data Specific to an On-device ML App and Preprocess the DataThe [TriviaQA](https://nlp.cs.washington.edu/triviaqa/) is a reading comprehension dataset containing over 650K question-answer-evidence triples. In this tutorial, you will use a subset of this dataset to learn how to use the Model Maker library.To load the data, convert the TriviaQA dataset to the [SQuAD1.1](https://rajpurkar.github.io/SQuAD-explorer/) format by running the [converter Python script](https://github.com/mandarjoshi90/triviaqamiscellaneous) with `--sample_size=8000` and a set of `web` data. Modify the conversion code a little bit by:* Skipping the samples that couldn't find any answer in the context document;* Getting the original answer in the context without uppercase or lowercase.Download the archived version of the already converted dataset.
###Code
train_data_path = tf.keras.utils.get_file(
fname='triviaqa-web-train-8000.json',
origin='https://storage.googleapis.com/download.tensorflow.org/models/tflite/dataset/triviaqa-web-train-8000.json')
validation_data_path = tf.keras.utils.get_file(
fname='triviaqa-verified-web-dev.json',
origin='https://storage.googleapis.com/download.tensorflow.org/models/tflite/dataset/triviaqa-verified-web-dev.json')
###Output
_____no_output_____
###Markdown
You can also train the MobileBERT model with your own dataset. If you are running this notebook on Colab, upload your data by using the left sidebar.If you prefer not to upload your data to the cloud, you can also run the library offline by following the [guide](https://github.com/tensorflow/examples/tree/master/tensorflow_examples/lite/model_maker). Use the `QuestionAnswerDataLoader.from_squad` method to load and preprocess the [SQuAD format](https://rajpurkar.github.io/SQuAD-explorer/) data according to a specific `model_spec`. You can use either SQuAD2.0 or SQuAD1.1 formats. Setting parameter `version_2_with_negative` as `True` means the formats is SQuAD2.0. Otherwise, the format is SQuAD1.1. By default, `version_2_with_negative` is `False`.
###Code
train_data = QuestionAnswerDataLoader.from_squad(train_data_path, spec, is_training=True)
validation_data = QuestionAnswerDataLoader.from_squad(validation_data_path, spec, is_training=False)
###Output
_____no_output_____
###Markdown
Customize the TensorFlow ModelCreate a custom question answer model based on the loaded data. The `create` function comprises the following steps:1. Creates the model for question answer according to `model_spec`.2. Train the question answer model. The default epochs and the default batch size are set according to two variables `default_training_epochs` and `default_batch_size` in the `model_spec` object.
###Code
model = question_answer.create(train_data, model_spec=spec)
###Output
_____no_output_____
###Markdown
Have a look at the detailed model structure.
###Code
model.summary()
###Output
_____no_output_____
###Markdown
Evaluate the Customized ModelEvaluate the model on the validation data and get a dict of metrics including `f1` score and `exact match` etc. Note that metrics are different for SQuAD1.1 and SQuAD2.0.
###Code
model.evaluate(validation_data)
###Output
_____no_output_____
###Markdown
Export to TensorFlow Lite ModelConvert the existing model to TensorFlow Lite model format that you can later use in an on-device ML application. Since MobileBERT is too big for on-device applications, use dynamic range quantization on the model to compress MobileBERT by 4x with the minimal loss of performance. First, define the quantization configuration:
###Code
config = configs.QuantizationConfig.create_dynamic_range_quantization(optimizations=[tf.lite.Optimize.OPTIMIZE_FOR_LATENCY])
config._experimental_new_quantizer = True
###Output
_____no_output_____
###Markdown
Export the quantized TFLite model according to the quantization config and save the vocabulary to a vocab file. The default TFLite model filename is `model.tflite`, and the default vocab filename is `vocab`.
###Code
model.export(export_dir='.', quantization_config=config)
###Output
_____no_output_____
###Markdown
You can use the TensorFlow Lite model file and vocab file in the [bert_qa](https://github.com/tensorflow/examples/tree/master/lite/examples/bert_qa/android) reference app by downloading it from the left sidebar on Colab. You can also evalute the tflite model with the `evaluate_tflite` method. This step is expected to take a long time.
###Code
model.evaluate_tflite('model.tflite', validation_data)
###Output
_____no_output_____
###Markdown
Advanced UsageThe `create` function is the critical part of this library in which the `model_spec` parameter defines the model specification. The `BertQAModelSpec` class is currently supported. There are 2 models: MobileBERT model, BERT-Base model. The `create` function comprises the following steps:1. Creates the model for question answer according to `model_spec`.2. Train the question answer model.This section describes several advanced topics, including adjusting the model, tuning the training hyperparameters etc. Adjust the modelYou can adjust the model infrastructure like parameters `seq_len` and `query_len` in the `BertQAModelSpec` class.Adjustable parameters for model:* `seq_len`: Length of the passage to feed into the model.* `query_len`: Length of the question to feed into the model.* `doc_stride`: The stride when doing a sliding window approach to take chunks of the documents.* `initializer_range`: The stdev of the truncated_normal_initializer for initializing all weight matrices.* `trainable`: Boolean, whether pre-trained layer is trainable.Adjustable parameters for training pipeline:* `model_dir`: The location of the model checkpoint files. If not set, temporary directory will be used.* `dropout_rate`: The rate for dropout.* `learning_rate`: The initial learning rate for Adam.* `predict_batch_size`: Batch size for prediction.* `tpu`: TPU address to connect to. Only used if using tpu. For example, you can train the model with a longer sequence length. If you change the model, you must first construct a new `model_spec`.
###Code
new_spec = model_spec.get('mobilebert_qa')
new_spec.seq_len = 512
###Output
_____no_output_____
###Markdown
Copyright 2020 The TensorFlow Authors.
###Code
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###Output
_____no_output_____
###Markdown
BERT Question Answer with TensorFlow Lite Model Maker View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook The TensorFlow Lite Model Maker library simplifies the process of adapting and converting a TensorFlow model to particular input data when deploying this model for on-device ML applications.This notebook shows an end-to-end example that utilizes the Model Maker library to illustrate the adaptation and conversion of a commonly-used question answer model for question answer task. Introduction to BERT Question Answer Task The supported task in this library is extractive question answer task, which means given a passage and a question, the answer is the span in the passage. The image below shows an example for question answer. Answers are spans in the passage (image credit: SQuAD blog) As for the model of question answer task, the inputs should be the passage and question pair that are already preprocessed, the outputs should be the start logits and end logits for each token in the passage.The size of input could be set and adjusted according to the length of passage and question. End-to-End Overview The following code snippet demonstrates how to get the model within a few lines of code. The overall process includes 5 steps: (1) choose a model, (2) load data, (3) retrain the model, (4) evaluate, and (5) export it to TensorFlow Lite format. ```python Chooses a model specification that represents the model.spec = model_spec.get('mobilebert_qa') Gets the training data and validation data.train_data = QuestionAnswerDataLoader.from_squad(train_data_path, spec, is_training=True)validation_data = QuestionAnswerDataLoader.from_squad(validation_data_path, spec, is_training=False) Fine-tunes the model.model = question_answer.create(train_data, model_spec=spec) Gets the evaluation result.metric = model.evaluate(validation_data) Exports the model to the TensorFlow Lite format with metadata in the export directory.model.export(export_dir)``` The following sections explain the code in more detail. PrerequisitesTo run this example, install the required packages, including the Model Maker package from the [GitHub repo](https://github.com/tensorflow/examples/tree/master/tensorflow_examples/lite/model_maker).
###Code
!pip install tflite-model-maker
###Output
Collecting tflite-model-maker
[?25l Downloading https://files.pythonhosted.org/packages/13/bc/4c23b9cb9ef612a1f48bac5543bd531665de5eab8f8231111aac067f8c30/tflite_model_maker-0.1.2-py3-none-any.whl (104kB)
[K |███▏ | 10kB 28.4MB/s eta 0:00:01
[K |██████▎ | 20kB 1.8MB/s eta 0:00:01
[K |█████████▍ | 30kB 2.4MB/s eta 0:00:01
[K |████████████▋ | 40kB 2.7MB/s eta 0:00:01
[K |███████████████▊ | 51kB 2.1MB/s eta 0:00:01
[K |██████████████████▉ | 61kB 2.4MB/s eta 0:00:01
[K |██████████████████████ | 71kB 2.7MB/s eta 0:00:01
[K |█████████████████████████▏ | 81kB 2.9MB/s eta 0:00:01
[K |████████████████████████████▎ | 92kB 3.1MB/s eta 0:00:01
[K |███████████████████████████████▌| 102kB 3.0MB/s eta 0:00:01
[K |████████████████████████████████| 112kB 3.0MB/s
[?25hRequirement already satisfied: absl-py in /usr/local/lib/python3.6/dist-packages (from tflite-model-maker) (0.10.0)
Collecting tf-nightly
[?25l Downloading https://files.pythonhosted.org/packages/33/d4/61c47ae889b490b9c5f07f4f61bdc057c158a1a1979c375fa019d647a19e/tf_nightly-2.4.0.dev20200914-cp36-cp36m-manylinux2010_x86_64.whl (390.1MB)
[K |████████████████████████████████| 390.2MB 43kB/s
[?25hRequirement already satisfied: numpy>=1.17.3 in /usr/local/lib/python3.6/dist-packages (from tflite-model-maker) (1.18.5)
Requirement already satisfied: pillow in /usr/local/lib/python3.6/dist-packages (from tflite-model-maker) (7.0.0)
Collecting tf-models-nightly
[?25l Downloading https://files.pythonhosted.org/packages/d3/e9/c4e5a451c268a5a75a27949562364f6086f6bb33b226a065a8beceefa9ba/tf_models_nightly-2.3.0.dev20200914-py2.py3-none-any.whl (993kB)
[K |████████████████████████████████| 1.0MB 57.6MB/s
[?25hCollecting flatbuffers==1.12
Downloading https://files.pythonhosted.org/packages/eb/26/712e578c5f14e26ae3314c39a1bdc4eb2ec2f4ddc89b708cf8e0a0d20423/flatbuffers-1.12-py2.py3-none-any.whl
Requirement already satisfied: tensorflow-hub>=0.8.0 in /usr/local/lib/python3.6/dist-packages (from tflite-model-maker) (0.9.0)
Collecting fire
[?25l Downloading https://files.pythonhosted.org/packages/34/a7/0e22e70778aca01a52b9c899d9c145c6396d7b613719cd63db97ffa13f2f/fire-0.3.1.tar.gz (81kB)
[K |████████████████████████████████| 81kB 11.5MB/s
[?25hCollecting sentencepiece
[?25l Downloading https://files.pythonhosted.org/packages/d4/a4/d0a884c4300004a78cca907a6ff9a5e9fe4f090f5d95ab341c53d28cbc58/sentencepiece-0.1.91-cp36-cp36m-manylinux1_x86_64.whl (1.1MB)
[K |████████████████████████████████| 1.1MB 50.9MB/s
[?25hCollecting tflite-support==0.1.0rc3.dev2
[?25l Downloading https://files.pythonhosted.org/packages/fa/c5/5e9ee3abd5b4ef8294432cd714407f49a66befa864905b66ee8bdc612795/tflite_support-0.1.0rc3.dev2-cp36-cp36m-manylinux2010_x86_64.whl (1.0MB)
[K |████████████████████████████████| 1.0MB 50.9MB/s
[?25hRequirement already satisfied: tensorflow-datasets>=2.1.0 in /usr/local/lib/python3.6/dist-packages (from tflite-model-maker) (2.1.0)
Requirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from absl-py->tflite-model-maker) (1.15.0)
Requirement already satisfied: termcolor>=1.1.0 in /usr/local/lib/python3.6/dist-packages (from tf-nightly->tflite-model-maker) (1.1.0)
Requirement already satisfied: opt-einsum>=2.3.2 in /usr/local/lib/python3.6/dist-packages (from tf-nightly->tflite-model-maker) (3.3.0)
Collecting tb-nightly<3.0.0a0,>=2.4.0a0
[?25l Downloading https://files.pythonhosted.org/packages/fc/cb/4dfe0d65bffb5e9663261ff664e6f5a2d37672b31dae27a0f14721ac00d3/tb_nightly-2.4.0a20200914-py3-none-any.whl (10.1MB)
[K |████████████████████████████████| 10.1MB 51.4MB/s
[?25hRequirement already satisfied: typing-extensions>=3.7.4.2 in /usr/local/lib/python3.6/dist-packages (from tf-nightly->tflite-model-maker) (3.7.4.3)
Requirement already satisfied: wheel>=0.26 in /usr/local/lib/python3.6/dist-packages (from tf-nightly->tflite-model-maker) (0.35.1)
Collecting tf-estimator-nightly
[?25l Downloading https://files.pythonhosted.org/packages/bd/9a/3bfb9994eda11e426c809ebdf434e2ac5824a0784d980018bb53fd1620ec/tf_estimator_nightly-2.4.0.dev2020091401-py2.py3-none-any.whl (460kB)
[K |████████████████████████████████| 460kB 36.0MB/s
[?25hRequirement already satisfied: google-pasta>=0.1.8 in /usr/local/lib/python3.6/dist-packages (from tf-nightly->tflite-model-maker) (0.2.0)
Requirement already satisfied: h5py<2.11.0,>=2.10.0 in /usr/local/lib/python3.6/dist-packages (from tf-nightly->tflite-model-maker) (2.10.0)
Requirement already satisfied: keras-preprocessing<1.2,>=1.1.1 in /usr/local/lib/python3.6/dist-packages (from tf-nightly->tflite-model-maker) (1.1.2)
Requirement already satisfied: wrapt>=1.11.1 in /usr/local/lib/python3.6/dist-packages (from tf-nightly->tflite-model-maker) (1.12.1)
Requirement already satisfied: grpcio>=1.8.6 in /usr/local/lib/python3.6/dist-packages (from tf-nightly->tflite-model-maker) (1.32.0)
Requirement already satisfied: protobuf>=3.9.2 in /usr/local/lib/python3.6/dist-packages (from tf-nightly->tflite-model-maker) (3.12.4)
Requirement already satisfied: gast==0.3.3 in /usr/local/lib/python3.6/dist-packages (from tf-nightly->tflite-model-maker) (0.3.3)
Requirement already satisfied: astunparse==1.6.3 in /usr/local/lib/python3.6/dist-packages (from tf-nightly->tflite-model-maker) (1.6.3)
Requirement already satisfied: scipy>=0.19.1 in /usr/local/lib/python3.6/dist-packages (from tf-models-nightly->tflite-model-maker) (1.4.1)
Collecting pyyaml>=5.1
[?25l Downloading https://files.pythonhosted.org/packages/64/c2/b80047c7ac2478f9501676c988a5411ed5572f35d1beff9cae07d321512c/PyYAML-5.3.1.tar.gz (269kB)
[K |████████████████████████████████| 276kB 59.8MB/s
[?25hCollecting tensorflow-model-optimization>=0.4.1
[?25l Downloading https://files.pythonhosted.org/packages/55/38/4fd48ea1bfcb0b6e36d949025200426fe9c3a8bfae029f0973d85518fa5a/tensorflow_model_optimization-0.5.0-py2.py3-none-any.whl (172kB)
[K |████████████████████████████████| 174kB 51.0MB/s
[?25hRequirement already satisfied: pandas>=0.22.0 in /usr/local/lib/python3.6/dist-packages (from tf-models-nightly->tflite-model-maker) (1.0.5)
Requirement already satisfied: dataclasses in /usr/local/lib/python3.6/dist-packages (from tf-models-nightly->tflite-model-maker) (0.7)
Requirement already satisfied: Cython in /usr/local/lib/python3.6/dist-packages (from tf-models-nightly->tflite-model-maker) (0.29.21)
Collecting opencv-python-headless
[?25l Downloading https://files.pythonhosted.org/packages/b6/2a/496e06fd289c01dc21b11970be1261c87ce1cc22d5340c14b516160822a7/opencv_python_headless-4.4.0.42-cp36-cp36m-manylinux2014_x86_64.whl (36.6MB)
[K |████████████████████████████████| 36.6MB 83kB/s
[?25hRequirement already satisfied: kaggle>=1.3.9 in /usr/local/lib/python3.6/dist-packages (from tf-models-nightly->tflite-model-maker) (1.5.8)
Requirement already satisfied: pycocotools in /usr/local/lib/python3.6/dist-packages (from tf-models-nightly->tflite-model-maker) (2.0.2)
Requirement already satisfied: oauth2client in /usr/local/lib/python3.6/dist-packages (from tf-models-nightly->tflite-model-maker) (4.1.3)
Requirement already satisfied: matplotlib in /usr/local/lib/python3.6/dist-packages (from tf-models-nightly->tflite-model-maker) (3.2.2)
Collecting tf-slim>=1.1.0
[?25l Downloading https://files.pythonhosted.org/packages/02/97/b0f4a64df018ca018cc035d44f2ef08f91e2e8aa67271f6f19633a015ff7/tf_slim-1.1.0-py2.py3-none-any.whl (352kB)
[K |████████████████████████████████| 358kB 55.9MB/s
[?25hCollecting seqeval
Downloading https://files.pythonhosted.org/packages/34/91/068aca8d60ce56dd9ba4506850e876aba5e66a6f2f29aa223224b50df0de/seqeval-0.0.12.tar.gz
Requirement already satisfied: psutil>=5.4.3 in /usr/local/lib/python3.6/dist-packages (from tf-models-nightly->tflite-model-maker) (5.4.8)
Collecting py-cpuinfo>=3.3.0
[?25l Downloading https://files.pythonhosted.org/packages/f6/f5/8e6e85ce2e9f6e05040cf0d4e26f43a4718bcc4bce988b433276d4b1a5c1/py-cpuinfo-7.0.0.tar.gz (95kB)
[K |████████████████████████████████| 102kB 13.5MB/s
[?25hRequirement already satisfied: google-api-python-client>=1.6.7 in /usr/local/lib/python3.6/dist-packages (from tf-models-nightly->tflite-model-maker) (1.7.12)
Requirement already satisfied: gin-config in /usr/local/lib/python3.6/dist-packages (from tf-models-nightly->tflite-model-maker) (0.3.0)
Requirement already satisfied: tensorflow-addons in /usr/local/lib/python3.6/dist-packages (from tf-models-nightly->tflite-model-maker) (0.8.3)
Requirement already satisfied: google-cloud-bigquery>=0.31.0 in /usr/local/lib/python3.6/dist-packages (from tf-models-nightly->tflite-model-maker) (1.21.0)
Collecting pybind11>=2.4
[?25l Downloading https://files.pythonhosted.org/packages/89/e3/d576f6f02bc75bacbc3d42494e8f1d063c95617d86648dba243c2cb3963e/pybind11-2.5.0-py2.py3-none-any.whl (296kB)
[K |████████████████████████████████| 296kB 47.9MB/s
[?25hRequirement already satisfied: promise in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets>=2.1.0->tflite-model-maker) (2.3)
Requirement already satisfied: tensorflow-metadata in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets>=2.1.0->tflite-model-maker) (0.24.0)
Requirement already satisfied: requests>=2.19.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets>=2.1.0->tflite-model-maker) (2.23.0)
Requirement already satisfied: dill in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets>=2.1.0->tflite-model-maker) (0.3.2)
Requirement already satisfied: attrs>=18.1.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets>=2.1.0->tflite-model-maker) (20.2.0)
Requirement already satisfied: tqdm in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets>=2.1.0->tflite-model-maker) (4.41.1)
Requirement already satisfied: future in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets>=2.1.0->tflite-model-maker) (0.16.0)
Requirement already satisfied: werkzeug>=0.11.15 in /usr/local/lib/python3.6/dist-packages (from tb-nightly<3.0.0a0,>=2.4.0a0->tf-nightly->tflite-model-maker) (1.0.1)
Requirement already satisfied: setuptools>=41.0.0 in /usr/local/lib/python3.6/dist-packages (from tb-nightly<3.0.0a0,>=2.4.0a0->tf-nightly->tflite-model-maker) (50.3.0)
Requirement already satisfied: tensorboard-plugin-wit>=1.6.0 in /usr/local/lib/python3.6/dist-packages (from tb-nightly<3.0.0a0,>=2.4.0a0->tf-nightly->tflite-model-maker) (1.7.0)
Requirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /usr/local/lib/python3.6/dist-packages (from tb-nightly<3.0.0a0,>=2.4.0a0->tf-nightly->tflite-model-maker) (0.4.1)
Requirement already satisfied: google-auth<2,>=1.6.3 in /usr/local/lib/python3.6/dist-packages (from tb-nightly<3.0.0a0,>=2.4.0a0->tf-nightly->tflite-model-maker) (1.17.2)
Requirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.6/dist-packages (from tb-nightly<3.0.0a0,>=2.4.0a0->tf-nightly->tflite-model-maker) (3.2.2)
Requirement already satisfied: dm-tree~=0.1.1 in /usr/local/lib/python3.6/dist-packages (from tensorflow-model-optimization>=0.4.1->tf-models-nightly->tflite-model-maker) (0.1.5)
Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.6/dist-packages (from pandas>=0.22.0->tf-models-nightly->tflite-model-maker) (2018.9)
Requirement already satisfied: python-dateutil>=2.6.1 in /usr/local/lib/python3.6/dist-packages (from pandas>=0.22.0->tf-models-nightly->tflite-model-maker) (2.8.1)
Requirement already satisfied: certifi in /usr/local/lib/python3.6/dist-packages (from kaggle>=1.3.9->tf-models-nightly->tflite-model-maker) (2020.6.20)
Requirement already satisfied: python-slugify in /usr/local/lib/python3.6/dist-packages (from kaggle>=1.3.9->tf-models-nightly->tflite-model-maker) (4.0.1)
Requirement already satisfied: slugify in /usr/local/lib/python3.6/dist-packages (from kaggle>=1.3.9->tf-models-nightly->tflite-model-maker) (0.0.1)
Requirement already satisfied: urllib3<1.25,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from kaggle>=1.3.9->tf-models-nightly->tflite-model-maker) (1.24.3)
Requirement already satisfied: pyasn1>=0.1.7 in /usr/local/lib/python3.6/dist-packages (from oauth2client->tf-models-nightly->tflite-model-maker) (0.4.8)
Requirement already satisfied: rsa>=3.1.4 in /usr/local/lib/python3.6/dist-packages (from oauth2client->tf-models-nightly->tflite-model-maker) (4.6)
Requirement already satisfied: httplib2>=0.9.1 in /usr/local/lib/python3.6/dist-packages (from oauth2client->tf-models-nightly->tflite-model-maker) (0.17.4)
Requirement already satisfied: pyasn1-modules>=0.0.5 in /usr/local/lib/python3.6/dist-packages (from oauth2client->tf-models-nightly->tflite-model-maker) (0.2.8)
Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib->tf-models-nightly->tflite-model-maker) (1.2.0)
Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib->tf-models-nightly->tflite-model-maker) (2.4.7)
Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.6/dist-packages (from matplotlib->tf-models-nightly->tflite-model-maker) (0.10.0)
Requirement already satisfied: Keras>=2.2.4 in /usr/local/lib/python3.6/dist-packages (from seqeval->tf-models-nightly->tflite-model-maker) (2.4.3)
Requirement already satisfied: google-auth-httplib2>=0.0.3 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client>=1.6.7->tf-models-nightly->tflite-model-maker) (0.0.4)
Requirement already satisfied: uritemplate<4dev,>=3.0.0 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client>=1.6.7->tf-models-nightly->tflite-model-maker) (3.0.1)
Requirement already satisfied: typeguard in /usr/local/lib/python3.6/dist-packages (from tensorflow-addons->tf-models-nightly->tflite-model-maker) (2.7.1)
Requirement already satisfied: google-cloud-core<2.0dev,>=1.0.3 in /usr/local/lib/python3.6/dist-packages (from google-cloud-bigquery>=0.31.0->tf-models-nightly->tflite-model-maker) (1.0.3)
Requirement already satisfied: google-resumable-media!=0.4.0,<0.5.0dev,>=0.3.1 in /usr/local/lib/python3.6/dist-packages (from google-cloud-bigquery>=0.31.0->tf-models-nightly->tflite-model-maker) (0.4.1)
Requirement already satisfied: googleapis-common-protos<2,>=1.52.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow-metadata->tensorflow-datasets>=2.1.0->tflite-model-maker) (1.52.0)
Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests>=2.19.0->tensorflow-datasets>=2.1.0->tflite-model-maker) (3.0.4)
Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests>=2.19.0->tensorflow-datasets>=2.1.0->tflite-model-maker) (2.10)
Requirement already satisfied: requests-oauthlib>=0.7.0 in /usr/local/lib/python3.6/dist-packages (from google-auth-oauthlib<0.5,>=0.4.1->tb-nightly<3.0.0a0,>=2.4.0a0->tf-nightly->tflite-model-maker) (1.3.0)
Requirement already satisfied: cachetools<5.0,>=2.0.0 in /usr/local/lib/python3.6/dist-packages (from google-auth<2,>=1.6.3->tb-nightly<3.0.0a0,>=2.4.0a0->tf-nightly->tflite-model-maker) (4.1.1)
Requirement already satisfied: importlib-metadata; python_version < "3.8" in /usr/local/lib/python3.6/dist-packages (from markdown>=2.6.8->tb-nightly<3.0.0a0,>=2.4.0a0->tf-nightly->tflite-model-maker) (1.7.0)
Requirement already satisfied: text-unidecode>=1.3 in /usr/local/lib/python3.6/dist-packages (from python-slugify->kaggle>=1.3.9->tf-models-nightly->tflite-model-maker) (1.3)
Requirement already satisfied: google-api-core<2.0.0dev,>=1.14.0 in /usr/local/lib/python3.6/dist-packages (from google-cloud-core<2.0dev,>=1.0.3->google-cloud-bigquery>=0.31.0->tf-models-nightly->tflite-model-maker) (1.16.0)
Requirement already satisfied: oauthlib>=3.0.0 in /usr/local/lib/python3.6/dist-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tb-nightly<3.0.0a0,>=2.4.0a0->tf-nightly->tflite-model-maker) (3.1.0)
Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.6/dist-packages (from importlib-metadata; python_version < "3.8"->markdown>=2.6.8->tb-nightly<3.0.0a0,>=2.4.0a0->tf-nightly->tflite-model-maker) (3.1.0)
Building wheels for collected packages: fire, pyyaml, seqeval, py-cpuinfo
Building wheel for fire (setup.py) ... [?25l[?25hdone
Created wheel for fire: filename=fire-0.3.1-py2.py3-none-any.whl size=111005 sha256=f0b82e6b31e21d6db3591478a37188c727533acefe415b16b456c85ef9bef47c
Stored in directory: /root/.cache/pip/wheels/c1/61/df/768b03527bf006b546dce284eb4249b185669e65afc5fbb2ac
Building wheel for pyyaml (setup.py) ... [?25l[?25hdone
Created wheel for pyyaml: filename=PyYAML-5.3.1-cp36-cp36m-linux_x86_64.whl size=44619 sha256=cdbc63ead8369d7403f47b1adff163ebde2636c9f0c2a5ebd6413d156b2b7a9f
Stored in directory: /root/.cache/pip/wheels/a7/c1/ea/cf5bd31012e735dc1dfea3131a2d5eae7978b251083d6247bd
Building wheel for seqeval (setup.py) ... [?25l[?25hdone
Created wheel for seqeval: filename=seqeval-0.0.12-cp36-none-any.whl size=7423 sha256=3ac4a1cc3b88a9b1a1ed8217f2b8d3abb7f936e853383025888b94019d98a856
Stored in directory: /root/.cache/pip/wheels/4f/32/0a/df3b340a82583566975377d65e724895b3fad101a3fb729f68
Building wheel for py-cpuinfo (setup.py) ... [?25l[?25hdone
Created wheel for py-cpuinfo: filename=py_cpuinfo-7.0.0-cp36-none-any.whl size=20071 sha256=b5491e6fcabbf9ae464c0def53ec6ec27bbf01230ff96f4e34c6a7c44d55d5c9
Stored in directory: /root/.cache/pip/wheels/f1/93/7b/127daf0c3a5a49feb2fecd468d508067c733fba5192f726ad1
Successfully built fire pyyaml seqeval py-cpuinfo
Installing collected packages: tb-nightly, flatbuffers, tf-estimator-nightly, tf-nightly, pyyaml, tensorflow-model-optimization, opencv-python-headless, sentencepiece, tf-slim, seqeval, py-cpuinfo, tf-models-nightly, fire, pybind11, tflite-support, tflite-model-maker
Found existing installation: PyYAML 3.13
Uninstalling PyYAML-3.13:
Successfully uninstalled PyYAML-3.13
Successfully installed fire-0.3.1 flatbuffers-1.12 opencv-python-headless-4.4.0.42 py-cpuinfo-7.0.0 pybind11-2.5.0 pyyaml-5.3.1 sentencepiece-0.1.91 seqeval-0.0.12 tb-nightly-2.4.0a20200914 tensorflow-model-optimization-0.5.0 tf-estimator-nightly-2.4.0.dev2020091401 tf-models-nightly-2.3.0.dev20200914 tf-nightly-2.4.0.dev20200914 tf-slim-1.1.0 tflite-model-maker-0.1.2 tflite-support-0.1.0rc3.dev2
###Markdown
Import the required packages.
###Code
import numpy as np
import os
import tensorflow as tf
assert tf.__version__.startswith('2')
from tflite_model_maker import configs
from tflite_model_maker import ExportFormat
from tflite_model_maker import model_spec
from tflite_model_maker import question_answer
from tflite_model_maker import QuestionAnswerDataLoader
###Output
_____no_output_____
###Markdown
The "End-to-End Overview" demonstrates a simple end-to-end example. The following sections walk through the example step by step to show more detail. Choose a model_spec that represents a model for question answerEach `model_spec` object represents a specific model for question answer. The Model Maker currently supports MobileBERT and BERT-Base models.Supported Model | Name of model_spec | Model Description--- | --- | ---[MobileBERT](https://arxiv.org/pdf/2004.02984.pdf) | 'mobilebert_qa' | 4.3x smaller and 5.5x faster than BERT-Base while achieving competitive results, suitable for on-device scenario.[MobileBERT-SQuAD](https://arxiv.org/pdf/2004.02984.pdf) | 'mobilebert_qa_squad' | Same model architecture as MobileBERT model and the initial model is already retrained on [SQuAD1.1](https://rajpurkar.github.io/SQuAD-explorer/).[BERT-Base](https://arxiv.org/pdf/1810.04805.pdf) | 'bert_qa' | Standard BERT model that widely used in NLP tasks.In this tutorial, [MobileBERT-SQuAD](https://arxiv.org/pdf/2004.02984.pdf) is used as an example. Since the model is already retrained on [SQuAD1.1](https://rajpurkar.github.io/SQuAD-explorer/), it could coverage faster for question answer task.
###Code
spec = model_spec.get('mobilebert_qa_squad')
###Output
_____no_output_____
###Markdown
Load Input Data Specific to an On-device ML App and Preprocess the DataThe [TriviaQA](https://nlp.cs.washington.edu/triviaqa/) is a reading comprehension dataset containing over 650K question-answer-evidence triples. In this tutorial, you will use a subset of this dataset to learn how to use the Model Maker library.To load the data, convert the TriviaQA dataset to the [SQuAD1.1](https://rajpurkar.github.io/SQuAD-explorer/) format by running the [converter Python script](https://github.com/mandarjoshi90/triviaqamiscellaneous) with `--sample_size=8000` and a set of `web` data. Modify the conversion code a little bit by:* Skipping the samples that couldn't find any answer in the context document;* Getting the original answer in the context without uppercase or lowercase.Download the archived version of the already converted dataset.
###Code
train_data_path = tf.keras.utils.get_file(
fname='triviaqa-web-train-8000.json',
origin='https://storage.googleapis.com/download.tensorflow.org/models/tflite/dataset/triviaqa-web-train-8000.json')
validation_data_path = tf.keras.utils.get_file(
fname='triviaqa-verified-web-dev.json',
origin='https://storage.googleapis.com/download.tensorflow.org/models/tflite/dataset/triviaqa-verified-web-dev.json')
###Output
Downloading data from https://storage.googleapis.com/download.tensorflow.org/models/tflite/dataset/triviaqa-web-train-8000.json
32571392/32570663 [==============================] - 1s 0us/step
Downloading data from https://storage.googleapis.com/download.tensorflow.org/models/tflite/dataset/triviaqa-verified-web-dev.json
1171456/1167744 [==============================] - 0s 0us/step
###Markdown
You can also train the MobileBERT model with your own dataset. If you are running this notebook on Colab, upload your data by using the left sidebar.If you prefer not to upload your data to the cloud, you can also run the library offline by following the [guide](https://github.com/tensorflow/examples/tree/master/tensorflow_examples/lite/model_maker). Use the `QuestionAnswerDataLoader.from_squad` method to load and preprocess the [SQuAD format](https://rajpurkar.github.io/SQuAD-explorer/) data according to a specific `model_spec`. You can use either SQuAD2.0 or SQuAD1.1 formats. Setting parameter `version_2_with_negative` as `True` means the formats is SQuAD2.0. Otherwise, the format is SQuAD1.1. By default, `version_2_with_negative` is `False`.
###Code
train_data = QuestionAnswerDataLoader.from_squad(train_data_path, spec, is_training=True)
validation_data = QuestionAnswerDataLoader.from_squad(validation_data_path, spec, is_training=False)
###Output
_____no_output_____
###Markdown
Customize the TensorFlow ModelCreate a custom question answer model based on the loaded data. The `create` function comprises the following steps:1. Creates the model for question answer according to `model_spec`.2. Train the question answer model. The default epochs and the default batch size are set according to two variables `default_training_epochs` and `default_batch_size` in the `model_spec` object.
###Code
model = question_answer.create(train_data, model_spec=spec)
###Output
INFO:tensorflow:Retraining the models...
###Markdown
Have a look at the detailed model structure.
###Code
model.summary()
###Output
_____no_output_____
###Markdown
Evaluate the Customized ModelEvaluate the model on the validation data and get a dict of metrics including `f1` score and `exact match` etc. Note that metrics are different for SQuAD1.1 and SQuAD2.0.
###Code
model.evaluate(validation_data)
###Output
_____no_output_____
###Markdown
Export to TensorFlow Lite ModelConvert the existing model to TensorFlow Lite model format that you can later use in an on-device ML application. Since MobileBERT is too big for on-device applications, use dynamic range quantization on the model to compress MobileBERT by 4x with the minimal loss of performance. First, define the quantization configuration:
###Code
config = configs.QuantizationConfig.create_dynamic_range_quantization(optimizations=[tf.lite.Optimize.OPTIMIZE_FOR_LATENCY])
config._experimental_new_quantizer = True
###Output
_____no_output_____
###Markdown
Export the quantized TFLite model according to the quantization config with [metadata](https://www.tensorflow.org/lite/convert/metadata). The default TFLite model filename is `model.tflite`.
###Code
model.export(export_dir='.', quantization_config=config)
###Output
_____no_output_____
###Markdown
You can use the TensorFlow Lite model file in the [bert_qa](https://github.com/tensorflow/examples/tree/master/lite/examples/bert_qa/android) reference app using [BertQuestionAnswerer API](https://www.tensorflow.org/lite/inference_with_metadata/task_library/bert_question_answerer) in [TensorFlow Lite Task Library](https://www.tensorflow.org/lite/inference_with_metadata/task_library/overview) by downloading it from the left sidebar on Colab. The allowed export formats can be one or a list of the following:* `ExportFormat.TFLITE`* `ExportFormat.VOCAB`* `ExportFormat.SAVED_MODEL`By default, it just exports TensorFlow Lite model with metadata. You can also selectively export different files. For instance, exporting only the vocab file as follows:
###Code
model.export(export_dir='.', export_format=ExportFormat.VOCAB)
###Output
_____no_output_____
###Markdown
You can also evaluate the tflite model with the `evaluate_tflite` method. This step is expected to take a long time.
###Code
model.evaluate_tflite('model.tflite', validation_data)
###Output
_____no_output_____
###Markdown
Advanced UsageThe `create` function is the critical part of this library in which the `model_spec` parameter defines the model specification. The `BertQAModelSpec` class is currently supported. There are 2 models: MobileBERT model, BERT-Base model. The `create` function comprises the following steps:1. Creates the model for question answer according to `model_spec`.2. Train the question answer model.This section describes several advanced topics, including adjusting the model, tuning the training hyperparameters etc. Adjust the modelYou can adjust the model infrastructure like parameters `seq_len` and `query_len` in the `BertQAModelSpec` class.Adjustable parameters for model:* `seq_len`: Length of the passage to feed into the model.* `query_len`: Length of the question to feed into the model.* `doc_stride`: The stride when doing a sliding window approach to take chunks of the documents.* `initializer_range`: The stdev of the truncated_normal_initializer for initializing all weight matrices.* `trainable`: Boolean, whether pre-trained layer is trainable.Adjustable parameters for training pipeline:* `model_dir`: The location of the model checkpoint files. If not set, temporary directory will be used.* `dropout_rate`: The rate for dropout.* `learning_rate`: The initial learning rate for Adam.* `predict_batch_size`: Batch size for prediction.* `tpu`: TPU address to connect to. Only used if using tpu. For example, you can train the model with a longer sequence length. If you change the model, you must first construct a new `model_spec`.
###Code
new_spec = model_spec.get('mobilebert_qa')
new_spec.seq_len = 512
###Output
_____no_output_____
###Markdown
Copyright 2020 The TensorFlow Authors.
###Code
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###Output
_____no_output_____
###Markdown
BERT Question Answer with TensorFlow Lite Model Maker View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook The [TensorFlow Lite Model Maker library](https://www.tensorflow.org/lite/guide/model_maker) simplifies the process of adapting and converting a TensorFlow model to particular input data when deploying this model for on-device ML applications.This notebook shows an end-to-end example that utilizes the Model Maker library to illustrate the adaptation and conversion of a commonly-used question answer model for question answer task. Introduction to BERT Question Answer Task The supported task in this library is extractive question answer task, which means given a passage and a question, the answer is the span in the passage. The image below shows an example for question answer. Answers are spans in the passage (image credit: SQuAD blog) As for the model of question answer task, the inputs should be the passage and question pair that are already preprocessed, the outputs should be the start logits and end logits for each token in the passage.The size of input could be set and adjusted according to the length of passage and question. End-to-End Overview The following code snippet demonstrates how to get the model within a few lines of code. The overall process includes 5 steps: (1) choose a model, (2) load data, (3) retrain the model, (4) evaluate, and (5) export it to TensorFlow Lite format. ```python Chooses a model specification that represents the model.spec = model_spec.get('mobilebert_qa') Gets the training data and validation data.train_data = DataLoader.from_squad(train_data_path, spec, is_training=True)validation_data = DataLoader.from_squad(validation_data_path, spec, is_training=False) Fine-tunes the model.model = question_answer.create(train_data, model_spec=spec) Gets the evaluation result.metric = model.evaluate(validation_data) Exports the model to the TensorFlow Lite format with metadata in the export directory.model.export(export_dir)``` The following sections explain the code in more detail. PrerequisitesTo run this example, install the required packages, including the Model Maker package from the [GitHub repo](https://github.com/tensorflow/examples/tree/master/tensorflow_examples/lite/model_maker).
###Code
!pip install -q tflite-model-maker
###Output
_____no_output_____
###Markdown
Import the required packages.
###Code
import numpy as np
import os
import tensorflow as tf
assert tf.__version__.startswith('2')
from tflite_model_maker import model_spec
from tflite_model_maker import question_answer
from tflite_model_maker.config import ExportFormat
from tflite_model_maker.config import QuantizationConfig
from tflite_model_maker.question_answer import DataLoader
###Output
_____no_output_____
###Markdown
The "End-to-End Overview" demonstrates a simple end-to-end example. The following sections walk through the example step by step to show more detail. Choose a model_spec that represents a model for question answerEach `model_spec` object represents a specific model for question answer. The Model Maker currently supports MobileBERT and BERT-Base models.Supported Model | Name of model_spec | Model Description--- | --- | ---[MobileBERT](https://arxiv.org/pdf/2004.02984.pdf) | 'mobilebert_qa' | 4.3x smaller and 5.5x faster than BERT-Base while achieving competitive results, suitable for on-device scenario.[MobileBERT-SQuAD](https://arxiv.org/pdf/2004.02984.pdf) | 'mobilebert_qa_squad' | Same model architecture as MobileBERT model and the initial model is already retrained on [SQuAD1.1](https://rajpurkar.github.io/SQuAD-explorer/).[BERT-Base](https://arxiv.org/pdf/1810.04805.pdf) | 'bert_qa' | Standard BERT model that widely used in NLP tasks.In this tutorial, [MobileBERT-SQuAD](https://arxiv.org/pdf/2004.02984.pdf) is used as an example. Since the model is already retrained on [SQuAD1.1](https://rajpurkar.github.io/SQuAD-explorer/), it could coverage faster for question answer task.
###Code
spec = model_spec.get('mobilebert_qa_squad')
###Output
_____no_output_____
###Markdown
Load Input Data Specific to an On-device ML App and Preprocess the DataThe [TriviaQA](https://nlp.cs.washington.edu/triviaqa/) is a reading comprehension dataset containing over 650K question-answer-evidence triples. In this tutorial, you will use a subset of this dataset to learn how to use the Model Maker library.To load the data, convert the TriviaQA dataset to the [SQuAD1.1](https://rajpurkar.github.io/SQuAD-explorer/) format by running the [converter Python script](https://github.com/mandarjoshi90/triviaqamiscellaneous) with `--sample_size=8000` and a set of `web` data. Modify the conversion code a little bit by:* Skipping the samples that couldn't find any answer in the context document;* Getting the original answer in the context without uppercase or lowercase.Download the archived version of the already converted dataset.
###Code
train_data_path = tf.keras.utils.get_file(
fname='triviaqa-web-train-8000.json',
origin='https://storage.googleapis.com/download.tensorflow.org/models/tflite/dataset/triviaqa-web-train-8000.json')
validation_data_path = tf.keras.utils.get_file(
fname='triviaqa-verified-web-dev.json',
origin='https://storage.googleapis.com/download.tensorflow.org/models/tflite/dataset/triviaqa-verified-web-dev.json')
###Output
_____no_output_____
###Markdown
You can also train the MobileBERT model with your own dataset. If you are running this notebook on Colab, upload your data by using the left sidebar.If you prefer not to upload your data to the cloud, you can also run the library offline by following the [guide](https://github.com/tensorflow/examples/tree/master/tensorflow_examples/lite/model_maker). Use the `DataLoader.from_squad` method to load and preprocess the [SQuAD format](https://rajpurkar.github.io/SQuAD-explorer/) data according to a specific `model_spec`. You can use either SQuAD2.0 or SQuAD1.1 formats. Setting parameter `version_2_with_negative` as `True` means the formats is SQuAD2.0. Otherwise, the format is SQuAD1.1. By default, `version_2_with_negative` is `False`.
###Code
train_data = DataLoader.from_squad(train_data_path, spec, is_training=True)
validation_data = DataLoader.from_squad(validation_data_path, spec, is_training=False)
###Output
_____no_output_____
###Markdown
Customize the TensorFlow ModelCreate a custom question answer model based on the loaded data. The `create` function comprises the following steps:1. Creates the model for question answer according to `model_spec`.2. Train the question answer model. The default epochs and the default batch size are set according to two variables `default_training_epochs` and `default_batch_size` in the `model_spec` object.
###Code
model = question_answer.create(train_data, model_spec=spec)
###Output
_____no_output_____
###Markdown
Have a look at the detailed model structure.
###Code
model.summary()
###Output
_____no_output_____
###Markdown
Evaluate the Customized ModelEvaluate the model on the validation data and get a dict of metrics including `f1` score and `exact match` etc. Note that metrics are different for SQuAD1.1 and SQuAD2.0.
###Code
model.evaluate(validation_data)
###Output
_____no_output_____
###Markdown
Export to TensorFlow Lite ModelConvert the existing model to TensorFlow Lite model format that you can later use in an on-device ML application. Since MobileBERT is too big for on-device applications, use dynamic range quantization on the model to compress MobileBERT by 4x with the minimal loss of performance. First, define the quantization configuration:
###Code
config = QuantizationConfig.for_dynamic()
config.experimental_new_quantizer = True
###Output
_____no_output_____
###Markdown
Export the quantized TFLite model according to the quantization config with [metadata](https://www.tensorflow.org/lite/convert/metadata). The default TFLite model filename is `model.tflite`.
###Code
model.export(export_dir='.', quantization_config=config)
###Output
_____no_output_____
###Markdown
You can use the TensorFlow Lite model file in the [bert_qa](https://github.com/tensorflow/examples/tree/master/lite/examples/bert_qa/android) reference app using [BertQuestionAnswerer API](https://www.tensorflow.org/lite/inference_with_metadata/task_library/bert_question_answerer) in [TensorFlow Lite Task Library](https://www.tensorflow.org/lite/inference_with_metadata/task_library/overview) by downloading it from the left sidebar on Colab. The allowed export formats can be one or a list of the following:* `ExportFormat.TFLITE`* `ExportFormat.VOCAB`* `ExportFormat.SAVED_MODEL`By default, it just exports TensorFlow Lite model with metadata. You can also selectively export different files. For instance, exporting only the vocab file as follows:
###Code
model.export(export_dir='.', export_format=ExportFormat.VOCAB)
###Output
_____no_output_____
###Markdown
You can also evaluate the tflite model with the `evaluate_tflite` method. This step is expected to take a long time.
###Code
model.evaluate_tflite('model.tflite', validation_data)
###Output
_____no_output_____
###Markdown
Advanced UsageThe `create` function is the critical part of this library in which the `model_spec` parameter defines the model specification. The `BertQASpec` class is currently supported. There are 2 models: MobileBERT model, BERT-Base model. The `create` function comprises the following steps:1. Creates the model for question answer according to `model_spec`.2. Train the question answer model.This section describes several advanced topics, including adjusting the model, tuning the training hyperparameters etc. Adjust the modelYou can adjust the model infrastructure like parameters `seq_len` and `query_len` in the `BertQASpec` class.Adjustable parameters for model:* `seq_len`: Length of the passage to feed into the model.* `query_len`: Length of the question to feed into the model.* `doc_stride`: The stride when doing a sliding window approach to take chunks of the documents.* `initializer_range`: The stdev of the truncated_normal_initializer for initializing all weight matrices.* `trainable`: Boolean, whether pre-trained layer is trainable.Adjustable parameters for training pipeline:* `model_dir`: The location of the model checkpoint files. If not set, temporary directory will be used.* `dropout_rate`: The rate for dropout.* `learning_rate`: The initial learning rate for Adam.* `predict_batch_size`: Batch size for prediction.* `tpu`: TPU address to connect to. Only used if using tpu. For example, you can train the model with a longer sequence length. If you change the model, you must first construct a new `model_spec`.
###Code
new_spec = model_spec.get('mobilebert_qa')
new_spec.seq_len = 512
###Output
_____no_output_____
###Markdown
Copyright 2020 The TensorFlow Authors.
###Code
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###Output
_____no_output_____
###Markdown
Question Answer with TensorFlow Lite Model Maker View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook The TensorFlow Lite Model Maker library simplifies the process of adapting and converting a TensorFlow model to particular input data when deploying this model for on-device ML applications.This notebook shows an end-to-end example that utilizes the Model Maker library to illustrate the adaptation and conversion of a commonly-used question answer model for question answer task. Introduction to Question Answer Task The supported task in this library is extractive question answer task, which means given a passage and a question, the answer is the span in the passage. The image below shows an example for question answer. Answers are spans in the passage (image credit: SQuAD blog) As for the model of question answer task, the inputs should be the passage and question pair that are already preprocessed, the outputs should be the start logits and end logits for each token in the passage.The size of input could be set and adjusted according to the length of passage and question. End-to-End Overview The following code snippet demonstrates how to get the model within a few lines of code. The overall process includes 5 steps: (1) choose a model, (2) load data, (3) retrain the model, (4) evaluate, and (5) export it to TensorFlow Lite format. ```python Chooses a model specification that represents the model.spec = model_spec.get('mobilebert_qa') Gets the training data and validation data.train_data = QuestionAnswerDataLoader.from_squad(train_data_path, spec, is_training=True)validation_data = QuestionAnswerDataLoader.from_squad(validation_data_path, spec, is_training=False) Fine-tunes the model.model = question_answer.create(train_data, model_spec=spec) Gets the evaluation result.metric = model.evaluate(validation_data) Exports the model to the TensorFlow Lite format in the export directory.model.export(export_dir)``` The following sections explain the code in more detail. PrerequisitesTo run this example, install the required packages, including the Model Maker package from the [GitHub repo](https://github.com/tensorflow/examples/tree/master/tensorflow_examples/lite/model_maker).
###Code
!pip install tflite-model-maker
###Output
_____no_output_____
###Markdown
Import the required packages.
###Code
import numpy as np
import os
import tensorflow as tf
assert tf.__version__.startswith('2')
from tflite_model_maker import configs
from tflite_model_maker import model_spec
from tflite_model_maker import question_answer
from tflite_model_maker import QuestionAnswerDataLoader
###Output
_____no_output_____
###Markdown
The "End-to-End Overview" demonstrates a simple end-to-end example. The following sections walk through the example step by step to show more detail. Choose a model_spec that represents a model for question answerEach `model_spec` object represents a specific model for question answer. The Model Maker currently supports MobileBERT and BERT-Base models.Supported Model | Name of model_spec | Model Description--- | --- | ---[MobileBERT](https://arxiv.org/pdf/2004.02984.pdf) | 'mobilebert_qa' | 4.3x smaller and 5.5x faster than BERT-Base while achieving competitive results, suitable for on-device scenario.[MobileBERT-SQuAD](https://arxiv.org/pdf/2004.02984.pdf) | 'mobilebert_qa_squad' | Same model architecture as MobileBERT model and the initial model is already retrained on [SQuAD1.1](https://rajpurkar.github.io/SQuAD-explorer/).[BERT-Base](https://arxiv.org/pdf/1810.04805.pdf) | 'bert_qa' | Standard BERT model that widely used in NLP tasks.In this tutorial, [MobileBERT-SQuAD](https://arxiv.org/pdf/2004.02984.pdf) is used as an example. Since the model is already retrained on [SQuAD1.1](https://rajpurkar.github.io/SQuAD-explorer/), it could coverage faster for question answer task.
###Code
spec = model_spec.get('mobilebert_qa_squad')
###Output
_____no_output_____
###Markdown
Load Input Data Specific to an On-device ML App and Preprocess the DataThe [TriviaQA](https://nlp.cs.washington.edu/triviaqa/) is a reading comprehension dataset containing over 650K question-answer-evidence triples. In this tutorial, you will use a subset of this dataset to learn how to use the Model Maker library.To load the data, convert the TriviaQA dataset to the [SQuAD1.1](https://rajpurkar.github.io/SQuAD-explorer/) format by running the [converter Python script](https://github.com/mandarjoshi90/triviaqamiscellaneous) with `--sample_size=8000` and a set of `web` data. Modify the conversion code a little bit by:* Skipping the samples that couldn't find any answer in the context document;* Getting the original answer in the context without uppercase or lowercase.Download the archived version of the already converted dataset.
###Code
train_data_path = tf.keras.utils.get_file(
fname='triviaqa-web-train-8000.json',
origin='https://storage.googleapis.com/download.tensorflow.org/models/tflite/dataset/triviaqa-web-train-8000.json')
validation_data_path = tf.keras.utils.get_file(
fname='triviaqa-verified-web-dev.json',
origin='https://storage.googleapis.com/download.tensorflow.org/models/tflite/dataset/triviaqa-verified-web-dev.json')
###Output
_____no_output_____
###Markdown
You can also train the MobileBERT model with your own dataset. If you are running this notebook on Colab, upload your data by using the left sidebar.If you prefer not to upload your data to the cloud, you can also run the library offline by following the [guide](https://github.com/tensorflow/examples/tree/master/tensorflow_examples/lite/model_maker). Use the `QuestionAnswerDataLoader.from_squad` method to load and preprocess the [SQuAD format](https://rajpurkar.github.io/SQuAD-explorer/) data according to a specific `model_spec`. You can use either SQuAD2.0 or SQuAD1.1 formats. Setting parameter `version_2_with_negative` as `True` means the formats is SQuAD2.0. Otherwise, the format is SQuAD1.1. By default, `version_2_with_negative` is `False`.
###Code
train_data = QuestionAnswerDataLoader.from_squad(train_data_path, spec, is_training=True)
validation_data = QuestionAnswerDataLoader.from_squad(validation_data_path, spec, is_training=False)
###Output
_____no_output_____
###Markdown
Customize the TensorFlow ModelCreate a custom question answer model based on the loaded data. The `create` function comprises the following steps:1. Creates the model for question answer according to `model_spec`.2. Train the question answer model. The default epochs and the default batch size are set according to two variables `default_training_epochs` and `default_batch_size` in the `model_spec` object.
###Code
model = question_answer.create(train_data, model_spec=spec)
###Output
_____no_output_____
###Markdown
Have a look at the detailed model structure.
###Code
model.summary()
###Output
_____no_output_____
###Markdown
Evaluate the Customized ModelEvaluate the model on the validation data and get a dict of metrics including `f1` score and `exact match` etc. Note that metrics are different for SQuAD1.1 and SQuAD2.0.
###Code
model.evaluate(validation_data)
###Output
_____no_output_____
###Markdown
Export to TensorFlow Lite ModelConvert the existing model to TensorFlow Lite model format that you can later use in an on-device ML application. Since MobileBERT is too big for on-device applications, use dynamic range quantization on the model to compress MobileBERT by 4x with the minimal loss of performance. First, define the quantization configuration:
###Code
config = configs.QuantizationConfig.create_dynamic_range_quantization(optimizations=[tf.lite.Optimize.OPTIMIZE_FOR_LATENCY])
config._experimental_new_quantizer = True
###Output
_____no_output_____
###Markdown
Export the quantized TFLite model according to the quantization config and save the vocabulary to a vocab file. The default TFLite model filename is `model.tflite`, and the default vocab filename is `vocab`.
###Code
model.export(export_dir='.', quantization_config=config)
###Output
_____no_output_____
###Markdown
You can use the TensorFlow Lite model file and vocab file in the [bert_qa](https://github.com/tensorflow/examples/tree/master/lite/examples/bert_qa/android) reference app by downloading it from the left sidebar on Colab. You can also evalute the tflite model with the `evaluate_tflite` method. This step is expected to take a long time.
###Code
model.evaluate_tflite('model.tflite', validation_data)
###Output
_____no_output_____
###Markdown
Advanced UsageThe `create` function is the critical part of this library in which the `model_spec` parameter defines the model specification. The `BertQAModelSpec` class is currently supported. There are 2 models: MobileBERT model, BERT-Base model. The `create` function comprises the following steps:1. Creates the model for question answer according to `model_spec`.2. Train the question answer model.This section describes several advanced topics, including adjusting the model, tuning the training hyperparameters etc. Adjust the modelYou can adjust the model infrastructure like parameters `seq_len` and `query_len` in the `BertQAModelSpec` class.Adjustable parameters for model:* `seq_len`: Length of the passage to feed into the model.* `query_len`: Length of the question to feed into the model.* `doc_stride`: The stride when doing a sliding window approach to take chunks of the documents.* `initializer_range`: The stdev of the truncated_normal_initializer for initializing all weight matrices.* `trainable`: Boolean, whether pre-trained layer is trainable.Adjustable parameters for training pipeline:* `model_dir`: The location of the model checkpoint files. If not set, temporary directory will be used.* `dropout_rate`: The rate for dropout.* `learning_rate`: The initial learning rate for Adam.* `predict_batch_size`: Batch size for prediction.* `tpu`: TPU address to connect to. Only used if using tpu. For example, you can train the model with a longer sequence length. If you change the model, you must first construct a new `model_spec`.
###Code
new_spec = model_spec.get('mobilebert_qa')
new_spec.seq_len = 512
###Output
_____no_output_____
###Markdown
Copyright 2020 The TensorFlow Authors.
###Code
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###Output
_____no_output_____
###Markdown
Question Answer with TensorFlow Lite Model Maker View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook The TensorFlow Lite Model Maker library simplifies the process of adapting and converting a TensorFlow model to particular input data when deploying this model for on-device ML applications.This notebook shows an end-to-end example that utilizes the Model Maker library to illustrate the adaptation and conversion of a commonly-used question answer model for question answer task. Introduction to Question Answer Task The supported task in this library is extractive question answer task, which means given a passage and a question, the answer is the span in the passage. The image below shows an example for question answer. Answers are spans in the passage (image credit: SQuAD blog) As for the model of question answer task, the inputs should be the passage and question pair that are already preprocessed, the outputs should be the start logits and end logits for each token in the passage.The size of input could be set and adjusted according to the length of passage and question. End-to-End Overview The following code snippet demonstrates how to get the model within a few lines of code. The overall process includes 5 steps: (1) choose a model, (2) load data, (3) retrain the model, (4) evaluate, and (5) export it to TensorFlow Lite format. ```python Chooses a model specification that represents the model.spec = model_spec.get('mobilebert_qa') Gets the training data and validation data.train_data = QuestionAnswerDataLoader.from_squad(train_data_path, spec, is_training=True)validation_data = QuestionAnswerDataLoader.from_squad(validation_data_path, spec, is_training=False) Fine-tunes the model.model = question_answer.create(train_data, model_spec=spec) Gets the evaluation result.metric = model.evaluate(validation_data) Exports the model to the TensorFlow Lite format with metadata in the export directory.model.export(export_dir)``` The following sections explain the code in more detail. PrerequisitesTo run this example, install the required packages, including the Model Maker package from the [GitHub repo](https://github.com/tensorflow/examples/tree/master/tensorflow_examples/lite/model_maker).
###Code
!pip install tflite-model-maker
###Output
Collecting tflite-model-maker
[?25l Downloading https://files.pythonhosted.org/packages/13/bc/4c23b9cb9ef612a1f48bac5543bd531665de5eab8f8231111aac067f8c30/tflite_model_maker-0.1.2-py3-none-any.whl (104kB)
[K |███▏ | 10kB 28.4MB/s eta 0:00:01
[K |██████▎ | 20kB 1.8MB/s eta 0:00:01
[K |█████████▍ | 30kB 2.4MB/s eta 0:00:01
[K |████████████▋ | 40kB 2.7MB/s eta 0:00:01
[K |███████████████▊ | 51kB 2.1MB/s eta 0:00:01
[K |██████████████████▉ | 61kB 2.4MB/s eta 0:00:01
[K |██████████████████████ | 71kB 2.7MB/s eta 0:00:01
[K |█████████████████████████▏ | 81kB 2.9MB/s eta 0:00:01
[K |████████████████████████████▎ | 92kB 3.1MB/s eta 0:00:01
[K |███████████████████████████████▌| 102kB 3.0MB/s eta 0:00:01
[K |████████████████████████████████| 112kB 3.0MB/s
[?25hRequirement already satisfied: absl-py in /usr/local/lib/python3.6/dist-packages (from tflite-model-maker) (0.10.0)
Collecting tf-nightly
[?25l Downloading https://files.pythonhosted.org/packages/33/d4/61c47ae889b490b9c5f07f4f61bdc057c158a1a1979c375fa019d647a19e/tf_nightly-2.4.0.dev20200914-cp36-cp36m-manylinux2010_x86_64.whl (390.1MB)
[K |████████████████████████████████| 390.2MB 43kB/s
[?25hRequirement already satisfied: numpy>=1.17.3 in /usr/local/lib/python3.6/dist-packages (from tflite-model-maker) (1.18.5)
Requirement already satisfied: pillow in /usr/local/lib/python3.6/dist-packages (from tflite-model-maker) (7.0.0)
Collecting tf-models-nightly
[?25l Downloading https://files.pythonhosted.org/packages/d3/e9/c4e5a451c268a5a75a27949562364f6086f6bb33b226a065a8beceefa9ba/tf_models_nightly-2.3.0.dev20200914-py2.py3-none-any.whl (993kB)
[K |████████████████████████████████| 1.0MB 57.6MB/s
[?25hCollecting flatbuffers==1.12
Downloading https://files.pythonhosted.org/packages/eb/26/712e578c5f14e26ae3314c39a1bdc4eb2ec2f4ddc89b708cf8e0a0d20423/flatbuffers-1.12-py2.py3-none-any.whl
Requirement already satisfied: tensorflow-hub>=0.8.0 in /usr/local/lib/python3.6/dist-packages (from tflite-model-maker) (0.9.0)
Collecting fire
[?25l Downloading https://files.pythonhosted.org/packages/34/a7/0e22e70778aca01a52b9c899d9c145c6396d7b613719cd63db97ffa13f2f/fire-0.3.1.tar.gz (81kB)
[K |████████████████████████████████| 81kB 11.5MB/s
[?25hCollecting sentencepiece
[?25l Downloading https://files.pythonhosted.org/packages/d4/a4/d0a884c4300004a78cca907a6ff9a5e9fe4f090f5d95ab341c53d28cbc58/sentencepiece-0.1.91-cp36-cp36m-manylinux1_x86_64.whl (1.1MB)
[K |████████████████████████████████| 1.1MB 50.9MB/s
[?25hCollecting tflite-support==0.1.0rc3.dev2
[?25l Downloading https://files.pythonhosted.org/packages/fa/c5/5e9ee3abd5b4ef8294432cd714407f49a66befa864905b66ee8bdc612795/tflite_support-0.1.0rc3.dev2-cp36-cp36m-manylinux2010_x86_64.whl (1.0MB)
[K |████████████████████████████████| 1.0MB 50.9MB/s
[?25hRequirement already satisfied: tensorflow-datasets>=2.1.0 in /usr/local/lib/python3.6/dist-packages (from tflite-model-maker) (2.1.0)
Requirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from absl-py->tflite-model-maker) (1.15.0)
Requirement already satisfied: termcolor>=1.1.0 in /usr/local/lib/python3.6/dist-packages (from tf-nightly->tflite-model-maker) (1.1.0)
Requirement already satisfied: opt-einsum>=2.3.2 in /usr/local/lib/python3.6/dist-packages (from tf-nightly->tflite-model-maker) (3.3.0)
Collecting tb-nightly<3.0.0a0,>=2.4.0a0
[?25l Downloading https://files.pythonhosted.org/packages/fc/cb/4dfe0d65bffb5e9663261ff664e6f5a2d37672b31dae27a0f14721ac00d3/tb_nightly-2.4.0a20200914-py3-none-any.whl (10.1MB)
[K |████████████████████████████████| 10.1MB 51.4MB/s
[?25hRequirement already satisfied: typing-extensions>=3.7.4.2 in /usr/local/lib/python3.6/dist-packages (from tf-nightly->tflite-model-maker) (3.7.4.3)
Requirement already satisfied: wheel>=0.26 in /usr/local/lib/python3.6/dist-packages (from tf-nightly->tflite-model-maker) (0.35.1)
Collecting tf-estimator-nightly
[?25l Downloading https://files.pythonhosted.org/packages/bd/9a/3bfb9994eda11e426c809ebdf434e2ac5824a0784d980018bb53fd1620ec/tf_estimator_nightly-2.4.0.dev2020091401-py2.py3-none-any.whl (460kB)
[K |████████████████████████████████| 460kB 36.0MB/s
[?25hRequirement already satisfied: google-pasta>=0.1.8 in /usr/local/lib/python3.6/dist-packages (from tf-nightly->tflite-model-maker) (0.2.0)
Requirement already satisfied: h5py<2.11.0,>=2.10.0 in /usr/local/lib/python3.6/dist-packages (from tf-nightly->tflite-model-maker) (2.10.0)
Requirement already satisfied: keras-preprocessing<1.2,>=1.1.1 in /usr/local/lib/python3.6/dist-packages (from tf-nightly->tflite-model-maker) (1.1.2)
Requirement already satisfied: wrapt>=1.11.1 in /usr/local/lib/python3.6/dist-packages (from tf-nightly->tflite-model-maker) (1.12.1)
Requirement already satisfied: grpcio>=1.8.6 in /usr/local/lib/python3.6/dist-packages (from tf-nightly->tflite-model-maker) (1.32.0)
Requirement already satisfied: protobuf>=3.9.2 in /usr/local/lib/python3.6/dist-packages (from tf-nightly->tflite-model-maker) (3.12.4)
Requirement already satisfied: gast==0.3.3 in /usr/local/lib/python3.6/dist-packages (from tf-nightly->tflite-model-maker) (0.3.3)
Requirement already satisfied: astunparse==1.6.3 in /usr/local/lib/python3.6/dist-packages (from tf-nightly->tflite-model-maker) (1.6.3)
Requirement already satisfied: scipy>=0.19.1 in /usr/local/lib/python3.6/dist-packages (from tf-models-nightly->tflite-model-maker) (1.4.1)
Collecting pyyaml>=5.1
[?25l Downloading https://files.pythonhosted.org/packages/64/c2/b80047c7ac2478f9501676c988a5411ed5572f35d1beff9cae07d321512c/PyYAML-5.3.1.tar.gz (269kB)
[K |████████████████████████████████| 276kB 59.8MB/s
[?25hCollecting tensorflow-model-optimization>=0.4.1
[?25l Downloading https://files.pythonhosted.org/packages/55/38/4fd48ea1bfcb0b6e36d949025200426fe9c3a8bfae029f0973d85518fa5a/tensorflow_model_optimization-0.5.0-py2.py3-none-any.whl (172kB)
[K |████████████████████████████████| 174kB 51.0MB/s
[?25hRequirement already satisfied: pandas>=0.22.0 in /usr/local/lib/python3.6/dist-packages (from tf-models-nightly->tflite-model-maker) (1.0.5)
Requirement already satisfied: dataclasses in /usr/local/lib/python3.6/dist-packages (from tf-models-nightly->tflite-model-maker) (0.7)
Requirement already satisfied: Cython in /usr/local/lib/python3.6/dist-packages (from tf-models-nightly->tflite-model-maker) (0.29.21)
Collecting opencv-python-headless
[?25l Downloading https://files.pythonhosted.org/packages/b6/2a/496e06fd289c01dc21b11970be1261c87ce1cc22d5340c14b516160822a7/opencv_python_headless-4.4.0.42-cp36-cp36m-manylinux2014_x86_64.whl (36.6MB)
[K |████████████████████████████████| 36.6MB 83kB/s
[?25hRequirement already satisfied: kaggle>=1.3.9 in /usr/local/lib/python3.6/dist-packages (from tf-models-nightly->tflite-model-maker) (1.5.8)
Requirement already satisfied: pycocotools in /usr/local/lib/python3.6/dist-packages (from tf-models-nightly->tflite-model-maker) (2.0.2)
Requirement already satisfied: oauth2client in /usr/local/lib/python3.6/dist-packages (from tf-models-nightly->tflite-model-maker) (4.1.3)
Requirement already satisfied: matplotlib in /usr/local/lib/python3.6/dist-packages (from tf-models-nightly->tflite-model-maker) (3.2.2)
Collecting tf-slim>=1.1.0
[?25l Downloading https://files.pythonhosted.org/packages/02/97/b0f4a64df018ca018cc035d44f2ef08f91e2e8aa67271f6f19633a015ff7/tf_slim-1.1.0-py2.py3-none-any.whl (352kB)
[K |████████████████████████████████| 358kB 55.9MB/s
[?25hCollecting seqeval
Downloading https://files.pythonhosted.org/packages/34/91/068aca8d60ce56dd9ba4506850e876aba5e66a6f2f29aa223224b50df0de/seqeval-0.0.12.tar.gz
Requirement already satisfied: psutil>=5.4.3 in /usr/local/lib/python3.6/dist-packages (from tf-models-nightly->tflite-model-maker) (5.4.8)
Collecting py-cpuinfo>=3.3.0
[?25l Downloading https://files.pythonhosted.org/packages/f6/f5/8e6e85ce2e9f6e05040cf0d4e26f43a4718bcc4bce988b433276d4b1a5c1/py-cpuinfo-7.0.0.tar.gz (95kB)
[K |████████████████████████████████| 102kB 13.5MB/s
[?25hRequirement already satisfied: google-api-python-client>=1.6.7 in /usr/local/lib/python3.6/dist-packages (from tf-models-nightly->tflite-model-maker) (1.7.12)
Requirement already satisfied: gin-config in /usr/local/lib/python3.6/dist-packages (from tf-models-nightly->tflite-model-maker) (0.3.0)
Requirement already satisfied: tensorflow-addons in /usr/local/lib/python3.6/dist-packages (from tf-models-nightly->tflite-model-maker) (0.8.3)
Requirement already satisfied: google-cloud-bigquery>=0.31.0 in /usr/local/lib/python3.6/dist-packages (from tf-models-nightly->tflite-model-maker) (1.21.0)
Collecting pybind11>=2.4
[?25l Downloading https://files.pythonhosted.org/packages/89/e3/d576f6f02bc75bacbc3d42494e8f1d063c95617d86648dba243c2cb3963e/pybind11-2.5.0-py2.py3-none-any.whl (296kB)
[K |████████████████████████████████| 296kB 47.9MB/s
[?25hRequirement already satisfied: promise in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets>=2.1.0->tflite-model-maker) (2.3)
Requirement already satisfied: tensorflow-metadata in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets>=2.1.0->tflite-model-maker) (0.24.0)
Requirement already satisfied: requests>=2.19.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets>=2.1.0->tflite-model-maker) (2.23.0)
Requirement already satisfied: dill in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets>=2.1.0->tflite-model-maker) (0.3.2)
Requirement already satisfied: attrs>=18.1.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets>=2.1.0->tflite-model-maker) (20.2.0)
Requirement already satisfied: tqdm in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets>=2.1.0->tflite-model-maker) (4.41.1)
Requirement already satisfied: future in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets>=2.1.0->tflite-model-maker) (0.16.0)
Requirement already satisfied: werkzeug>=0.11.15 in /usr/local/lib/python3.6/dist-packages (from tb-nightly<3.0.0a0,>=2.4.0a0->tf-nightly->tflite-model-maker) (1.0.1)
Requirement already satisfied: setuptools>=41.0.0 in /usr/local/lib/python3.6/dist-packages (from tb-nightly<3.0.0a0,>=2.4.0a0->tf-nightly->tflite-model-maker) (50.3.0)
Requirement already satisfied: tensorboard-plugin-wit>=1.6.0 in /usr/local/lib/python3.6/dist-packages (from tb-nightly<3.0.0a0,>=2.4.0a0->tf-nightly->tflite-model-maker) (1.7.0)
Requirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /usr/local/lib/python3.6/dist-packages (from tb-nightly<3.0.0a0,>=2.4.0a0->tf-nightly->tflite-model-maker) (0.4.1)
Requirement already satisfied: google-auth<2,>=1.6.3 in /usr/local/lib/python3.6/dist-packages (from tb-nightly<3.0.0a0,>=2.4.0a0->tf-nightly->tflite-model-maker) (1.17.2)
Requirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.6/dist-packages (from tb-nightly<3.0.0a0,>=2.4.0a0->tf-nightly->tflite-model-maker) (3.2.2)
Requirement already satisfied: dm-tree~=0.1.1 in /usr/local/lib/python3.6/dist-packages (from tensorflow-model-optimization>=0.4.1->tf-models-nightly->tflite-model-maker) (0.1.5)
Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.6/dist-packages (from pandas>=0.22.0->tf-models-nightly->tflite-model-maker) (2018.9)
Requirement already satisfied: python-dateutil>=2.6.1 in /usr/local/lib/python3.6/dist-packages (from pandas>=0.22.0->tf-models-nightly->tflite-model-maker) (2.8.1)
Requirement already satisfied: certifi in /usr/local/lib/python3.6/dist-packages (from kaggle>=1.3.9->tf-models-nightly->tflite-model-maker) (2020.6.20)
Requirement already satisfied: python-slugify in /usr/local/lib/python3.6/dist-packages (from kaggle>=1.3.9->tf-models-nightly->tflite-model-maker) (4.0.1)
Requirement already satisfied: slugify in /usr/local/lib/python3.6/dist-packages (from kaggle>=1.3.9->tf-models-nightly->tflite-model-maker) (0.0.1)
Requirement already satisfied: urllib3<1.25,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from kaggle>=1.3.9->tf-models-nightly->tflite-model-maker) (1.24.3)
Requirement already satisfied: pyasn1>=0.1.7 in /usr/local/lib/python3.6/dist-packages (from oauth2client->tf-models-nightly->tflite-model-maker) (0.4.8)
Requirement already satisfied: rsa>=3.1.4 in /usr/local/lib/python3.6/dist-packages (from oauth2client->tf-models-nightly->tflite-model-maker) (4.6)
Requirement already satisfied: httplib2>=0.9.1 in /usr/local/lib/python3.6/dist-packages (from oauth2client->tf-models-nightly->tflite-model-maker) (0.17.4)
Requirement already satisfied: pyasn1-modules>=0.0.5 in /usr/local/lib/python3.6/dist-packages (from oauth2client->tf-models-nightly->tflite-model-maker) (0.2.8)
Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib->tf-models-nightly->tflite-model-maker) (1.2.0)
Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib->tf-models-nightly->tflite-model-maker) (2.4.7)
Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.6/dist-packages (from matplotlib->tf-models-nightly->tflite-model-maker) (0.10.0)
Requirement already satisfied: Keras>=2.2.4 in /usr/local/lib/python3.6/dist-packages (from seqeval->tf-models-nightly->tflite-model-maker) (2.4.3)
Requirement already satisfied: google-auth-httplib2>=0.0.3 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client>=1.6.7->tf-models-nightly->tflite-model-maker) (0.0.4)
Requirement already satisfied: uritemplate<4dev,>=3.0.0 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client>=1.6.7->tf-models-nightly->tflite-model-maker) (3.0.1)
Requirement already satisfied: typeguard in /usr/local/lib/python3.6/dist-packages (from tensorflow-addons->tf-models-nightly->tflite-model-maker) (2.7.1)
Requirement already satisfied: google-cloud-core<2.0dev,>=1.0.3 in /usr/local/lib/python3.6/dist-packages (from google-cloud-bigquery>=0.31.0->tf-models-nightly->tflite-model-maker) (1.0.3)
Requirement already satisfied: google-resumable-media!=0.4.0,<0.5.0dev,>=0.3.1 in /usr/local/lib/python3.6/dist-packages (from google-cloud-bigquery>=0.31.0->tf-models-nightly->tflite-model-maker) (0.4.1)
Requirement already satisfied: googleapis-common-protos<2,>=1.52.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow-metadata->tensorflow-datasets>=2.1.0->tflite-model-maker) (1.52.0)
Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests>=2.19.0->tensorflow-datasets>=2.1.0->tflite-model-maker) (3.0.4)
Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests>=2.19.0->tensorflow-datasets>=2.1.0->tflite-model-maker) (2.10)
Requirement already satisfied: requests-oauthlib>=0.7.0 in /usr/local/lib/python3.6/dist-packages (from google-auth-oauthlib<0.5,>=0.4.1->tb-nightly<3.0.0a0,>=2.4.0a0->tf-nightly->tflite-model-maker) (1.3.0)
Requirement already satisfied: cachetools<5.0,>=2.0.0 in /usr/local/lib/python3.6/dist-packages (from google-auth<2,>=1.6.3->tb-nightly<3.0.0a0,>=2.4.0a0->tf-nightly->tflite-model-maker) (4.1.1)
Requirement already satisfied: importlib-metadata; python_version < "3.8" in /usr/local/lib/python3.6/dist-packages (from markdown>=2.6.8->tb-nightly<3.0.0a0,>=2.4.0a0->tf-nightly->tflite-model-maker) (1.7.0)
Requirement already satisfied: text-unidecode>=1.3 in /usr/local/lib/python3.6/dist-packages (from python-slugify->kaggle>=1.3.9->tf-models-nightly->tflite-model-maker) (1.3)
Requirement already satisfied: google-api-core<2.0.0dev,>=1.14.0 in /usr/local/lib/python3.6/dist-packages (from google-cloud-core<2.0dev,>=1.0.3->google-cloud-bigquery>=0.31.0->tf-models-nightly->tflite-model-maker) (1.16.0)
Requirement already satisfied: oauthlib>=3.0.0 in /usr/local/lib/python3.6/dist-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tb-nightly<3.0.0a0,>=2.4.0a0->tf-nightly->tflite-model-maker) (3.1.0)
Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.6/dist-packages (from importlib-metadata; python_version < "3.8"->markdown>=2.6.8->tb-nightly<3.0.0a0,>=2.4.0a0->tf-nightly->tflite-model-maker) (3.1.0)
Building wheels for collected packages: fire, pyyaml, seqeval, py-cpuinfo
Building wheel for fire (setup.py) ... [?25l[?25hdone
Created wheel for fire: filename=fire-0.3.1-py2.py3-none-any.whl size=111005 sha256=f0b82e6b31e21d6db3591478a37188c727533acefe415b16b456c85ef9bef47c
Stored in directory: /root/.cache/pip/wheels/c1/61/df/768b03527bf006b546dce284eb4249b185669e65afc5fbb2ac
Building wheel for pyyaml (setup.py) ... [?25l[?25hdone
Created wheel for pyyaml: filename=PyYAML-5.3.1-cp36-cp36m-linux_x86_64.whl size=44619 sha256=cdbc63ead8369d7403f47b1adff163ebde2636c9f0c2a5ebd6413d156b2b7a9f
Stored in directory: /root/.cache/pip/wheels/a7/c1/ea/cf5bd31012e735dc1dfea3131a2d5eae7978b251083d6247bd
Building wheel for seqeval (setup.py) ... [?25l[?25hdone
Created wheel for seqeval: filename=seqeval-0.0.12-cp36-none-any.whl size=7423 sha256=3ac4a1cc3b88a9b1a1ed8217f2b8d3abb7f936e853383025888b94019d98a856
Stored in directory: /root/.cache/pip/wheels/4f/32/0a/df3b340a82583566975377d65e724895b3fad101a3fb729f68
Building wheel for py-cpuinfo (setup.py) ... [?25l[?25hdone
Created wheel for py-cpuinfo: filename=py_cpuinfo-7.0.0-cp36-none-any.whl size=20071 sha256=b5491e6fcabbf9ae464c0def53ec6ec27bbf01230ff96f4e34c6a7c44d55d5c9
Stored in directory: /root/.cache/pip/wheels/f1/93/7b/127daf0c3a5a49feb2fecd468d508067c733fba5192f726ad1
Successfully built fire pyyaml seqeval py-cpuinfo
Installing collected packages: tb-nightly, flatbuffers, tf-estimator-nightly, tf-nightly, pyyaml, tensorflow-model-optimization, opencv-python-headless, sentencepiece, tf-slim, seqeval, py-cpuinfo, tf-models-nightly, fire, pybind11, tflite-support, tflite-model-maker
Found existing installation: PyYAML 3.13
Uninstalling PyYAML-3.13:
Successfully uninstalled PyYAML-3.13
Successfully installed fire-0.3.1 flatbuffers-1.12 opencv-python-headless-4.4.0.42 py-cpuinfo-7.0.0 pybind11-2.5.0 pyyaml-5.3.1 sentencepiece-0.1.91 seqeval-0.0.12 tb-nightly-2.4.0a20200914 tensorflow-model-optimization-0.5.0 tf-estimator-nightly-2.4.0.dev2020091401 tf-models-nightly-2.3.0.dev20200914 tf-nightly-2.4.0.dev20200914 tf-slim-1.1.0 tflite-model-maker-0.1.2 tflite-support-0.1.0rc3.dev2
###Markdown
Import the required packages.
###Code
import numpy as np
import os
import tensorflow as tf
assert tf.__version__.startswith('2')
from tflite_model_maker import configs
from tflite_model_maker import ExportFormat
from tflite_model_maker import model_spec
from tflite_model_maker import question_answer
from tflite_model_maker import QuestionAnswerDataLoader
###Output
_____no_output_____
###Markdown
The "End-to-End Overview" demonstrates a simple end-to-end example. The following sections walk through the example step by step to show more detail. Choose a model_spec that represents a model for question answerEach `model_spec` object represents a specific model for question answer. The Model Maker currently supports MobileBERT and BERT-Base models.Supported Model | Name of model_spec | Model Description--- | --- | ---[MobileBERT](https://arxiv.org/pdf/2004.02984.pdf) | 'mobilebert_qa' | 4.3x smaller and 5.5x faster than BERT-Base while achieving competitive results, suitable for on-device scenario.[MobileBERT-SQuAD](https://arxiv.org/pdf/2004.02984.pdf) | 'mobilebert_qa_squad' | Same model architecture as MobileBERT model and the initial model is already retrained on [SQuAD1.1](https://rajpurkar.github.io/SQuAD-explorer/).[BERT-Base](https://arxiv.org/pdf/1810.04805.pdf) | 'bert_qa' | Standard BERT model that widely used in NLP tasks.In this tutorial, [MobileBERT-SQuAD](https://arxiv.org/pdf/2004.02984.pdf) is used as an example. Since the model is already retrained on [SQuAD1.1](https://rajpurkar.github.io/SQuAD-explorer/), it could coverage faster for question answer task.
###Code
spec = model_spec.get('mobilebert_qa_squad')
###Output
_____no_output_____
###Markdown
Load Input Data Specific to an On-device ML App and Preprocess the DataThe [TriviaQA](https://nlp.cs.washington.edu/triviaqa/) is a reading comprehension dataset containing over 650K question-answer-evidence triples. In this tutorial, you will use a subset of this dataset to learn how to use the Model Maker library.To load the data, convert the TriviaQA dataset to the [SQuAD1.1](https://rajpurkar.github.io/SQuAD-explorer/) format by running the [converter Python script](https://github.com/mandarjoshi90/triviaqamiscellaneous) with `--sample_size=8000` and a set of `web` data. Modify the conversion code a little bit by:* Skipping the samples that couldn't find any answer in the context document;* Getting the original answer in the context without uppercase or lowercase.Download the archived version of the already converted dataset.
###Code
train_data_path = tf.keras.utils.get_file(
fname='triviaqa-web-train-8000.json',
origin='https://storage.googleapis.com/download.tensorflow.org/models/tflite/dataset/triviaqa-web-train-8000.json')
validation_data_path = tf.keras.utils.get_file(
fname='triviaqa-verified-web-dev.json',
origin='https://storage.googleapis.com/download.tensorflow.org/models/tflite/dataset/triviaqa-verified-web-dev.json')
###Output
Downloading data from https://storage.googleapis.com/download.tensorflow.org/models/tflite/dataset/triviaqa-web-train-8000.json
32571392/32570663 [==============================] - 1s 0us/step
Downloading data from https://storage.googleapis.com/download.tensorflow.org/models/tflite/dataset/triviaqa-verified-web-dev.json
1171456/1167744 [==============================] - 0s 0us/step
###Markdown
You can also train the MobileBERT model with your own dataset. If you are running this notebook on Colab, upload your data by using the left sidebar.If you prefer not to upload your data to the cloud, you can also run the library offline by following the [guide](https://github.com/tensorflow/examples/tree/master/tensorflow_examples/lite/model_maker). Use the `QuestionAnswerDataLoader.from_squad` method to load and preprocess the [SQuAD format](https://rajpurkar.github.io/SQuAD-explorer/) data according to a specific `model_spec`. You can use either SQuAD2.0 or SQuAD1.1 formats. Setting parameter `version_2_with_negative` as `True` means the formats is SQuAD2.0. Otherwise, the format is SQuAD1.1. By default, `version_2_with_negative` is `False`.
###Code
train_data = QuestionAnswerDataLoader.from_squad(train_data_path, spec, is_training=True)
validation_data = QuestionAnswerDataLoader.from_squad(validation_data_path, spec, is_training=False)
###Output
_____no_output_____
###Markdown
Customize the TensorFlow ModelCreate a custom question answer model based on the loaded data. The `create` function comprises the following steps:1. Creates the model for question answer according to `model_spec`.2. Train the question answer model. The default epochs and the default batch size are set according to two variables `default_training_epochs` and `default_batch_size` in the `model_spec` object.
###Code
model = question_answer.create(train_data, model_spec=spec)
###Output
INFO:tensorflow:Retraining the models...
###Markdown
Have a look at the detailed model structure.
###Code
model.summary()
###Output
_____no_output_____
###Markdown
Evaluate the Customized ModelEvaluate the model on the validation data and get a dict of metrics including `f1` score and `exact match` etc. Note that metrics are different for SQuAD1.1 and SQuAD2.0.
###Code
model.evaluate(validation_data)
###Output
_____no_output_____
###Markdown
Export to TensorFlow Lite ModelConvert the existing model to TensorFlow Lite model format that you can later use in an on-device ML application. Since MobileBERT is too big for on-device applications, use dynamic range quantization on the model to compress MobileBERT by 4x with the minimal loss of performance. First, define the quantization configuration:
###Code
config = configs.QuantizationConfig.create_dynamic_range_quantization(optimizations=[tf.lite.Optimize.OPTIMIZE_FOR_LATENCY])
config._experimental_new_quantizer = True
###Output
_____no_output_____
###Markdown
Export the quantized TFLite model according to the quantization config with [metadata](https://www.tensorflow.org/lite/convert/metadata). The default TFLite model filename is `model.tflite`.
###Code
model.export(export_dir='.', quantization_config=config)
###Output
_____no_output_____
###Markdown
You can use the TensorFlow Lite model file in the [bert_qa](https://github.com/tensorflow/examples/tree/master/lite/examples/bert_qa/android) reference app using [BertQuestionAnswerer API](https://www.tensorflow.org/lite/inference_with_metadata/task_library/bert_question_answerer) in [TensorFlow Lite Task Library](https://www.tensorflow.org/lite/inference_with_metadata/task_library/overview) by downloading it from the left sidebar on Colab. The allowed export formats can be one or a list of the following:* `ExportFormat.TFLITE`* `ExportFormat.VOCAB`* `ExportFormat.SAVED_MODEL`By default, it just exports TensorFlow Lite model with metadata. You can also selectively export different files. For instance, exporting only the vocab file as follows:
###Code
model.export(export_dir='.', export_format=ExportFormat.VOCAB)
###Output
_____no_output_____
###Markdown
You can also evalute the tflite model with the `evaluate_tflite` method. This step is expected to take a long time.
###Code
model.evaluate_tflite('model.tflite', validation_data)
###Output
_____no_output_____
###Markdown
Advanced UsageThe `create` function is the critical part of this library in which the `model_spec` parameter defines the model specification. The `BertQAModelSpec` class is currently supported. There are 2 models: MobileBERT model, BERT-Base model. The `create` function comprises the following steps:1. Creates the model for question answer according to `model_spec`.2. Train the question answer model.This section describes several advanced topics, including adjusting the model, tuning the training hyperparameters etc. Adjust the modelYou can adjust the model infrastructure like parameters `seq_len` and `query_len` in the `BertQAModelSpec` class.Adjustable parameters for model:* `seq_len`: Length of the passage to feed into the model.* `query_len`: Length of the question to feed into the model.* `doc_stride`: The stride when doing a sliding window approach to take chunks of the documents.* `initializer_range`: The stdev of the truncated_normal_initializer for initializing all weight matrices.* `trainable`: Boolean, whether pre-trained layer is trainable.Adjustable parameters for training pipeline:* `model_dir`: The location of the model checkpoint files. If not set, temporary directory will be used.* `dropout_rate`: The rate for dropout.* `learning_rate`: The initial learning rate for Adam.* `predict_batch_size`: Batch size for prediction.* `tpu`: TPU address to connect to. Only used if using tpu. For example, you can train the model with a longer sequence length. If you change the model, you must first construct a new `model_spec`.
###Code
new_spec = model_spec.get('mobilebert_qa')
new_spec.seq_len = 512
###Output
_____no_output_____
###Markdown
Copyright 2020 The TensorFlow Authors.
###Code
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###Output
_____no_output_____
###Markdown
Question Answer with TensorFlow Lite Model Maker View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook The TensorFlow Lite Model Maker library simplifies the process of adapting and converting a TensorFlow model to particular input data when deploying this model for on-device ML applications.This notebook shows an end-to-end example that utilizes the Model Maker library to illustrate the adaptation and conversion of a commonly-used question answer model for question answer task. Introduction to Question Answer Task The supported task in this library is extractive question answer task, which means given a passage and a question, the answer is the span in the passage. The image below shows an example for question answer. Answers are spans in the passage (image credit: SQuAD blog) As for the model of question answer task, the inputs should be the passage and question pair that are already preprocessed, the outputs should be the start logits and end logits for each token in the passage.The size of input could be set and adjusted according to the length of passage and question. End-to-End Overview The following code snippet demonstrates how to get the model within a few lines of code. The overall process includes 5 steps: (1) choose a model, (2) load data, (3) retrain the model, (4) evaluate, and (5) export it to TensorFlow Lite format. ```python Chooses a model specification that represents the model.spec = model_spec.get('mobilebert_qa') Gets the training data and validation data.train_data = QuestionAnswerDataLoader.from_squad(train_data_path, spec, is_training=True)validation_data = QuestionAnswerDataLoader.from_squad(validation_data_path, spec, is_training=False) Fine-tunes the model.model = question_answer.create(train_data, model_spec=spec) Gets the evaluation result.metric = model.evaluate(validation_data) Exports the model to the TensorFlow Lite format in the export directory.model.export(export_dir)``` The following sections explain the code in more detail. PrerequisitesTo run this example, install the required packages, including the Model Maker package from the [GitHub repo](https://github.com/tensorflow/examples/tree/master/tensorflow_examples/lite/model_maker).
###Code
!pip install tflite-model-maker
###Output
Collecting tflite-model-maker
[?25l Downloading https://files.pythonhosted.org/packages/13/bc/4c23b9cb9ef612a1f48bac5543bd531665de5eab8f8231111aac067f8c30/tflite_model_maker-0.1.2-py3-none-any.whl (104kB)
[K |███▏ | 10kB 28.4MB/s eta 0:00:01
[K |██████▎ | 20kB 1.8MB/s eta 0:00:01
[K |█████████▍ | 30kB 2.4MB/s eta 0:00:01
[K |████████████▋ | 40kB 2.7MB/s eta 0:00:01
[K |███████████████▊ | 51kB 2.1MB/s eta 0:00:01
[K |██████████████████▉ | 61kB 2.4MB/s eta 0:00:01
[K |██████████████████████ | 71kB 2.7MB/s eta 0:00:01
[K |█████████████████████████▏ | 81kB 2.9MB/s eta 0:00:01
[K |████████████████████████████▎ | 92kB 3.1MB/s eta 0:00:01
[K |███████████████████████████████▌| 102kB 3.0MB/s eta 0:00:01
[K |████████████████████████████████| 112kB 3.0MB/s
[?25hRequirement already satisfied: absl-py in /usr/local/lib/python3.6/dist-packages (from tflite-model-maker) (0.10.0)
Collecting tf-nightly
[?25l Downloading https://files.pythonhosted.org/packages/33/d4/61c47ae889b490b9c5f07f4f61bdc057c158a1a1979c375fa019d647a19e/tf_nightly-2.4.0.dev20200914-cp36-cp36m-manylinux2010_x86_64.whl (390.1MB)
[K |████████████████████████████████| 390.2MB 43kB/s
[?25hRequirement already satisfied: numpy>=1.17.3 in /usr/local/lib/python3.6/dist-packages (from tflite-model-maker) (1.18.5)
Requirement already satisfied: pillow in /usr/local/lib/python3.6/dist-packages (from tflite-model-maker) (7.0.0)
Collecting tf-models-nightly
[?25l Downloading https://files.pythonhosted.org/packages/d3/e9/c4e5a451c268a5a75a27949562364f6086f6bb33b226a065a8beceefa9ba/tf_models_nightly-2.3.0.dev20200914-py2.py3-none-any.whl (993kB)
[K |████████████████████████████████| 1.0MB 57.6MB/s
[?25hCollecting flatbuffers==1.12
Downloading https://files.pythonhosted.org/packages/eb/26/712e578c5f14e26ae3314c39a1bdc4eb2ec2f4ddc89b708cf8e0a0d20423/flatbuffers-1.12-py2.py3-none-any.whl
Requirement already satisfied: tensorflow-hub>=0.8.0 in /usr/local/lib/python3.6/dist-packages (from tflite-model-maker) (0.9.0)
Collecting fire
[?25l Downloading https://files.pythonhosted.org/packages/34/a7/0e22e70778aca01a52b9c899d9c145c6396d7b613719cd63db97ffa13f2f/fire-0.3.1.tar.gz (81kB)
[K |████████████████████████████████| 81kB 11.5MB/s
[?25hCollecting sentencepiece
[?25l Downloading https://files.pythonhosted.org/packages/d4/a4/d0a884c4300004a78cca907a6ff9a5e9fe4f090f5d95ab341c53d28cbc58/sentencepiece-0.1.91-cp36-cp36m-manylinux1_x86_64.whl (1.1MB)
[K |████████████████████████████████| 1.1MB 50.9MB/s
[?25hCollecting tflite-support==0.1.0rc3.dev2
[?25l Downloading https://files.pythonhosted.org/packages/fa/c5/5e9ee3abd5b4ef8294432cd714407f49a66befa864905b66ee8bdc612795/tflite_support-0.1.0rc3.dev2-cp36-cp36m-manylinux2010_x86_64.whl (1.0MB)
[K |████████████████████████████████| 1.0MB 50.9MB/s
[?25hRequirement already satisfied: tensorflow-datasets>=2.1.0 in /usr/local/lib/python3.6/dist-packages (from tflite-model-maker) (2.1.0)
Requirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from absl-py->tflite-model-maker) (1.15.0)
Requirement already satisfied: termcolor>=1.1.0 in /usr/local/lib/python3.6/dist-packages (from tf-nightly->tflite-model-maker) (1.1.0)
Requirement already satisfied: opt-einsum>=2.3.2 in /usr/local/lib/python3.6/dist-packages (from tf-nightly->tflite-model-maker) (3.3.0)
Collecting tb-nightly<3.0.0a0,>=2.4.0a0
[?25l Downloading https://files.pythonhosted.org/packages/fc/cb/4dfe0d65bffb5e9663261ff664e6f5a2d37672b31dae27a0f14721ac00d3/tb_nightly-2.4.0a20200914-py3-none-any.whl (10.1MB)
[K |████████████████████████████████| 10.1MB 51.4MB/s
[?25hRequirement already satisfied: typing-extensions>=3.7.4.2 in /usr/local/lib/python3.6/dist-packages (from tf-nightly->tflite-model-maker) (3.7.4.3)
Requirement already satisfied: wheel>=0.26 in /usr/local/lib/python3.6/dist-packages (from tf-nightly->tflite-model-maker) (0.35.1)
Collecting tf-estimator-nightly
[?25l Downloading https://files.pythonhosted.org/packages/bd/9a/3bfb9994eda11e426c809ebdf434e2ac5824a0784d980018bb53fd1620ec/tf_estimator_nightly-2.4.0.dev2020091401-py2.py3-none-any.whl (460kB)
[K |████████████████████████████████| 460kB 36.0MB/s
[?25hRequirement already satisfied: google-pasta>=0.1.8 in /usr/local/lib/python3.6/dist-packages (from tf-nightly->tflite-model-maker) (0.2.0)
Requirement already satisfied: h5py<2.11.0,>=2.10.0 in /usr/local/lib/python3.6/dist-packages (from tf-nightly->tflite-model-maker) (2.10.0)
Requirement already satisfied: keras-preprocessing<1.2,>=1.1.1 in /usr/local/lib/python3.6/dist-packages (from tf-nightly->tflite-model-maker) (1.1.2)
Requirement already satisfied: wrapt>=1.11.1 in /usr/local/lib/python3.6/dist-packages (from tf-nightly->tflite-model-maker) (1.12.1)
Requirement already satisfied: grpcio>=1.8.6 in /usr/local/lib/python3.6/dist-packages (from tf-nightly->tflite-model-maker) (1.32.0)
Requirement already satisfied: protobuf>=3.9.2 in /usr/local/lib/python3.6/dist-packages (from tf-nightly->tflite-model-maker) (3.12.4)
Requirement already satisfied: gast==0.3.3 in /usr/local/lib/python3.6/dist-packages (from tf-nightly->tflite-model-maker) (0.3.3)
Requirement already satisfied: astunparse==1.6.3 in /usr/local/lib/python3.6/dist-packages (from tf-nightly->tflite-model-maker) (1.6.3)
Requirement already satisfied: scipy>=0.19.1 in /usr/local/lib/python3.6/dist-packages (from tf-models-nightly->tflite-model-maker) (1.4.1)
Collecting pyyaml>=5.1
[?25l Downloading https://files.pythonhosted.org/packages/64/c2/b80047c7ac2478f9501676c988a5411ed5572f35d1beff9cae07d321512c/PyYAML-5.3.1.tar.gz (269kB)
[K |████████████████████████████████| 276kB 59.8MB/s
[?25hCollecting tensorflow-model-optimization>=0.4.1
[?25l Downloading https://files.pythonhosted.org/packages/55/38/4fd48ea1bfcb0b6e36d949025200426fe9c3a8bfae029f0973d85518fa5a/tensorflow_model_optimization-0.5.0-py2.py3-none-any.whl (172kB)
[K |████████████████████████████████| 174kB 51.0MB/s
[?25hRequirement already satisfied: pandas>=0.22.0 in /usr/local/lib/python3.6/dist-packages (from tf-models-nightly->tflite-model-maker) (1.0.5)
Requirement already satisfied: dataclasses in /usr/local/lib/python3.6/dist-packages (from tf-models-nightly->tflite-model-maker) (0.7)
Requirement already satisfied: Cython in /usr/local/lib/python3.6/dist-packages (from tf-models-nightly->tflite-model-maker) (0.29.21)
Collecting opencv-python-headless
[?25l Downloading https://files.pythonhosted.org/packages/b6/2a/496e06fd289c01dc21b11970be1261c87ce1cc22d5340c14b516160822a7/opencv_python_headless-4.4.0.42-cp36-cp36m-manylinux2014_x86_64.whl (36.6MB)
[K |████████████████████████████████| 36.6MB 83kB/s
[?25hRequirement already satisfied: kaggle>=1.3.9 in /usr/local/lib/python3.6/dist-packages (from tf-models-nightly->tflite-model-maker) (1.5.8)
Requirement already satisfied: pycocotools in /usr/local/lib/python3.6/dist-packages (from tf-models-nightly->tflite-model-maker) (2.0.2)
Requirement already satisfied: oauth2client in /usr/local/lib/python3.6/dist-packages (from tf-models-nightly->tflite-model-maker) (4.1.3)
Requirement already satisfied: matplotlib in /usr/local/lib/python3.6/dist-packages (from tf-models-nightly->tflite-model-maker) (3.2.2)
Collecting tf-slim>=1.1.0
[?25l Downloading https://files.pythonhosted.org/packages/02/97/b0f4a64df018ca018cc035d44f2ef08f91e2e8aa67271f6f19633a015ff7/tf_slim-1.1.0-py2.py3-none-any.whl (352kB)
[K |████████████████████████████████| 358kB 55.9MB/s
[?25hCollecting seqeval
Downloading https://files.pythonhosted.org/packages/34/91/068aca8d60ce56dd9ba4506850e876aba5e66a6f2f29aa223224b50df0de/seqeval-0.0.12.tar.gz
Requirement already satisfied: psutil>=5.4.3 in /usr/local/lib/python3.6/dist-packages (from tf-models-nightly->tflite-model-maker) (5.4.8)
Collecting py-cpuinfo>=3.3.0
[?25l Downloading https://files.pythonhosted.org/packages/f6/f5/8e6e85ce2e9f6e05040cf0d4e26f43a4718bcc4bce988b433276d4b1a5c1/py-cpuinfo-7.0.0.tar.gz (95kB)
[K |████████████████████████████████| 102kB 13.5MB/s
[?25hRequirement already satisfied: google-api-python-client>=1.6.7 in /usr/local/lib/python3.6/dist-packages (from tf-models-nightly->tflite-model-maker) (1.7.12)
Requirement already satisfied: gin-config in /usr/local/lib/python3.6/dist-packages (from tf-models-nightly->tflite-model-maker) (0.3.0)
Requirement already satisfied: tensorflow-addons in /usr/local/lib/python3.6/dist-packages (from tf-models-nightly->tflite-model-maker) (0.8.3)
Requirement already satisfied: google-cloud-bigquery>=0.31.0 in /usr/local/lib/python3.6/dist-packages (from tf-models-nightly->tflite-model-maker) (1.21.0)
Collecting pybind11>=2.4
[?25l Downloading https://files.pythonhosted.org/packages/89/e3/d576f6f02bc75bacbc3d42494e8f1d063c95617d86648dba243c2cb3963e/pybind11-2.5.0-py2.py3-none-any.whl (296kB)
[K |████████████████████████████████| 296kB 47.9MB/s
[?25hRequirement already satisfied: promise in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets>=2.1.0->tflite-model-maker) (2.3)
Requirement already satisfied: tensorflow-metadata in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets>=2.1.0->tflite-model-maker) (0.24.0)
Requirement already satisfied: requests>=2.19.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets>=2.1.0->tflite-model-maker) (2.23.0)
Requirement already satisfied: dill in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets>=2.1.0->tflite-model-maker) (0.3.2)
Requirement already satisfied: attrs>=18.1.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets>=2.1.0->tflite-model-maker) (20.2.0)
Requirement already satisfied: tqdm in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets>=2.1.0->tflite-model-maker) (4.41.1)
Requirement already satisfied: future in /usr/local/lib/python3.6/dist-packages (from tensorflow-datasets>=2.1.0->tflite-model-maker) (0.16.0)
Requirement already satisfied: werkzeug>=0.11.15 in /usr/local/lib/python3.6/dist-packages (from tb-nightly<3.0.0a0,>=2.4.0a0->tf-nightly->tflite-model-maker) (1.0.1)
Requirement already satisfied: setuptools>=41.0.0 in /usr/local/lib/python3.6/dist-packages (from tb-nightly<3.0.0a0,>=2.4.0a0->tf-nightly->tflite-model-maker) (50.3.0)
Requirement already satisfied: tensorboard-plugin-wit>=1.6.0 in /usr/local/lib/python3.6/dist-packages (from tb-nightly<3.0.0a0,>=2.4.0a0->tf-nightly->tflite-model-maker) (1.7.0)
Requirement already satisfied: google-auth-oauthlib<0.5,>=0.4.1 in /usr/local/lib/python3.6/dist-packages (from tb-nightly<3.0.0a0,>=2.4.0a0->tf-nightly->tflite-model-maker) (0.4.1)
Requirement already satisfied: google-auth<2,>=1.6.3 in /usr/local/lib/python3.6/dist-packages (from tb-nightly<3.0.0a0,>=2.4.0a0->tf-nightly->tflite-model-maker) (1.17.2)
Requirement already satisfied: markdown>=2.6.8 in /usr/local/lib/python3.6/dist-packages (from tb-nightly<3.0.0a0,>=2.4.0a0->tf-nightly->tflite-model-maker) (3.2.2)
Requirement already satisfied: dm-tree~=0.1.1 in /usr/local/lib/python3.6/dist-packages (from tensorflow-model-optimization>=0.4.1->tf-models-nightly->tflite-model-maker) (0.1.5)
Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.6/dist-packages (from pandas>=0.22.0->tf-models-nightly->tflite-model-maker) (2018.9)
Requirement already satisfied: python-dateutil>=2.6.1 in /usr/local/lib/python3.6/dist-packages (from pandas>=0.22.0->tf-models-nightly->tflite-model-maker) (2.8.1)
Requirement already satisfied: certifi in /usr/local/lib/python3.6/dist-packages (from kaggle>=1.3.9->tf-models-nightly->tflite-model-maker) (2020.6.20)
Requirement already satisfied: python-slugify in /usr/local/lib/python3.6/dist-packages (from kaggle>=1.3.9->tf-models-nightly->tflite-model-maker) (4.0.1)
Requirement already satisfied: slugify in /usr/local/lib/python3.6/dist-packages (from kaggle>=1.3.9->tf-models-nightly->tflite-model-maker) (0.0.1)
Requirement already satisfied: urllib3<1.25,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from kaggle>=1.3.9->tf-models-nightly->tflite-model-maker) (1.24.3)
Requirement already satisfied: pyasn1>=0.1.7 in /usr/local/lib/python3.6/dist-packages (from oauth2client->tf-models-nightly->tflite-model-maker) (0.4.8)
Requirement already satisfied: rsa>=3.1.4 in /usr/local/lib/python3.6/dist-packages (from oauth2client->tf-models-nightly->tflite-model-maker) (4.6)
Requirement already satisfied: httplib2>=0.9.1 in /usr/local/lib/python3.6/dist-packages (from oauth2client->tf-models-nightly->tflite-model-maker) (0.17.4)
Requirement already satisfied: pyasn1-modules>=0.0.5 in /usr/local/lib/python3.6/dist-packages (from oauth2client->tf-models-nightly->tflite-model-maker) (0.2.8)
Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib->tf-models-nightly->tflite-model-maker) (1.2.0)
Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib->tf-models-nightly->tflite-model-maker) (2.4.7)
Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.6/dist-packages (from matplotlib->tf-models-nightly->tflite-model-maker) (0.10.0)
Requirement already satisfied: Keras>=2.2.4 in /usr/local/lib/python3.6/dist-packages (from seqeval->tf-models-nightly->tflite-model-maker) (2.4.3)
Requirement already satisfied: google-auth-httplib2>=0.0.3 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client>=1.6.7->tf-models-nightly->tflite-model-maker) (0.0.4)
Requirement already satisfied: uritemplate<4dev,>=3.0.0 in /usr/local/lib/python3.6/dist-packages (from google-api-python-client>=1.6.7->tf-models-nightly->tflite-model-maker) (3.0.1)
Requirement already satisfied: typeguard in /usr/local/lib/python3.6/dist-packages (from tensorflow-addons->tf-models-nightly->tflite-model-maker) (2.7.1)
Requirement already satisfied: google-cloud-core<2.0dev,>=1.0.3 in /usr/local/lib/python3.6/dist-packages (from google-cloud-bigquery>=0.31.0->tf-models-nightly->tflite-model-maker) (1.0.3)
Requirement already satisfied: google-resumable-media!=0.4.0,<0.5.0dev,>=0.3.1 in /usr/local/lib/python3.6/dist-packages (from google-cloud-bigquery>=0.31.0->tf-models-nightly->tflite-model-maker) (0.4.1)
Requirement already satisfied: googleapis-common-protos<2,>=1.52.0 in /usr/local/lib/python3.6/dist-packages (from tensorflow-metadata->tensorflow-datasets>=2.1.0->tflite-model-maker) (1.52.0)
Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests>=2.19.0->tensorflow-datasets>=2.1.0->tflite-model-maker) (3.0.4)
Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests>=2.19.0->tensorflow-datasets>=2.1.0->tflite-model-maker) (2.10)
Requirement already satisfied: requests-oauthlib>=0.7.0 in /usr/local/lib/python3.6/dist-packages (from google-auth-oauthlib<0.5,>=0.4.1->tb-nightly<3.0.0a0,>=2.4.0a0->tf-nightly->tflite-model-maker) (1.3.0)
Requirement already satisfied: cachetools<5.0,>=2.0.0 in /usr/local/lib/python3.6/dist-packages (from google-auth<2,>=1.6.3->tb-nightly<3.0.0a0,>=2.4.0a0->tf-nightly->tflite-model-maker) (4.1.1)
Requirement already satisfied: importlib-metadata; python_version < "3.8" in /usr/local/lib/python3.6/dist-packages (from markdown>=2.6.8->tb-nightly<3.0.0a0,>=2.4.0a0->tf-nightly->tflite-model-maker) (1.7.0)
Requirement already satisfied: text-unidecode>=1.3 in /usr/local/lib/python3.6/dist-packages (from python-slugify->kaggle>=1.3.9->tf-models-nightly->tflite-model-maker) (1.3)
Requirement already satisfied: google-api-core<2.0.0dev,>=1.14.0 in /usr/local/lib/python3.6/dist-packages (from google-cloud-core<2.0dev,>=1.0.3->google-cloud-bigquery>=0.31.0->tf-models-nightly->tflite-model-maker) (1.16.0)
Requirement already satisfied: oauthlib>=3.0.0 in /usr/local/lib/python3.6/dist-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tb-nightly<3.0.0a0,>=2.4.0a0->tf-nightly->tflite-model-maker) (3.1.0)
Requirement already satisfied: zipp>=0.5 in /usr/local/lib/python3.6/dist-packages (from importlib-metadata; python_version < "3.8"->markdown>=2.6.8->tb-nightly<3.0.0a0,>=2.4.0a0->tf-nightly->tflite-model-maker) (3.1.0)
Building wheels for collected packages: fire, pyyaml, seqeval, py-cpuinfo
Building wheel for fire (setup.py) ... [?25l[?25hdone
Created wheel for fire: filename=fire-0.3.1-py2.py3-none-any.whl size=111005 sha256=f0b82e6b31e21d6db3591478a37188c727533acefe415b16b456c85ef9bef47c
Stored in directory: /root/.cache/pip/wheels/c1/61/df/768b03527bf006b546dce284eb4249b185669e65afc5fbb2ac
Building wheel for pyyaml (setup.py) ... [?25l[?25hdone
Created wheel for pyyaml: filename=PyYAML-5.3.1-cp36-cp36m-linux_x86_64.whl size=44619 sha256=cdbc63ead8369d7403f47b1adff163ebde2636c9f0c2a5ebd6413d156b2b7a9f
Stored in directory: /root/.cache/pip/wheels/a7/c1/ea/cf5bd31012e735dc1dfea3131a2d5eae7978b251083d6247bd
Building wheel for seqeval (setup.py) ... [?25l[?25hdone
Created wheel for seqeval: filename=seqeval-0.0.12-cp36-none-any.whl size=7423 sha256=3ac4a1cc3b88a9b1a1ed8217f2b8d3abb7f936e853383025888b94019d98a856
Stored in directory: /root/.cache/pip/wheels/4f/32/0a/df3b340a82583566975377d65e724895b3fad101a3fb729f68
Building wheel for py-cpuinfo (setup.py) ... [?25l[?25hdone
Created wheel for py-cpuinfo: filename=py_cpuinfo-7.0.0-cp36-none-any.whl size=20071 sha256=b5491e6fcabbf9ae464c0def53ec6ec27bbf01230ff96f4e34c6a7c44d55d5c9
Stored in directory: /root/.cache/pip/wheels/f1/93/7b/127daf0c3a5a49feb2fecd468d508067c733fba5192f726ad1
Successfully built fire pyyaml seqeval py-cpuinfo
Installing collected packages: tb-nightly, flatbuffers, tf-estimator-nightly, tf-nightly, pyyaml, tensorflow-model-optimization, opencv-python-headless, sentencepiece, tf-slim, seqeval, py-cpuinfo, tf-models-nightly, fire, pybind11, tflite-support, tflite-model-maker
Found existing installation: PyYAML 3.13
Uninstalling PyYAML-3.13:
Successfully uninstalled PyYAML-3.13
Successfully installed fire-0.3.1 flatbuffers-1.12 opencv-python-headless-4.4.0.42 py-cpuinfo-7.0.0 pybind11-2.5.0 pyyaml-5.3.1 sentencepiece-0.1.91 seqeval-0.0.12 tb-nightly-2.4.0a20200914 tensorflow-model-optimization-0.5.0 tf-estimator-nightly-2.4.0.dev2020091401 tf-models-nightly-2.3.0.dev20200914 tf-nightly-2.4.0.dev20200914 tf-slim-1.1.0 tflite-model-maker-0.1.2 tflite-support-0.1.0rc3.dev2
###Markdown
Import the required packages.
###Code
import numpy as np
import os
import tensorflow as tf
assert tf.__version__.startswith('2')
from tflite_model_maker import configs
from tflite_model_maker import model_spec
from tflite_model_maker import question_answer
from tflite_model_maker import QuestionAnswerDataLoader
###Output
_____no_output_____
###Markdown
The "End-to-End Overview" demonstrates a simple end-to-end example. The following sections walk through the example step by step to show more detail. Choose a model_spec that represents a model for question answerEach `model_spec` object represents a specific model for question answer. The Model Maker currently supports MobileBERT and BERT-Base models.Supported Model | Name of model_spec | Model Description--- | --- | ---[MobileBERT](https://arxiv.org/pdf/2004.02984.pdf) | 'mobilebert_qa' | 4.3x smaller and 5.5x faster than BERT-Base while achieving competitive results, suitable for on-device scenario.[MobileBERT-SQuAD](https://arxiv.org/pdf/2004.02984.pdf) | 'mobilebert_qa_squad' | Same model architecture as MobileBERT model and the initial model is already retrained on [SQuAD1.1](https://rajpurkar.github.io/SQuAD-explorer/).[BERT-Base](https://arxiv.org/pdf/1810.04805.pdf) | 'bert_qa' | Standard BERT model that widely used in NLP tasks.In this tutorial, [MobileBERT-SQuAD](https://arxiv.org/pdf/2004.02984.pdf) is used as an example. Since the model is already retrained on [SQuAD1.1](https://rajpurkar.github.io/SQuAD-explorer/), it could coverage faster for question answer task.
###Code
spec = model_spec.get('mobilebert_qa_squad')
###Output
_____no_output_____
###Markdown
Load Input Data Specific to an On-device ML App and Preprocess the DataThe [TriviaQA](https://nlp.cs.washington.edu/triviaqa/) is a reading comprehension dataset containing over 650K question-answer-evidence triples. In this tutorial, you will use a subset of this dataset to learn how to use the Model Maker library.To load the data, convert the TriviaQA dataset to the [SQuAD1.1](https://rajpurkar.github.io/SQuAD-explorer/) format by running the [converter Python script](https://github.com/mandarjoshi90/triviaqamiscellaneous) with `--sample_size=8000` and a set of `web` data. Modify the conversion code a little bit by:* Skipping the samples that couldn't find any answer in the context document;* Getting the original answer in the context without uppercase or lowercase.Download the archived version of the already converted dataset.
###Code
train_data_path = tf.keras.utils.get_file(
fname='triviaqa-web-train-8000.json',
origin='https://storage.googleapis.com/download.tensorflow.org/models/tflite/dataset/triviaqa-web-train-8000.json')
validation_data_path = tf.keras.utils.get_file(
fname='triviaqa-verified-web-dev.json',
origin='https://storage.googleapis.com/download.tensorflow.org/models/tflite/dataset/triviaqa-verified-web-dev.json')
###Output
Downloading data from https://storage.googleapis.com/download.tensorflow.org/models/tflite/dataset/triviaqa-web-train-8000.json
32571392/32570663 [==============================] - 1s 0us/step
Downloading data from https://storage.googleapis.com/download.tensorflow.org/models/tflite/dataset/triviaqa-verified-web-dev.json
1171456/1167744 [==============================] - 0s 0us/step
###Markdown
You can also train the MobileBERT model with your own dataset. If you are running this notebook on Colab, upload your data by using the left sidebar.If you prefer not to upload your data to the cloud, you can also run the library offline by following the [guide](https://github.com/tensorflow/examples/tree/master/tensorflow_examples/lite/model_maker). Use the `QuestionAnswerDataLoader.from_squad` method to load and preprocess the [SQuAD format](https://rajpurkar.github.io/SQuAD-explorer/) data according to a specific `model_spec`. You can use either SQuAD2.0 or SQuAD1.1 formats. Setting parameter `version_2_with_negative` as `True` means the formats is SQuAD2.0. Otherwise, the format is SQuAD1.1. By default, `version_2_with_negative` is `False`.
###Code
train_data = QuestionAnswerDataLoader.from_squad(train_data_path, spec, is_training=True)
validation_data = QuestionAnswerDataLoader.from_squad(validation_data_path, spec, is_training=False)
###Output
_____no_output_____
###Markdown
Customize the TensorFlow ModelCreate a custom question answer model based on the loaded data. The `create` function comprises the following steps:1. Creates the model for question answer according to `model_spec`.2. Train the question answer model. The default epochs and the default batch size are set according to two variables `default_training_epochs` and `default_batch_size` in the `model_spec` object.
###Code
model = question_answer.create(train_data, model_spec=spec)
###Output
INFO:tensorflow:Retraining the models...
###Markdown
Have a look at the detailed model structure.
###Code
model.summary()
###Output
_____no_output_____
###Markdown
Evaluate the Customized ModelEvaluate the model on the validation data and get a dict of metrics including `f1` score and `exact match` etc. Note that metrics are different for SQuAD1.1 and SQuAD2.0.
###Code
model.evaluate(validation_data)
###Output
_____no_output_____
###Markdown
Export to TensorFlow Lite ModelConvert the existing model to TensorFlow Lite model format that you can later use in an on-device ML application. Since MobileBERT is too big for on-device applications, use dynamic range quantization on the model to compress MobileBERT by 4x with the minimal loss of performance. First, define the quantization configuration:
###Code
config = configs.QuantizationConfig.create_dynamic_range_quantization(optimizations=[tf.lite.Optimize.OPTIMIZE_FOR_LATENCY])
config._experimental_new_quantizer = True
###Output
_____no_output_____
###Markdown
Export the quantized TFLite model according to the quantization config and save the vocabulary to a vocab file. The default TFLite model filename is `model.tflite`, and the default vocab filename is `vocab`.
###Code
model.export(export_dir='.', quantization_config=config)
###Output
_____no_output_____
###Markdown
You can use the TensorFlow Lite model file and vocab file in the [bert_qa](https://github.com/tensorflow/examples/tree/master/lite/examples/bert_qa/android) reference app by downloading it from the left sidebar on Colab. You can also evalute the tflite model with the `evaluate_tflite` method. This step is expected to take a long time.
###Code
model.evaluate_tflite('model.tflite', validation_data)
###Output
_____no_output_____
###Markdown
Advanced UsageThe `create` function is the critical part of this library in which the `model_spec` parameter defines the model specification. The `BertQAModelSpec` class is currently supported. There are 2 models: MobileBERT model, BERT-Base model. The `create` function comprises the following steps:1. Creates the model for question answer according to `model_spec`.2. Train the question answer model.This section describes several advanced topics, including adjusting the model, tuning the training hyperparameters etc. Adjust the modelYou can adjust the model infrastructure like parameters `seq_len` and `query_len` in the `BertQAModelSpec` class.Adjustable parameters for model:* `seq_len`: Length of the passage to feed into the model.* `query_len`: Length of the question to feed into the model.* `doc_stride`: The stride when doing a sliding window approach to take chunks of the documents.* `initializer_range`: The stdev of the truncated_normal_initializer for initializing all weight matrices.* `trainable`: Boolean, whether pre-trained layer is trainable.Adjustable parameters for training pipeline:* `model_dir`: The location of the model checkpoint files. If not set, temporary directory will be used.* `dropout_rate`: The rate for dropout.* `learning_rate`: The initial learning rate for Adam.* `predict_batch_size`: Batch size for prediction.* `tpu`: TPU address to connect to. Only used if using tpu. For example, you can train the model with a longer sequence length. If you change the model, you must first construct a new `model_spec`.
###Code
new_spec = model_spec.get('mobilebert_qa')
new_spec.seq_len = 512
###Output
_____no_output_____
###Markdown
Copyright 2020 The TensorFlow Authors.
###Code
#@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###Output
_____no_output_____
###Markdown
BERT Question Answer with TensorFlow Lite Model Maker View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook The [TensorFlow Lite Model Maker library](https://www.tensorflow.org/lite/guide/model_maker) simplifies the process of adapting and converting a TensorFlow model to particular input data when deploying this model for on-device ML applications.This notebook shows an end-to-end example that utilizes the Model Maker library to illustrate the adaptation and conversion of a commonly-used question answer model for question answer task. Introduction to BERT Question Answer Task The supported task in this library is extractive question answer task, which means given a passage and a question, the answer is the span in the passage. The image below shows an example for question answer. Answers are spans in the passage (image credit: SQuAD blog) As for the model of question answer task, the inputs should be the passage and question pair that are already preprocessed, the outputs should be the start logits and end logits for each token in the passage.The size of input could be set and adjusted according to the length of passage and question. End-to-End Overview The following code snippet demonstrates how to get the model within a few lines of code. The overall process includes 5 steps: (1) choose a model, (2) load data, (3) retrain the model, (4) evaluate, and (5) export it to TensorFlow Lite format. ```python Chooses a model specification that represents the model.spec = model_spec.get('mobilebert_qa') Gets the training data and validation data.train_data = DataLoader.from_squad(train_data_path, spec, is_training=True)validation_data = DataLoader.from_squad(validation_data_path, spec, is_training=False) Fine-tunes the model.model = question_answer.create(train_data, model_spec=spec) Gets the evaluation result.metric = model.evaluate(validation_data) Exports the model to the TensorFlow Lite format with metadata in the export directory.model.export(export_dir)``` The following sections explain the code in more detail. PrerequisitesTo run this example, install the required packages, including the Model Maker package from the [GitHub repo](https://github.com/tensorflow/examples/tree/master/tensorflow_examples/lite/model_maker).
###Code
!pip install -q tflite-model-maker
###Output
_____no_output_____
###Markdown
Import the required packages.
###Code
import numpy as np
import os
import tensorflow as tf
assert tf.__version__.startswith('2')
from tflite_model_maker import model_spec
from tflite_model_maker import question_answer
from tflite_model_maker.config import ExportFormat
from tflite_model_maker.question_answer import DataLoader
###Output
_____no_output_____
###Markdown
The "End-to-End Overview" demonstrates a simple end-to-end example. The following sections walk through the example step by step to show more detail. Choose a model_spec that represents a model for question answerEach `model_spec` object represents a specific model for question answer. The Model Maker currently supports MobileBERT and BERT-Base models.Supported Model | Name of model_spec | Model Description--- | --- | ---[MobileBERT](https://arxiv.org/pdf/2004.02984.pdf) | 'mobilebert_qa' | 4.3x smaller and 5.5x faster than BERT-Base while achieving competitive results, suitable for on-device scenario.[MobileBERT-SQuAD](https://arxiv.org/pdf/2004.02984.pdf) | 'mobilebert_qa_squad' | Same model architecture as MobileBERT model and the initial model is already retrained on [SQuAD1.1](https://rajpurkar.github.io/SQuAD-explorer/).[BERT-Base](https://arxiv.org/pdf/1810.04805.pdf) | 'bert_qa' | Standard BERT model that widely used in NLP tasks.In this tutorial, [MobileBERT-SQuAD](https://arxiv.org/pdf/2004.02984.pdf) is used as an example. Since the model is already retrained on [SQuAD1.1](https://rajpurkar.github.io/SQuAD-explorer/), it could coverage faster for question answer task.
###Code
spec = model_spec.get('mobilebert_qa_squad')
###Output
_____no_output_____
###Markdown
Load Input Data Specific to an On-device ML App and Preprocess the DataThe [TriviaQA](https://nlp.cs.washington.edu/triviaqa/) is a reading comprehension dataset containing over 650K question-answer-evidence triples. In this tutorial, you will use a subset of this dataset to learn how to use the Model Maker library.To load the data, convert the TriviaQA dataset to the [SQuAD1.1](https://rajpurkar.github.io/SQuAD-explorer/) format by running the [converter Python script](https://github.com/mandarjoshi90/triviaqamiscellaneous) with `--sample_size=8000` and a set of `web` data. Modify the conversion code a little bit by:* Skipping the samples that couldn't find any answer in the context document;* Getting the original answer in the context without uppercase or lowercase.Download the archived version of the already converted dataset.
###Code
train_data_path = tf.keras.utils.get_file(
fname='triviaqa-web-train-8000.json',
origin='https://storage.googleapis.com/download.tensorflow.org/models/tflite/dataset/triviaqa-web-train-8000.json')
validation_data_path = tf.keras.utils.get_file(
fname='triviaqa-verified-web-dev.json',
origin='https://storage.googleapis.com/download.tensorflow.org/models/tflite/dataset/triviaqa-verified-web-dev.json')
###Output
_____no_output_____
###Markdown
You can also train the MobileBERT model with your own dataset. If you are running this notebook on Colab, upload your data by using the left sidebar.If you prefer not to upload your data to the cloud, you can also run the library offline by following the [guide](https://github.com/tensorflow/examples/tree/master/tensorflow_examples/lite/model_maker). Use the `DataLoader.from_squad` method to load and preprocess the [SQuAD format](https://rajpurkar.github.io/SQuAD-explorer/) data according to a specific `model_spec`. You can use either SQuAD2.0 or SQuAD1.1 formats. Setting parameter `version_2_with_negative` as `True` means the formats is SQuAD2.0. Otherwise, the format is SQuAD1.1. By default, `version_2_with_negative` is `False`.
###Code
train_data = DataLoader.from_squad(train_data_path, spec, is_training=True)
validation_data = DataLoader.from_squad(validation_data_path, spec, is_training=False)
###Output
_____no_output_____
###Markdown
Customize the TensorFlow ModelCreate a custom question answer model based on the loaded data. The `create` function comprises the following steps:1. Creates the model for question answer according to `model_spec`.2. Train the question answer model. The default epochs and the default batch size are set according to two variables `default_training_epochs` and `default_batch_size` in the `model_spec` object.
###Code
model = question_answer.create(train_data, model_spec=spec)
###Output
_____no_output_____
###Markdown
Have a look at the detailed model structure.
###Code
model.summary()
###Output
_____no_output_____
###Markdown
Evaluate the Customized ModelEvaluate the model on the validation data and get a dict of metrics including `f1` score and `exact match` etc. Note that metrics are different for SQuAD1.1 and SQuAD2.0.
###Code
model.evaluate(validation_data)
###Output
_____no_output_____
###Markdown
Export to TensorFlow Lite ModelConvert the trained model to TensorFlow Lite model format with [metadata](https://www.tensorflow.org/lite/convert/metadata) so that you can later use in an on-device ML application. The vocab file are embedded in metadata. The default TFLite filename is `model.tflite`.In many on-device ML application, the model size is an important factor. Therefore, it is recommended that you apply quantize the model to make it smaller and potentially run faster.The default post-training quantization technique is dynamic range quantization for the BERT and MobileBERT models.
###Code
model.export(export_dir='.')
###Output
_____no_output_____
###Markdown
You can use the TensorFlow Lite model file in the [bert_qa](https://github.com/tensorflow/examples/tree/master/lite/examples/bert_qa/android) reference app using [BertQuestionAnswerer API](https://www.tensorflow.org/lite/inference_with_metadata/task_library/bert_question_answerer) in [TensorFlow Lite Task Library](https://www.tensorflow.org/lite/inference_with_metadata/task_library/overview) by downloading it from the left sidebar on Colab. The allowed export formats can be one or a list of the following:* `ExportFormat.TFLITE`* `ExportFormat.VOCAB`* `ExportFormat.SAVED_MODEL`By default, it just exports TensorFlow Lite model with metadata. You can also selectively export different files. For instance, exporting only the vocab file as follows:
###Code
model.export(export_dir='.', export_format=ExportFormat.VOCAB)
###Output
_____no_output_____
###Markdown
You can also evaluate the tflite model with the `evaluate_tflite` method. This step is expected to take a long time.
###Code
model.evaluate_tflite('model.tflite', validation_data)
###Output
_____no_output_____
###Markdown
Advanced UsageThe `create` function is the critical part of this library in which the `model_spec` parameter defines the model specification. The `BertQASpec` class is currently supported. There are 2 models: MobileBERT model, BERT-Base model. The `create` function comprises the following steps:1. Creates the model for question answer according to `model_spec`.2. Train the question answer model.This section describes several advanced topics, including adjusting the model, tuning the training hyperparameters etc. Adjust the modelYou can adjust the model infrastructure like parameters `seq_len` and `query_len` in the `BertQASpec` class.Adjustable parameters for model:* `seq_len`: Length of the passage to feed into the model.* `query_len`: Length of the question to feed into the model.* `doc_stride`: The stride when doing a sliding window approach to take chunks of the documents.* `initializer_range`: The stdev of the truncated_normal_initializer for initializing all weight matrices.* `trainable`: Boolean, whether pre-trained layer is trainable.Adjustable parameters for training pipeline:* `model_dir`: The location of the model checkpoint files. If not set, temporary directory will be used.* `dropout_rate`: The rate for dropout.* `learning_rate`: The initial learning rate for Adam.* `predict_batch_size`: Batch size for prediction.* `tpu`: TPU address to connect to. Only used if using tpu. For example, you can train the model with a longer sequence length. If you change the model, you must first construct a new `model_spec`.
###Code
new_spec = model_spec.get('mobilebert_qa')
new_spec.seq_len = 512
###Output
_____no_output_____ |
notebooks/.ipynb_checkpoints/Tutorial_05_LibraryDataStructures-checkpoint.ipynb | ###Markdown
The fun part: Scientific & Numerical Data StructuresAlthough `Python` was not originally designed for scientific data, its community-base and free nature allowed for the development of packages and libraries that handle it nicely & efficiently. Beyond the data types and collections we have already seen, scientific computation needs specific data structures, as we want to be able to handle (efficiently):- large amounts of data- multiple dimensions- mathematical and statistical operation over parts or the whole data set- metadata and data attributes Here we will use these basic modules of scientific & numerical computing: `math`, `scipy`, `numpy`, `pandas`, `xarray` & `matplotlib`Note: these packages are also referred as libraries or modules *** `math` moduleBasic math operation (as methods or functions) and numbers (as attributes) Try it out! - Execute the code below to try different ways to import the math module.
###Code
import math
import math as m
from math import pi
print(math.pi, m.pi, pi,'\n\n')
###Output
_____no_output_____
###Markdown
Try it out! - Try the next code to use some functions from the math module
###Code
rads = 2*pi
degrees = math.degrees(rads)
print('{} radians is equal to {} degrees'.format(rads,m.floor(degrees)))
###Output
_____no_output_____ |
site/gtrends/data/.ipynb_checkpoints/script_trends-checkpoint.ipynb | ###Markdown
import syssys.argv[0] (nom du fichier)sys.argv[1] (1er paramètre, etc...) Documentation de l'API :https://github.com/GeneralMills/pytrends open issues Limites de requêtes sur Google :- générer un string aléatoire à passer en paramètre custom_useragenthttps://github.com/GeneralMills/pytrends/issues/77Format JSON :- quel format lu par chart.js, d3.js ?http://stackoverflow.com/questions/24929931/drawing-line-chart-in-chart-js-with-json-responsePlus de 5 recherches à la fois :- cf open issues sur pytrendshttps://github.com/GeneralMills/pytrends/issues/77[résolu] Gérer les timestamps et timezones :- cf : https://docs.python.org/3/library/datetime.htmldatetime.tzinfo Les tendances sur les recherches - 'Élection présidentielle française de 2017' : '/m/0n49cn3' (Élection) Codes associés aux candidats :- Manuel Valls : '/m/047drb0' (Ancien Premier ministre français)- François Fillon : '/m/0fqmlm' (Ancien Ministre de l’Écologie, du Développement durable et de l’Énergie)- Vincent Peillon : '/m/0551vp' (Homme politique)- François Bayrou : '/m/02y2cb' (Homme politique)- François Hollande : '/m/02qg4z' (Président de la République française)- Jean-Luc Mélanchon : '/m/04zzm99' (Homme politique)- Yannick Jadot : '/m/05zztc0' (Ecologiste)- Nicolas Dupont-Aignan (Debout la France) : '/m/0f6b18'- Michèle Alliot-Marie (Indépendante) : '/m/061czc' (Ancienne Ministre de l'Intérieur de France)- Nathalie Artaud (LO) : pas dispo- Philippe Poutou (NPA) : '/m/0gxyxxy'- Emmanuel Macron : '/m/011ncr8c' (Ancien Ministre de l'Économie et des Finances)- Jacques Cheminade : '/m/047fzn' Codes associés aux partis :- LR : '/g/11b7n_r2jq'- PS : '/m/01qdcv'- FN : '/m/0hp7g'- EELV : '/m/0h7nzzw'- FI (France Insoumise) : pas dispo ... renvoie vers le PCF- PCF : '/m/01v8x4'- Debout la France : '/m/02rwc3q'- MoDem : '/m/02qt5xp' (Mouvement Démocrate)- Lutte Ouvrière : '/m/01vvcv'- Nouveau Parti Anticapitalise : '/m/04glk_t'- En marche! : pas dispo
###Code
TrendReq('mdp', 'user', custom_useragent=None).suggestions("debout la france")
###Output
_____no_output_____
###Markdown
Fonction qui sauvegarde les requetes via l'API en JSON
###Code
def trends_to_json(query='candidats', periode='7d', geo='FR'):
# Formats possibles pour la date : now 1-H, now 4-H, now 1-d, now 7-d, today 1-m, today 3-m
periodes = {'1h': 'now 1-H', '4h': 'now 4-H', '1d': 'now 1-d', '7d': 'now 7-d',
'1m': 'today 1-m','3m': 'today 3-m'}
# Les termes de recherche (5 au maximum separes par des virgules)
# On associe a un type de recherche la liste des parametres correspondants
queries = {'candidats': '/m/047drb0, /m/0fqmlm', 'partis': 'a completer'}
# se referer a la table de correspondance ci-dessus
if (query not in queries) or (periode not in periodes):
print('Erreur de parametre')
return
try:
# Connection to Google (use a valid Google account name for increased query limits)
pytrend = TrendReq('[email protected]', 'projet_fil_rouge', custom_useragent=None)
# Possibilite de periode personnalise : specifier deux dates (ex : 2015-01-01 2015-12-31)
# geographie : FR (toute France), FR-A ou B ou C... (region de France par ordre alphabetique)
# categorie politique : cat = 396
# On fait la requete sur Google avec les parametres choisis
payload = {'q': queries[query], 'geo': geo, 'date': periodes[periode]}
df = pytrend.trend(payload, return_type='dataframe')
# Formattage de la date
if periode in ['1h', '4h', '1d', '7d']:
dates = []
rdict = {' à': '', ' UTC−8': '', 'janv.': '01', 'févr.': '02', 'mars': '03', 'avr.': '04',
'mai': '05', 'juin': '06', 'juil.': '07', 'août': '08', 'sept.': '09', 'oct.': '10',
'nov.': '11', 'déc.': '12'}
robj = re.compile('|'.join(rdict.keys()))
for date in df['Date']: # converting str to datetime object
t = datetime.strptime(robj.sub(lambda m: rdict[m.group(0)], date),
'%d %m %Y %H:%M') + timedelta(hours=9) # GMT+1
dates.append(datetime.strftime(t, '%d-%m %H:%M'))
df['Date'] = dates
df.set_index('Date', inplace=True)
# Sauvegarde en JSON
df.to_json(query + '_' + periode + '.json', orient='split')
status = 'sauvegarde dans : ' + query + '_' + periode + '.json'
except:
print('Erreur')
return
###Output
_____no_output_____
###Markdown
On lance la fonction
###Code
trends_to_json(query='candidats', periode='1h')
pd.read_json('candidats_4h.json', orient='split')
###Output
_____no_output_____ |
code/algorithms/course_udemy_1/Array Sequences/Array Sequences Interview Questions/Array Sequence Interview Questions - SOLUTIONS/Unique Characters in String - SOLUTION.ipynb | ###Markdown
Unique Characters in String ProblemGiven a string,determine if it is compreised of all unique characters. For example, the string 'abcde' has all unique characters and should return True. The string 'aabcde' contains duplicate characters and should return false. SolutionWe'll show two possible solutions, one using a built-in data structure and a built in function, and another using a built-in data structure but using a look-up method to check if the characters are unique.
###Code
def uni_char(s):
return len(set(s)) == len(s)
def uni_char2(s):
chars = set()
for let in s:
# Check if in set
if let in chars:
return False
else:
#Add it to the set
chars.add(let)
return True
###Output
_____no_output_____
###Markdown
Test Your Solution
###Code
"""
RUN THIS CELL TO TEST YOUR CODE>
"""
from nose.tools import assert_equal
class TestUnique(object):
def test(self, sol):
assert_equal(sol(''), True)
assert_equal(sol('goo'), False)
assert_equal(sol('abcdefg'), True)
print 'ALL TEST CASES PASSED'
# Run Tests
t = TestUnique()
t.test(uni_char)
###Output
ALL TEST CASES PASSED
|
src/user_guide/auxiliary_steps.ipynb | ###Markdown
Makefile-style pattern-matching rules * **Difficulty level**: intermediate* **Time need to lean**: 20 minutes or less* **Key points**: * Option `provides` extends the "data-flow" style workflow that allows steps to generate different outputs. * Steps with `provides` section option has default `step_output`. `input` can be derived from pattern-matched variables. Auxiliary steps Auxiliary steps are special steps that are executed to provide [targets](sos_actions.html) that are required by others.For example, when the following step is executed with an input file `bamfile` (with extension `.bam`), it checks the existence of input file (`bamfile`), and a dependent index file (with extension `.bam.bai`).```sos[100 (call variant)]input: bamfiledepends: bamfile + '.bai'run: commands to call variants from input bam file```Because the step depends on an index file, SoS will look in the script for a step that provides such a target, which would be similar to```sos[index_bam : provides='{sample}.bam.bai']input: f"{sample}.bam"run: expand=True samtools index {_input}```Such a step is characterized by a **`provides`** option (or a step with simple `output` statement and is called an auxiliary step. In this particular case, if `bamfile="AS123.bam"`, the requested dependent file would be `AS123.bam.bai`. Through the matching mechanism of option `provides`, the `index_bam` step would be executed with variables `sample="AS123"` and `step_output="AS123.bam.bai"`. Unless option `-T` (see [tracing dependency](trace_dependency.html) for details) is specified, **SoS will not check if an depdendent target can be generated by an auxiliary step if it already exists**. In an extreme case, `sos run -t filename` will quit directly if `filename` already exists. An auxiliary step can trigger other auxiliary steps and form a DAG (Directed Acyclic Graph). Acutually, you can write workflows in a make-file style with all auxiliary steps and execute workflows defined by targets. If you are familiar with Makefile, especially [snakemake](https://bitbucket.org/johanneskoester/snakemake), it can be natural for you to implement your workflow in this style. The advantage of SoS is that **you can use either or both forward-style and makefile-style steps to define your workflow** and take advantages of both approaches. Step option `provides` An auxiliary step is defined by the `provides` option in section head, in the format of```sos[step_name : provides=target]```where `target` can be* A filename or file pattern such as `"{sample}.bam.idx"`* Other types of targets such as `executable("ms")`* A list (sequence) of one or more file patterns and targets. File Pattern A file pattern is a filename with optional patterns with variable names enbraced in `{ }`. SoS matches filenames with the patterns and, if successful, assign variables with matched parts of the names. For example,```[compress: provides = '{filename}.bam']```would be triggered with target `sample_A.bam` and `sample_B.bam`. When the step is triggered by `sample_A.bam`, it defines variable `filename` as `sample_A` and sets the output of the step as `sample_A.bam`.The following example removes all local `*.bam` and `*.bam.bi` file before it executes three workflows defined by `targets`. We use magic `%run` to execute it, which is equivalent to executing it from command line using commands such as```bash sos run myscript -t TS1.bam``` Let us create a workflow with two auxiliary steps `compress` and `index`. The `compress` step generates a `.bam` file (no input here for simplicity) and `index` step creates a `.bam.bai` file from the `.bam` file.
###Code
%save test_provides.sos -f
[compress: provides = '{filename}.bam']
print(f"> {step_name} input to {_output}")
sh: expand=True
touch {_output}
[index: provides = '{filename}.bam.bai']
input: f"{filename}.bam"
print(f"> {step_name} {_input} to {_output}")
sh: expand=True
touch {_output}
###Output
_____no_output_____
###Markdown
If we only want to generate a `bam` file (with option `-t TS1.bam`), the `compress` step is executed
###Code
!rm -f TS1.bam TS1.bam.bai
%runfile test_provides -t TS1.bam -v1
###Output
> compress input to TS1.bam
###Markdown
If we would like to generate both `.bam` and `.bam.bai` files (with option `-t TS2.bam.bai`), both steps are executed.
###Code
!rm -f TS2.bam TS2.bam.bai
%runfile test_provides -t TS2.bam.bai -v1
###Output
> compress input to TS2.bam
> index TS2.bam to TS2.bam.bai
###Markdown
As you can see from the output, when the first workflow is executed with target `TS1.bam`, step `compress` is executed to produce it. In the run, both steps are executed to generate `TS2.bam` and then `TS2.bam.bai`. Non-file targets In addition to output files, an auxiliary step can provide targets of other types. A most widely used target is `sos_variable`, which provides variables that can be accessed by later steps. For example,
###Code
%run -v1
# this step provides variable `numNotebooks`
[count: provides=sos_variable('numNotebooks')]
import glob
numNotebooks = len(glob.glob('*.ipynb'))
[default]
depends: sos_variable('numNotebooks')
print(f"There are {numNotebooks} notebooks in this directory")
###Output
There are 94 notebooks in this directory
###Markdown
However, for this particular example, it is more straightforward to return the variable with [option `shared`](shared_variables.html) as follows:
###Code
%run -v1
# this step provides variable `numNotebooks`
[count: shared='numNotebooks']
import glob
numNotebooks = len(glob.glob('*.ipynb'))
[default]
depends: sos_variable('numNotebooks')
print(f"There are {numNotebooks} notebooks in this directory")
###Output
There are 94 notebooks in this directory
###Markdown
Multiple targets You can specify multiple targets to the `provides` option. A step would be triggered if any of the targets matches. For example, the `temp` step is triggered twice in the following example, first time by target `text.bak` and the second time by target `text.tmp`.
###Code
!rm -f text.bak text.tmp
%run -v1
[temp: provides = ['{filename}.bak', '{filename}.tmp']]
print(f"Touch {_output}")
sh: expand=True
touch {_output}
[default]
depends: 'text.bak', 'text.tmp'
###Output
Touch text.tmp
Touch text.bak
###Markdown
However, depending on what the auxiliary step is designed, it might be generating multiple output at the same time and it would be wasteful to execute the step multiple times. In this case, you can define an `output` statement and let SoS know that the execution of the step generates multiple targets.
###Code
!rm -f text.bak text.tmp
%run -v1
[temp: provides = ['{filename}.bak', '{filename}.tmp']]
output: f'{filename}.bak', f'{filename}.tmp'
print(f"Touch {_output}")
sh: expand=True
touch {_output}
[default]
depends: 'text.bak', 'text.tmp'
###Output
Touch text.bak text.tmp
###Markdown
How to use Makefile-style rules to generate required files * **Difficulty level**: intermediate* **Time need to lean**: 10 minutes or less* **Key points**: * Option `provides` Auxiliary steps and makefile-style workflows Auxiliary steps are special steps that are executed to provide [targets](../documentation/Targets_and_Actions.html) that are required by others.For example, when the following step is executed with an input file `bamfile` (with extension `.bam`), it checks the existence of input file (`bamfile`), and a dependent index file (with extension `.bam.bai`).```sos[100 (call variant)]input: bamfiledepends: bamfile + '.bai'run: commands to call variants from input bam file```Because the step depends on an index file, SoS will look in the script for a step that provides such a target, which would be similar to```sos[index_bam : provides='{sample}.bam.bai']input: f"{sample}.bam"run: expand=True samtools index {input}```Such a step is characterized by a **`provides`** option (or a step with simple `output` statement, or a **`shared`** option that will be discussed later) and is called an auxiliary step. In this particular case, if `bamfile="AS123.bam"`, the requested dependent file would be `AS123.bam.bai`. Through the matching mechanism of option `provides`, the `index_bam` step would be executed with variables `sample="AS123"` and `output=["AS123.bam.bai"]`. SoS will always check if an depdendent target can be generated by an auxiliary step. If a target cannot be generated by an auxiliary step, it must exist before the execution of the workflow. Otherwise, sos will add the auxiliary step to the DAG and execute the step to generate the file even if it already exists. The normal signature rules apply (see [Execution of workflow](../tutorials/Execution_of_Workflow.html) for details) so you use option `-s build` to ignore the auxiliary step if the target already exists. An auxiliary step can trigger other auxiliary steps and form a DAG (Directed Acyclic Graph). Acutually, you can write workflows in a make-file style with all auxiliary steps and execute workflows defined by targets. If you are familiar with Makefile, especially [snakemake](https://bitbucket.org/johanneskoester/snakemake), it can be natural for you to implement your workflow in this style. The advantage of SoS is that **you can use either or both forward-style and makefile-style steps to define your workflow** and take advantages of both approaches. For example, people frequently need to create fake targets to trigger steps that do not produce any target in a makefile-style workflow system, but this is not needed in SoS because steps defined in forward-style will always be executed. Automatic auxiliary step Because we jump into more complex pattern based auxiliary steps, it is worth mentioning that any step with a simple `output` statement can be triggered with the specified `output`, making it a simple auxiliary step without an explicit `provides` option. That is to say, when you have a regular step with a statement that specifies one or more file names (or other targets), without using any other variables such as `_input`, it can be triggered by the output.For example, the following workflow has a single step that generates an output file `a.md`. It can be triggered by specifying the name of the workflow
###Code
%sandbox
%preview -n a.md
%run report
[report]
output: 'a.md'
report: output=_output
* item 1
* item 2
###Output
_____no_output_____
###Markdown
or be triggered by the use of the `-t` (target) option
###Code
%sandbox
%preview -n a.md
%run -t a.md
[report]
output: 'a.md'
report: output=_output
* item 1
* item 2
###Output
_____no_output_____
###Markdown
which is more or less equivalent to the following "pure" auxiliary step with a `provides` option (explained below) but is actually more flexible in that it can also be triggered by workflow name.
###Code
%sandbox
%preview -n a.md
%run -t a.md
[report: provides='a.md']
report: output=_output
* item 1
* item 2
###Output
_____no_output_____
###Markdown
Step option `provides` An auxiliary step can be defined by the `provides` option in section head, in the format of```sos[step_name : provides=target]```where `target` can be* A filename or file pattern such as `"{sample}.bam.idx"`* Other types of targets such as `executable("ms")`* A list (sequence) of one or more file patterns and targets. File Pattern A file pattern is a filename with optional patterns with variable names enbraced in `{ }`. SoS matches filenames with the patterns and, if successful, assign variables with matched parts of the names. For example,```[compress: provides = '{filename}.bam']```would be triggered with target `sample_A.bam` and `sample_B.bam`. When the step is triggered by `sample_A.bam`, it defines variable `filename` as `sample_A` and sets the output of the step as `sample_A.bam`.The following example removes all local `*.bam` and `*.bam.bi` file before it executes three workflows defined by `targets`. We use magic `%run` to execute it, which is equivalent to executing it from command line using commands such as```bash sos run myscript -t TS1.bam```
###Code
%sandbox
%preview --off
%run -t TS1.bam
[compress: provides = '{filename}.bam']
print(f"> {step_name} input to {_output}")
sh: expand=True
touch {_output}
[index: provides = '{filename}.bam.bai']
input: f"{filename}.bam"
print(f"> {step_name} {_input} to {_output}")
sh: expand=True
touch {_output}
%sandbox
%rerun -t TS2.bam.bai
###Output
> compress input to TS2.bam
> index TS2.bam to TS2.bam.bai
###Markdown
As you can see from the output, when the first workflow is executed with target `TS1.bam`, step `compress` is executed to produce it. In the run, both steps are executed to generate `TS2.bam` and then `TS2.bam.bai`. Non-file targets In addition to output files, an auxiliary step can provide targets of other types. A most widely used target is `sos_variable`, which provides variables that can be accessed by later steps. For example,
###Code
# remove var in case it is defined already
%dict --del numNotebooks
# this step provides variable `numNotebooks`
[count: provides=sos_variable('numNotebooks')]
import glob
numNotebooks = len(glob.glob('*.ipynb'))
[default]
depends: sos_variable('numNotebooks')
print(f"There are {numNotebooks} notebooks in this directory")
###Output
_____no_output_____
###Markdown
Multiple targets You can specify multiple targets to the `provides` option and a step would be triggered if any of the targets matches. For example, the `temp` step is triggered twice in the following example, first time by target `text.bak` and the second time by target `text.tmp`.
###Code
%sandbox
%preview --off
[temp: provides = ['{filename}.bak', '{filename}.tmp']]
print(f"Touch {_output}")
sh: expand=True
touch {_output}
[default]
depends: 'text.bak', 'text.tmp'
###Output
_____no_output_____
###Markdown
`output` statement As you have noticed, auxiliary steps usually do not define their own `output` statement. This is because auxiliary steps have a default `output` statement```output: __default_output__```where `__default_output__` is the matched target. You can cutomize the output of an auxiliary step by defining your own `output` statement. This technique is usually used for the generation of multiple output files.For example, in the following example, step `touch` is triggered three times for the generation of three targets.
###Code
%sandbox
%preview --off
[touch: provides = ['1.txt', '2.txt', '3.txt']]
sh: expand=True
echo "Create {_output}"
touch {_output}
[default]
depends: '1.txt', '2.txt', '3.txt'
###Output
_____no_output_____
###Markdown
You can however design your auxiliary step to generate multiple outputs by specifying a different `output`:
###Code
%sandbox
%preview --off
%run
[touch: provides = ['1.txt', '2.txt', '3.txt']]
print(f"step triggered by {__default_output__}")
output: '1.txt', '2.txt', '3.txt'
sh: expand=True
echo "Write A to {_output}"
touch {_output}
[default]
depends: '1.txt', '2.txt', '3.txt'
###Output
step triggered by ['1.txt']
Write A to 1.txt 2.txt 3.txt
###Markdown
In this example, the `touch` step is triggered by one of the three files, but it produces three output files `1.txt`, `2.txt`, `3.txt`. The `default` step will not look for steps to generate the other two files because they have already been generated. Step option `shared` Another common task of SoS steps is to provide some information through SoS variables. This can be achived by a `provides` option with `sos_variale` targets, but can be more easily implemented with a `shared` option.
###Code
# remove var in case it is defined already
%dict --del numNotebooks
# this step provides variable `numNotebooks`
[count: shared='numNotebooks']
import glob
numNotebooks = len(glob.glob('*.ipynb'))
[default]
depends: sos_variable('numNotebooks')
print(f"There are {numNotebooks} notebooks in this directory")
###Output
_____no_output_____
###Markdown
This workflow has one step that depends on a `sos_variable` `numNotebooks`. The `count` step is then executed to provide this variable.There is however a minor difference between the `shared` and `provides` for the specification of shared variables. That is to say, whereas```[step: provides=[sos_variable('var1'), sos_variable('var2')]```would be triggered by `var1` or `var2` and generate **one of** the variables (due to the multi-target rule of option `provides`),```[step: shared=['var1', 'var2']]```would be assumed to generate **both of** the variables, so technically speaking the `shared` version is equivalent to```[step: provides=[sos_variable('var1'), sos_variable('var2')]output: sos_variable('var1'), sos_variable('var2')``` Executing workflows with auxiliary steps You can execute forward-style workflows by specifying workflow name (can be `default`) from command line. The workflow can trigger auxiliary steps for the generation of unavailable targets. The workflows are executed with a mind-setting of **apply workflow to certain input file**.You can execute a makefile-style workflow by specifying one or more targets using option `-t` (target). SoS would collect all auxiliary steps in the script and create DAGs to generate these targets. The workflows are executed with a mind-setting of **execute necessary steps to generate specified output files**. Forward-style workflows defined in the script, if defined, would be ignored.You can specify both a forward-style workflow and one or more targets using the `-t` option. In this case SoS would create a DAG with both the forward-style workflow and steps to produce the specified targets. The DAG would then be trimmed to a sub-DAG that produce only specified targets. The usage is usually used to **produce only selected targets from a forward-style workflow**. In contrast to the second case where targets have to be targets of auxiliary steps, targets specified in this case can be any output targets from the forward-style workflow. Let us use a slightly complex example with both forward-style and auxiliary steps to demonstrate these three cases. In this case we are using action `sos_run` to execute workflows as multiple subworkflows, saving us the trouble to execute the script multiple times.
###Code
%sandbox --expect-error
%run
[gzip: provides='{name}.gz']
input: f"{name}"
print(f"> {step_name} {input} to {output}")
run: expand=True
touch {output}
[download: provides='{name}.pdf']
print(f"> {step_name} {output}")
run: expand=True
touch {output}
[process_10]
print(f"> Running step {step_name}")
[process_20]
depends: "step20.pdf"
output: "step20.out"
print(f"> Running step {step_name} to produce {output}")
run: expand=True
touch {output}
[process_30]
output: "step30.out"
print(f"> Running step {step_name} to produce {output}")
run: expand=True
touch {output}
[default]
print("Forward-style workflow")
sos_run("process")
print("\nMakefile-style workflow")
sos_run(targets="ms.pdf.gz")
print("\nTargets of forward-style workflow")
sos_run("process", targets="step20.out")
print("\nTargets from forward-style and makefile-style workflows")
sos_run("process", targets=["step20.out", "ms1.pdf.gz"])
os.remove('step20.out')
print("\nInvalid target step20.out")
sos_run(targets=["step20.out"])
###Output
Forward-style workflow
> Running step process_10
###Markdown
This example has a forward-style workflow `process` in which step `process_20` depends on an auxiliary step `download`.1. In the first case with command line equivalence ```bash sos run myscript process ``` the forward-style workflow `process` is executed.2. In the second example ```bash sos run myscript -t ms.pdf.gz ``` two auxiliary steps `download` and `gzip` are called to produce target `ms.pdf.gz`. 3. In the third example ```bash sos run myscript process -t step20.out ``` the `process` workflow is executed partially until it generates target `step20.out`. 4. In the fourth example ```bash sos run myscript process -t step20.out ms1.pdf.gz ``` the `process` workflow is executed partially to produce target `step20.out`, and two auxiliary steps are executed to produce the additional target `ms1.pdf.gz`. 5. In the last example ```bash sos run myscript -t step20.out ``` SoS could not find an auxiliary step to produce target `step20.out` and exited with error. Note that SoS would not try to execute a default workflow (workflow `default` or the only forwar-style workflow defined in the script) with the presence of option `-t`. Output DAG of execution SoS allows the output of Direct Acyclic Graph in [graphviz dot format](http://www.graphviz.org/content/dot-language) of the execution of the workflow using option `-d`. DAGs would be written to standard output if the option `-d` is given without value, and to one or more files if a filename is given. An extension `.dot` would be automatically added if needed. Because of the dynamic nature of SoS, multiple DAGs could be outputted with increasing or decreasing number of nodes, resulting multiple files named `FILE.dot`, `FILE_2.dot`, etc.Let us create an example with some nodes, and execute the workflow with two targets `B2.txt` and `C2.txt`
###Code
%sandbox --dir temp
%preview -n dag.dot
!rm -f A?.txt B?.txt C?.txt
%run -t B2.txt C2.txt -d dag
[A_1]
input: 'B1.txt'
output: 'A1.txt'
sh:
touch A1.txt
[A_2]
depends: 'B2.txt'
sh:
touch A2.txt
[B1: provides='B1.txt']
depends: 'B2.txt'
sh:
touch B1.txt
[B2: provides='B2.txt']
depends: 'B3.txt', 'C1.txt'
sh:
touch B2.txt
[B3: provides='B3.txt']
sh:
touch B3.txt
[C1: provides='C1.txt']
depends: 'C2.txt', 'C3.txt'
sh:
touch C1.txt
[C2: provides='C2.txt']
depends: 'C4.txt'
sh:
touch C2.txt
[C3: provides='C3.txt']
depends: 'C4.txt'
sh:
touch C3.txt
[C4: provides='C4.txt']
sh:
touch C4.txt
###Output
_____no_output_____
###Markdown
The `-d` option produced two `.dot` files that can be converted to png format using `dot` command (e.g. `dot dag.dot -T png > dag.png`) but here we use the `%preview` magic to display them directory. As you might have guessed, the first DAG is the complete DAG created from the workflow, and the second DAG is the trimmed down DAG that produces targets `B2.txt` and `C2.txt`. In real world applications, the DAG might grow with additional auxiliary steps if some input or dependency files are unavailable.
###Code
# Clean up
!rm -rf temp
###Output
_____no_output_____
###Markdown
Makefile-style workflow Using **auxiliary steps** that are only executed to provide desired output, a SoS workflow can be constructed dynamically to produce the specified target. For example, the following pipeline does not have any numbered steps and is triggered by option `-t test.vcf` (target).
###Code
%sandbox
# preview multiple DAG
%preview -n target.dot -v4
!touch test.bam
%run -t test.vcf -d target.dot
# this step provides variable `var`
[index: provides='{filename}.bam.bai']
input: f"{filename}.bam"
run: expand=True
echo "Generating {_output}"
touch {_output}
[call: provides='{filename}.vcf']
input: f"{filename}.bam"
depends: f"{_input}.bai"
run: expand=True
echo "Calling variants from {_input} with {_depends} to {_output}"
touch {_output}
###Output
echo "Generating test.bam.bai"
Generating test.bam.bai
touch test.bam.bai
echo "Calling variants from test.bam with test.bam.bai to test.vcf"
Calling variants from test.bam with test.bam.bai to test.vcf
touch test.vcf
###Markdown
In this example, SoS first look for a step that can produce `test.vcf` and found the `call` step through pattern `{filename}.vcf`. It turns out that this step requires an existing input file `test.bam` but a missing dependent file `test.bam.bai`, so it continues to check the workflow to identify step `index` that generates `test.bam.bai` from `test.bam`. With all dependencies met, as illustrated by the DAG (Direct Acyclic Graph) of this workflow, two steps, `index` and `call` are executed to produce the output `test.vcf`. As a convenience feature, any workflow step with explicit simple `output` statement can be used as an auxiliary step so that the step can be triggered from its output. Here **simple output statement** means output statements like `output: 'file.txt'` and `output: 'file1.txt', 'file2.txt'` that does not rely on external variables (e.g. not derived from `_input`) and without any option.For example, the following simple workflow can be executed with workflow name `step`,
###Code
%sandbox
%preview -n a.txt
%run step
[step]
output: 'a.txt'
sh: expand=True
echo "SOMETHING" > {_output}
###Output
_____no_output_____
###Markdown
and it can also be executed with expected target `-t a.txt`, because the `step` automatically `provides` `a.txt` because `output: 'a.txt'` is a simple output statement.
###Code
%sandbox
%preview -n a.txt
%run -t a.txt
[step]
output: 'a.txt'
sh: expand=True
echo "SOMETHING" > {_output}
###Output
_____no_output_____
###Markdown
Makefile-style workflow can be used to construct very complex workflows. Please refer to a [tutorial on auxiliary steps](../tutorials/Auxiliary_Steps.ipynb) for details. Mixed style workflows Auxiliary steps provide a mechanism to produce missing targets and can also be used in forward-time workflows. The resulting workflows have a numbered "stem" steps and an arbitrary number of auxiliary steps that provide required input and dependent files for these steps. For example, the following example demonstrates the use of a nested workflow with two forward-style workflows with assistance from two auxiliary steps.
###Code
%sandbox
%preview -n mixed.dot
%run -d mixed.dot
[align_10]
depends: 'hg19.fa'
print(step_name)
[align_20]
print(step_name)
[call_10]
depends: 'dbsnp.vcf', 'hg19.fa'
print(step_name)
[call_20]
print(step_name)
[default]
sos_run('align+call')
[refseq: provides='hg19.fa']
run:
# a real step would download a fasta file for hg19
touch hg19.fa
[dbsnp: provides='dbsnp.vcf']
run:
touch dbsnp.vcf
###Output
# a real step would download a fasta file for hg19
touch hg19.fa
align_10
align_20
touch dbsnp.vcf
call_10
call_20
###Markdown
Another type of mixed-style workflow allows a step to depend on the result of a process-oriented workflow. Using a target `sos_step()` with a workflow name so that the `sos_step` would depend on an entire process-oriented workflow, you can rewrite the last example as follows:
###Code
%preview -n mixed1.dot
%run -d mixed1.dot
[align_10]
depends: 'hg19.fa'
print(step_name)
[align_20]
print(step_name)
[call_10]
depends: 'dbsnp.vcf', 'hg19.fa'
print(step_name)
[call_20]
print(step_name)
[default]
depends: sos_step('align')
sos_run('call')
[refseq: provides='hg19.fa']
run:
# a real step would download a fasta file for hg19
touch hg19.fa
[dbsnp: provides='dbsnp.vcf']
run:
touch dbsnp.vcf
###Output
align_10
align_20
call_10
call_20
###Markdown
Makefile-style pattern-matching rules * **Difficulty level**: intermediate* **Time need to lean**: 20 minutes or less* **Key points**: * Option `provides` extends the "data-flow" style workflow that allows steps to generate different outputs. * Steps with `provides` section option has default `step_output`. `input` can be derived from pattern-matched variables. Auxiliary steps Auxiliary steps are special steps that are executed to provide [targets](sos_actions.html) that are required by others.For example, when the following step is executed with an input file `bamfile` (with extension `.bam`), it checks the existence of input file (`bamfile`), and a dependent index file (with extension `.bam.bai`).```sos[100 (call variant)]input: bamfiledepends: bamfile + '.bai'run: commands to call variants from input bam file```Because the step depends on an index file, SoS will look in the script for a step that provides such a target, which would be similar to```sos[index_bam : provides='{sample}.bam.bai']input: f"{sample}.bam"run: expand=True samtools index {_input}```Such a step is characterized by a **`provides`** option (or a step with simple `output` statement and is called an auxiliary step. In this particular case, if `bamfile="AS123.bam"`, the requested dependent file would be `AS123.bam.bai`. Through the matching mechanism of option `provides`, the `index_bam` step would be executed with variables `sample="AS123"` and `step_output="AS123.bam.bai"`. Unless option `-T` (see [tracing dependency](trace_dependency.html) for details) is specified, **SoS will not check if an depdendent target can be generated by an auxiliary step if it already exists**. In an extreme case, `sos run -t filename` will quit directly if `filename` already exists. An auxiliary step can trigger other auxiliary steps and form a DAG (Directed Acyclic Graph). Acutually, you can write workflows in a make-file style with all auxiliary steps and execute workflows defined by targets. If you are familiar with Makefile, especially [snakemake](https://bitbucket.org/johanneskoester/snakemake), it can be natural for you to implement your workflow in this style. The advantage of SoS is that **you can use either or both forward-style and makefile-style steps to define your workflow** and take advantages of both approaches. Step option `provides` An auxiliary step is defined by the `provides` option in section head, in the format of```sos[step_name : provides=target]```where `target` can be* A filename or file pattern such as `"{sample}.bam.idx"`* Other types of targets such as `executable("ms")`* A list (sequence) of one or more file patterns and targets. File Pattern A file pattern is a filename with optional patterns with variable names enbraced in `{ }`. SoS matches filenames with the patterns and, if successful, assign variables with matched parts of the names. For example,```[compress: provides = '{filename}.bam']```would be triggered with target `sample_A.bam` and `sample_B.bam`. When the step is triggered by `sample_A.bam`, it defines variable `filename` as `sample_A` and sets the output of the step as `sample_A.bam`.The following example removes all local `*.bam` and `*.bam.bi` file before it executes three workflows defined by `targets`. We use magic `%run` to execute it, which is equivalent to executing it from command line using commands such as```bash sos run myscript -t TS1.bam``` Let us create a workflow with two auxiliary steps `compress` and `index`. The `compress` step generates a `.bam` file (no input here for simplicity) and `index` step creates a `.bam.bai` file from the `.bam` file.
###Code
%save test_provides.sos -f
[compress: provides = '{filename}.bam']
print(f"> {step_name} input to {_output}")
sh: expand=True
touch {_output}
[index: provides = '{filename}.bam.bai']
input: f"{filename}.bam"
print(f"> {step_name} {_input} to {_output}")
sh: expand=True
touch {_output}
###Output
_____no_output_____
###Markdown
If we only want to generate a `bam` file (with option `-t TS1.bam`), the `compress` step is executed
###Code
!rm -f TS1.bam TS1.bam.bai
%runfile test_provides -t TS1.bam -v1
###Output
> compress input to TS1.bam
###Markdown
If we would like to generate both `.bam` and `.bam.bai` files (with option `-t TS2.bam.bai`), both steps are executed.
###Code
!rm -f TS2.bam TS2.bam.bai
%runfile test_provides -t TS2.bam.bai -v1
###Output
> compress input to TS2.bam
> index TS2.bam to TS2.bam.bai
###Markdown
As you can see from the output, when the first workflow is executed with target `TS1.bam`, step `compress` is executed to produce it. In the run, both steps are executed to generate `TS2.bam` and then `TS2.bam.bai`. Non-file targets In addition to output files, an auxiliary step can provide targets of other types. A most widely used target is `sos_variable`, which provides variables that can be accessed by later steps. For example,
###Code
%run -v1
# this step provides variable `numNotebooks`
[count: provides=sos_variable('numNotebooks')]
import glob
numNotebooks = len(glob.glob('*.ipynb'))
[default]
depends: sos_variable('numNotebooks')
print(f"There are {numNotebooks} notebooks in this directory")
###Output
There are 94 notebooks in this directory
###Markdown
However, for this particular example, it is more straightforward to return the variable with [option `shared`](shared_variables.html) as follows:
###Code
%run -v1
# this step provides variable `numNotebooks`
[count: shared='numNotebooks']
import glob
numNotebooks = len(glob.glob('*.ipynb'))
[default]
depends: sos_variable('numNotebooks')
print(f"There are {numNotebooks} notebooks in this directory")
###Output
There are 94 notebooks in this directory
###Markdown
Multiple targets You can specify multiple targets to the `provides` option. A step would be triggered if any of the targets matches. For example, the `temp` step is triggered twice in the following example, first time by target `text.bak` and the second time by target `text.tmp`.
###Code
!rm -f text.bak text.tmp
%run -v1
[temp: provides = ['{filename}.bak', '{filename}.tmp']]
print(f"Touch {_output}")
sh: expand=True
touch {_output}
[default]
depends: 'text.bak', 'text.tmp'
###Output
Touch text.tmp
Touch text.bak
###Markdown
However, depending on what the auxiliary step is designed, it might be generating multiple output at the same time and it would be wasteful to execute the step multiple times. In this case, you can define an `output` statement and let SoS know that the execution of the step generates multiple targets.
###Code
!rm -f text.bak text.tmp
%run -v1
[temp: provides = ['{filename}.bak', '{filename}.tmp']]
output: f'{filename}.bak', f'{filename}.tmp'
print(f"Touch {_output}")
sh: expand=True
touch {_output}
[default]
depends: 'text.bak', 'text.tmp'
###Output
Touch text.bak text.tmp
|
questions/7_Loops_1.ipynb | ###Markdown
HangmanThe idea is simple, the implementation is a little harder.Make a game of hangman that you and a friend can play!**New function:**input
###Code
# example of using input
name = input('Type in your name and hit enter: ')
print('Hi, ' + name + '!')
# Learn more about input
?input # this works for me in Jupyter Notebook, if it doesn't for you, try:
help(input)
###Output
Help on method raw_input in module ipykernel.kernelbase:
raw_input(prompt='') method of ipykernel.ipkernel.IPythonKernel instance
Forward raw_input to frontends
Raises
------
StdinNotImplentedError if active frontend doesn't support stdin.
|
Clinical_fingerprinting_delta_AIC_analysis.ipynb | ###Markdown
LicenseThis file is part of the project megFingerprinting. All of megFingerprinting code is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. megFingerprinting is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with megFingerprinting. If not, see https://www.gnu.org/licenses/.
###Code
import difflib
from fuzzywuzzy import fuzz
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np
from os import listdir
from os.path import isfile, join
import pandas as pd
import re
import seaborn as sns
import scipy as sp
import scipy.io as sio
from sklearn.decomposition import PCA
from sklearn.metrics import accuracy_score
from sklearn.linear_model import LinearRegression
from scipy import stats
from scipy.stats import pearsonr
sns.set(font_scale=2)
sns.set_style("whitegrid")
sns.set_palette(sns.color_palette("husl", 8))
def mean_confidence_interval(data, confidence=0.95):
a = 1.0 * np.array(data)
n = len(a)
m, se = np.mean(a), sp.stats.sem(a)
h = np.percentile(a, (1-((1-confidence)/2))*100)
l = np.percentile(a, ((1-confidence)/2)*100)
return m, l, h
###Output
_____no_output_____
###Markdown
I. Subject Identifiability: Original Feature Space vs PCA Reconstructed
###Code
# Yeo network definition
dmn=[0,4,14,15,20,21,30,31,34,38,39,40,50,51,52,53,56,57]
da=[58, 59]
fp= [5,54, 55]
limbic= [8,9,10,11,16,17,24,25,28,29,64,65]
som=[1,32,33,44,45,48,49,60,61,66,67]
va=[2,3,18,19,36,37,41,46,47,62,63]
vis=[6,7,12,13,22,23,26,27,35,42,43]
lista= [dmn,da,fp,limbic,som,va,vis]
listb= [18,2,3,12,11,11,11]
# change in AIC per Yeo network
self_id_roi = np.zeros((7,154))
accuracy_roi=np.zeros((2,7))
# Warangle data set into two big feature matrices
def prune_subject_csv(filename, ind):
'''
This function takes in the subject's csv file from MATLAB, takes out the
doubled correlations (because of symmetry) and outputs a numpy array ready to be concatenated
in the grand feature matrix
Args:
filename (string): Name of the csv matrix
Returns:
sub_feat (np.array): Subject's features
'''
#print(filename)
print(filename[19:23])
sub_feat = np.zeros([1, (n_feats)+1]) # Number of unique values in corr matrix + subject label
psd_matrix = pd.read_csv(filename, header=None)
mat=np.asmatrix(psd_matrix)
sub_feat[0, :-1]=mat[ind,0:451].flatten()
sub_feat[0, -1] = int(filename[19:23])
return sub_feat
for i in range(7):
ind=lista[i]
# Parameters
n_subs = 154 # Change here to get number of participants!
n_feats = int(listb[i]*451)
n_measurements = 2
# Get n subjects: both training and testing datasets
onlyfiles = [f for f in listdir('NEWspectraFUL/') if isfile(join('NEWspectraFUL/', f))]
sub_target = np.zeros([n_subs, (n_feats)+1])
sub_database = np.zeros([n_subs, (n_feats)+1])
iv = 0
it = 0
for iFile in sorted(onlyfiles)[0:(n_subs*2)]:
sub = 'NEWspectraFUL/' + iFile
print(sub)
if sub[33] == 'v':
sub_target[iv, :] = prune_subject_csv(sub, ind)
iv += 1
else:
sub_database[it, :] = prune_subject_csv(sub, ind)
it += 1
# Correlations can be computed as the dot product between two z-scored vectors
z_target = sp.stats.zscore(sub_target[:, :-1], axis = 1)
z_database = sp.stats.zscore(sub_database[:,:-1], axis = 1)
predictions = z_target.dot(z_database.transpose()) / (sub_database.shape[1] - 1) # target, database
target_from_database = accuracy_score(range(n_subs), predictions.argmax(axis = 1))
database_from_target = accuracy_score(range(n_subs), predictions.argmax(axis = 0))
print('When predicting the target from the database, we get a ' + str(target_from_database*100)[0:5] + '% accuracy')
print('When predicting the database from the target, we get a ' + str(database_from_target*100)[0:5] + '% accuracy')
accuracy_roi[0,i]=target_from_database*100
accuracy_roi[1,i]=database_from_target*100
# For the figure, we also get self-identifiability and reconstructed self-identifiability
self_id_roi[i,:]= np.diagonal(sp.stats.zscore(predictions, axis = 1))
print(self_id_roi)
df = pd.DataFrame(self_id_roi)
df.to_csv("AIC_network_psd_test.csv")
df = pd.DataFrame(accuracy_roi)
df.to_csv("AIC_network_psd_test_acc.csv")
# change in AIC per ROI
def prune_subject_csv(filename, roi):
'''
This function takes in the subject's csv file from MATLAB, takes out the
doubled correlations (because of symmetry) and outputs a numpy array ready to be concatenated
in the grand feature matrix
Args:
filename (string): Name of the csv matrix
Returns:
sub_feat (np.array): Subject's features
'''
#print(filename)
#print(filename[19:23])
sub_feat = np.zeros([1, (n_feats)+1]) # Number of unique values in corr matrix + subject label
psd_matrix = pd.read_csv(filename, header=None)
mat=np.asmatrix(psd_matrix)
sub_feat[0, :-1]=mat[np.arange(68) != roi,0:451].flatten()
sub_feat[0, -1] = int(filename[19:23])
return sub_feat
# Parameters
n_subs = 154 # Change here to get number of participants!
n_feats = int(67*451)
n_measurements = 2
self_id_roi = np.zeros((68,154))
accuracy_roi=np.zeros((2,68))
# Get n subjects: both training and testing datasets
for i in range(68):
onlyfiles = [f for f in listdir('NEWspectraFUL/') if isfile(join('NEWspectraFUL/', f))]
sub_target = np.zeros([n_subs, (n_feats)+1])
sub_database = np.zeros([n_subs, (n_feats)+1])
iv = 0
it = 0
for iFile in sorted(onlyfiles)[0:(n_subs*2)]:
sub = 'NEWspectraFUL/' + iFile
#print(sub)
#print(sub[33])
if sub[33] == 'v':
sub_target[iv, :] = prune_subject_csv(sub, i)
iv += 1
else:
sub_database[it, :] = prune_subject_csv(sub, i)
it += 1
# Correlations can be computed as the dot product between two z-scored vectors
z_target = sp.stats.zscore(sub_target[:, :-1], axis = 1)
z_database = sp.stats.zscore(sub_database[:,:-1], axis = 1)
predictions = z_target.dot(z_database.transpose()) / (sub_database.shape[1] - 1) # target, database
target_from_database = accuracy_score(range(n_subs), predictions.argmax(axis = 1))
database_from_target = accuracy_score(range(n_subs), predictions.argmax(axis = 0))
print('When predicting the target from the database, we get a ' + str(target_from_database*100)[0:5] + '% accuracy')
print('When predicting the database from the target, we get a ' + str(database_from_target*100)[0:5] + '% accuracy')
accuracy_roi[0,i]=target_from_database*100
accuracy_roi[1,i]=database_from_target*100
# For the figure, we also get self-identifiability and reconstructed self-identifiability
self_id_roi[i,:]= np.diagonal(sp.stats.zscore(predictions, axis = 1))
print(self_id_roi)
df = pd.DataFrame(self_id_roi)
df.to_csv("AIC_ROI_self_identification_tester.csv")
df = pd.DataFrame(accuracy_roi)
df.to_csv("AIC_ROI_accuracy_tester.csv")
###Output
_____no_output_____
###Markdown
Remove frequency analysis AIC
###Code
# Parameters
n_subs = 154 # Change here to get number of participants!
n_feats = int(68*439)
n_measurements = 2
# Warangle data set into two big feature matrices
def prune_subject_csv(filename):
'''
This function takes in the subject's csv file from MATLAB, takes out the
doubled correlations (because of symmetry) and outputs a numpy array ready to be concatenated
in the grand feature matrix
Args:
filename (string): Name of the csv matrix
Returns:
sub_feat (np.array): Subject's features
'''
#print(filename)
print(filename[19:23])
sub_feat = np.zeros([1, (n_feats)+1]) # Number of unique values in corr matrix + subject label
psd_matrix = pd.read_csv(filename, header=None)
mat=np.asmatrix(psd_matrix)
sub_feat[0, :-1]=mat[:,12:451].flatten()
sub_feat[0, -1] = int(filename[19:23])
return sub_feat
# Get n subjects: both training and testing datasets
onlyfiles = [f for f in listdir('NEWspectraFUL/') if isfile(join('NEWspectraFUL/', f))]
sub_target = np.zeros([n_subs, (n_feats)+1])
sub_database = np.zeros([n_subs, (n_feats)+1])
iv = 0
it = 0
for iFile in sorted(onlyfiles)[0:(n_subs*2)]:
sub = 'NEWspectraFUL/' + iFile
print(sub)
print(sub[33])
if sub[33] == 'v':
sub_target[iv, :] = prune_subject_csv(sub)
iv += 1
else:
sub_database[it, :] = prune_subject_csv(sub)
it += 1
# Correlations can be computed as the dot product between two z-scored vectors
z_target = sp.stats.zscore(sub_target[:, :-1], axis = 1)
z_database = sp.stats.zscore(sub_database[:,:-1], axis = 1)
predictions = z_target.dot(z_database.transpose()) / (sub_database.shape[1] - 1) # target, database
target_from_database = accuracy_score(range(n_subs), predictions.argmax(axis = 1))
database_from_target = accuracy_score(range(n_subs), predictions.argmax(axis = 0))
print('When predicting the target from the database, we get a ' + str(target_from_database*100)[0:5] + '% accuracy')
print('When predicting the database from the target, we get a ' + str(database_from_target*100)[0:5] + '% accuracy')
self_id= np.diagonal(sp.stats.zscore(predictions, axis = 1))
print(self_id)
# First we get subject number
def subs_list(sub):
if sub < 10:
return 'sub-000' + sub.astype(int).astype(str)
elif sub >= 10 and sub < 100:
return 'sub-00' + sub.astype(int).astype(str)
else:
return 'sub-0' + sub.astype(int).astype(str)
# Get subject data fromCA (Raw)
subs_analyzed = list(map(subs_list, sub_target[:, -1]))
subs_omega = pd.read_csv('dependency/QPN_demo_data.csv', sep=',', header=0)
# Wrangle data to get subjecs' age
sub_moca = list(subs_omega['MoCA (Raw)'].values)
for x in range(len(sub_moca)):
if isinstance(sub_moca[x], str):
sub_moca[x] = sub_moca[x][3:5]
if (sub_moca[x]==""):
sub_moca[x] = np.nan
subs_omega['X.session.moca.'] = sub_moca
subs_omega = subs_omega.rename(columns={'X.session.moca.': 'moca'})
sub_UPDRS = list(subs_omega['UPDRS Score'].values)
for x in range(len(sub_UPDRS)):
if isinstance(sub_UPDRS[x], str):
sub_UPDRS[x] = sub_UPDRS[x][3:5]
if (sub_UPDRS[x]==""):
sub_UPDRS[x] = np.nan
subs_omega['X.session.UPDRS.'] = sub_UPDRS
subs_omega = subs_omega.rename(columns={'X.session.UPDRS.': 'UPDRS'})
subs_omega['self_id_remove_delta'] = self_id
print(self_id)
# Parameters
n_subs = 154 # Change here to get number of participants!
n_feats = int(68*439)
n_measurements = 2
# Warangle data set into two big feature matrices
def prune_subject_csv(filename):
'''
This function takes in the subject's csv file from MATLAB, takes out the
doubled correlations (because of symmetry) and outputs a numpy array ready to be concatenated
in the grand feature matrix
Args:
filename (string): Name of the csv matrix
Returns:
sub_feat (np.array): Subject's features
'''
#print(filename)
print(filename[19:23])
sub_feat = np.zeros([1, (n_feats)+1]) # Number of unique values in corr matrix + subject label
psd_matrix = pd.read_csv(filename, header=None)
mat=np.asmatrix(psd_matrix)
sub_feat[0, :-1]=mat[:,np.append(np.arange(0,12),np.arange(24,451))].flatten()
sub_feat[0, -1] = int(filename[19:23])
return sub_feat
# Get n subjects: both training and testing datasets
onlyfiles = [f for f in listdir('NEWspectraFUL/') if isfile(join('NEWspectraFUL/', f))]
sub_target = np.zeros([n_subs, (n_feats)+1])
sub_database = np.zeros([n_subs, (n_feats)+1])
iv = 0
it = 0
for iFile in sorted(onlyfiles)[0:(n_subs*2)]:
sub = 'NEWspectraFUL/' + iFile
print(sub)
print(sub[33])
if sub[33] == 'v':
sub_target[iv, :] = prune_subject_csv(sub)
iv += 1
else:
sub_database[it, :] = prune_subject_csv(sub)
it += 1
# Correlations can be computed as the dot product between two z-scored vectors
z_target = sp.stats.zscore(sub_target[:, :-1], axis = 1)
z_database = sp.stats.zscore(sub_database[:,:-1], axis = 1)
predictions = z_target.dot(z_database.transpose()) / (sub_database.shape[1] - 1) # target, database
target_from_database = accuracy_score(range(n_subs), predictions.argmax(axis = 1))
database_from_target = accuracy_score(range(n_subs), predictions.argmax(axis = 0))
print('When predicting the target from the database, we get a ' + str(target_from_database*100)[0:5] + '% accuracy')
print('When predicting the database from the target, we get a ' + str(database_from_target*100)[0:5] + '% accuracy')
self_id= np.diagonal(sp.stats.zscore(predictions, axis = 1))
subs_omega['self_id_remove_theta'] = self_id
# Parameters
n_subs = 154 # Change here to get number of participants!
n_feats = int(68*436)
n_measurements = 2
# Warangle data set into two big feature matrices
def prune_subject_csv(filename):
'''
This function takes in the subject's csv file from MATLAB, takes out the
doubled correlations (because of symmetry) and outputs a numpy array ready to be concatenated
in the grand feature matrix
Args:
filename (string): Name of the csv matrix
Returns:
sub_feat (np.array): Subject's features
'''
#print(filename)
print(filename[19:23])
sub_feat = np.zeros([1, (n_feats)+1]) # Number of unique values in corr matrix + subject label
psd_matrix = pd.read_csv(filename, header=None)
mat=np.asmatrix(psd_matrix)
sub_feat[0, :-1]=mat[:,np.append(np.arange(0,24),np.arange(39,451))].flatten()
sub_feat[0, -1] = int(filename[19:23])
return sub_feat
# Get n subjects: both training and testing datasets
onlyfiles = [f for f in listdir('NEWspectraFUL/') if isfile(join('NEWspectraFUL/', f))]
sub_target = np.zeros([n_subs, (n_feats)+1])
sub_database = np.zeros([n_subs, (n_feats)+1])
iv = 0
it = 0
for iFile in sorted(onlyfiles)[0:(n_subs*2)]:
sub = 'NEWspectraFUL/' + iFile
print(sub)
print(sub[33])
if sub[33] == 'v':
sub_target[iv, :] = prune_subject_csv(sub)
iv += 1
else:
sub_database[it, :] = prune_subject_csv(sub)
it += 1
# Correlations can be computed as the dot product between two z-scored vectors
z_target = sp.stats.zscore(sub_target[:, :-1], axis = 1)
z_database = sp.stats.zscore(sub_database[:,:-1], axis = 1)
predictions = z_target.dot(z_database.transpose()) / (sub_database.shape[1] - 1) # target, database
target_from_database = accuracy_score(range(n_subs), predictions.argmax(axis = 1))
database_from_target = accuracy_score(range(n_subs), predictions.argmax(axis = 0))
print('When predicting the target from the database, we get a ' + str(target_from_database*100)[0:5] + '% accuracy')
print('When predicting the database from the target, we get a ' + str(database_from_target*100)[0:5] + '% accuracy')
self_id= np.diagonal(sp.stats.zscore(predictions, axis = 1))
subs_omega['self_id_remove_alpha'] = self_id
# Parameters
n_subs = 154 # Change here to get number of participants!
n_feats = int(68*400)
n_measurements = 2
# Warangle data set into two big feature matrices
def prune_subject_csv(filename):
'''
This function takes in the subject's csv file from MATLAB, takes out the
doubled correlations (because of symmetry) and outputs a numpy array ready to be concatenated
in the grand feature matrix
Args:
filename (string): Name of the csv matrix
Returns:
sub_feat (np.array): Subject's features
'''
#print(filename)
print(filename[19:23])
sub_feat = np.zeros([1, (n_feats)+1]) # Number of unique values in corr matrix + subject label
psd_matrix = pd.read_csv(filename, header=None)
mat=np.asmatrix(psd_matrix)
sub_feat[0, :-1]=mat[:,np.append(np.arange(0,39),np.arange(90,451))].flatten()
sub_feat[0, -1] = int(filename[19:23])
return sub_feat
# Get n subjects: both training and testing datasets
onlyfiles = [f for f in listdir('NEWspectraFUL/') if isfile(join('NEWspectraFUL/', f))]
sub_target = np.zeros([n_subs, (n_feats)+1])
sub_database = np.zeros([n_subs, (n_feats)+1])
iv = 0
it = 0
for iFile in sorted(onlyfiles)[0:(n_subs*2)]:
sub = 'NEWspectraFUL/' + iFile
print(sub)
print(sub[33])
if sub[33] == 'v':
sub_target[iv, :] = prune_subject_csv(sub)
iv += 1
else:
sub_database[it, :] = prune_subject_csv(sub)
it += 1
# Correlations can be computed as the dot product between two z-scored vectors
z_target = sp.stats.zscore(sub_target[:, :-1], axis = 1)
z_database = sp.stats.zscore(sub_database[:,:-1], axis = 1)
predictions = z_target.dot(z_database.transpose()) / (sub_database.shape[1] - 1) # target, database
target_from_database = accuracy_score(range(n_subs), predictions.argmax(axis = 1))
database_from_target = accuracy_score(range(n_subs), predictions.argmax(axis = 0))
print('When predicting the target from the database, we get a ' + str(target_from_database*100)[0:5] + '% accuracy')
print('When predicting the database from the target, we get a ' + str(database_from_target*100)[0:5] + '% accuracy')
self_id= np.diagonal(sp.stats.zscore(predictions, axis = 1))
subs_omega['self_id_remove_beta'] = self_id
# Parameters
n_subs = 154 # Change here to get number of participants!
n_feats = int(68*391)
n_measurements = 2
# Warangle data set into two big feature matrices
def prune_subject_csv(filename):
'''
This function takes in the subject's csv file from MATLAB, takes out the
doubled correlations (because of symmetry) and outputs a numpy array ready to be concatenated
in the grand feature matrix
Args:
filename (string): Name of the csv matrix
Returns:
sub_feat (np.array): Subject's features
'''
#print(filename)
print(filename[19:23])
sub_feat = np.zeros([1, (n_feats)+1]) # Number of unique values in corr matrix + subject label
psd_matrix = pd.read_csv(filename, header=None)
mat=np.asmatrix(psd_matrix)
sub_feat[0, :-1]=mat[:,np.append(np.arange(0,90),np.arange(150,451))].flatten()
sub_feat[0, -1] = int(filename[19:23])
return sub_feat
# Get n subjects: both training and testing datasets
onlyfiles = [f for f in listdir('NEWspectraFUL/') if isfile(join('NEWspectraFUL/', f))]
sub_target = np.zeros([n_subs, (n_feats)+1])
sub_database = np.zeros([n_subs, (n_feats)+1])
iv = 0
it = 0
for iFile in sorted(onlyfiles)[0:(n_subs*2)]:
sub = 'NEWspectraFUL/' + iFile
print(sub)
print(sub[33])
if sub[33] == 'v':
sub_target[iv, :] = prune_subject_csv(sub)
iv += 1
else:
sub_database[it, :] = prune_subject_csv(sub)
it += 1
# Correlations can be computed as the dot product between two z-scored vectors
z_target = sp.stats.zscore(sub_target[:, :-1], axis = 1)
z_database = sp.stats.zscore(sub_database[:,:-1], axis = 1)
predictions = z_target.dot(z_database.transpose()) / (sub_database.shape[1] - 1) # target, database
target_from_database = accuracy_score(range(n_subs), predictions.argmax(axis = 1))
database_from_target = accuracy_score(range(n_subs), predictions.argmax(axis = 0))
print('When predicting the target from the database, we get a ' + str(target_from_database*100)[0:5] + '% accuracy')
print('When predicting the database from the target, we get a ' + str(database_from_target*100)[0:5] + '% accuracy')
self_id= np.diagonal(sp.stats.zscore(predictions, axis = 1))
subs_omega['self_id_remove_gamma'] = self_id
# Parameters
n_subs = 154 # Change here to get number of participants!
n_feats = int(68*150)
n_measurements = 2
# Warangle data set into two big feature matrices
def prune_subject_csv(filename):
'''
This function takes in the subject's csv file from MATLAB, takes out the
doubled correlations (because of symmetry) and outputs a numpy array ready to be concatenated
in the grand feature matrix
Args:
filename (string): Name of the csv matrix
Returns:
sub_feat (np.array): Subject's features
'''
#print(filename)
print(filename[19:23])
sub_feat = np.zeros([1, (n_feats)+1]) # Number of unique values in corr matrix + subject label
psd_matrix = pd.read_csv(filename, header=None)
mat=np.asmatrix(psd_matrix)
sub_feat[0, :-1]=mat[:,0:150].flatten()
sub_feat[0, -1] = int(filename[19:23])
return sub_feat
# Get n subjects: both training and testing datasets
onlyfiles = [f for f in listdir('NEWspectraFUL/') if isfile(join('NEWspectraFUL/', f))]
sub_target = np.zeros([n_subs, (n_feats)+1])
sub_database = np.zeros([n_subs, (n_feats)+1])
iv = 0
it = 0
for iFile in sorted(onlyfiles)[0:(n_subs*2)]:
sub = 'NEWspectraFUL/' + iFile
print(sub)
print(sub[33])
if sub[33] == 'v':
sub_target[iv, :] = prune_subject_csv(sub)
iv += 1
else:
sub_database[it, :] = prune_subject_csv(sub)
it += 1
# Correlations can be computed as the dot product between two z-scored vectors
z_target = sp.stats.zscore(sub_target[:, :-1], axis = 1)
z_database = sp.stats.zscore(sub_database[:,:-1], axis = 1)
predictions = z_target.dot(z_database.transpose()) / (sub_database.shape[1] - 1) # target, database
target_from_database = accuracy_score(range(n_subs), predictions.argmax(axis = 1))
database_from_target = accuracy_score(range(n_subs), predictions.argmax(axis = 0))
print('When predicting the target from the database, we get a ' + str(target_from_database*100)[0:5] + '% accuracy')
print('When predicting the database from the target, we get a ' + str(database_from_target*100)[0:5] + '% accuracy')
self_id= np.diagonal(sp.stats.zscore(predictions, axis = 1))
subs_omega['self_id_remove_highgamma'] = self_id
subs_omega.to_csv('QPN_demo_with_fingerprinting_score_AIC_analysis_tester.csv')
###Output
_____no_output_____ |
d2l-en/tensorflow/chapter_recurrent-neural-networks/sequence.ipynb | ###Markdown
Sequence Models:label:`sec_sequence`Imagine that you are watching movies on Netflix. As a good Netflix user, you decide to rate each of the movies religiously. After all, a good movie is a good movie, and you want to watch more of them, right? As it turns out, things are not quite so simple. People's opinions on movies can change quite significantly over time. In fact, psychologists even have names for some of the effects:* There is *anchoring*, based on someone else's opinion. For instance, after the Oscar awards, ratings for the corresponding movie go up, even though it is still the same movie. This effect persists for a few months until the award is forgotten. It has been shown that the effect lifts rating by over half a point:cite:`Wu.Ahmed.Beutel.ea.2017`.* There is the *hedonic adaptation*, where humans quickly adapt to accept an improved or a worsened situation as the new normal. For instance, after watching many good movies, the expectations that the next movie is equally good or better are high. Hence, even an average movie might be considered as bad after many great ones are watched.* There is *seasonality*. Very few viewers like to watch a Santa Claus movie in August.* In some cases, movies become unpopular due to the misbehaviors of directors or actors in the production.* Some movies become cult movies, because they were almost comically bad. *Plan 9 from Outer Space* and *Troll 2* achieved a high degree of notoriety for this reason.In short, movie ratings are anything but stationary. Thus, using temporal dynamicsled to more accurate movie recommendations :cite:`Koren.2009`.Of course, sequence data are not just about movie ratings. The following gives more illustrations.* Many users have highly particular behavior when it comes to the time when they open apps. For instance, social media apps are much more popular after school with students. Stock market trading apps are more commonly used when the markets are open.* It is much harder to predict tomorrow's stock prices than to fill in the blanks for a stock price we missed yesterday, even though both are just a matter of estimating one number. After all, foresight is so much harder than hindsight. In statistics, the former (predicting beyond the known observations) is called *extrapolation* whereas the latter (estimating between the existing observations) is called *interpolation*.* Music, speech, text, and videos are all sequential in nature. If we were to permute them they would make little sense. The headline *dog bites man* is much less surprising than *man bites dog*, even though the words are identical.* Earthquakes are strongly correlated, i.e., after a massive earthquake there are very likely several smaller aftershocks, much more so than without the strong quake. In fact, earthquakes are spatiotemporally correlated, i.e., the aftershocks typically occur within a short time span and in close proximity.* Humans interact with each other in a sequential nature, as can be seen in Twitter fights, dance patterns, and debates. Statistical ToolsWe need statistical tools and new deep neural network architectures to deal with sequence data. To keep things simple, we use the stock price (FTSE 100 index) illustrated in :numref:`fig_ftse100` as an example.:width:`400px`:label:`fig_ftse100`Let us denote the prices by $x_t$, i.e., at *time step* $t \in \mathbb{Z}^+$ we observe price $x_t$.Note that for sequences in this text,$t$ will typically be discrete and vary over integers or its subset.Suppose thata trader who wants to do well in the stock market on day $t$ predicts $x_t$ via$$x_t \sim P(x_t \mid x_{t-1}, \ldots, x_1).$$ Autoregressive ModelsIn order to achieve this, our trader could use a regression model such as the one that we trained in :numref:`sec_linear_concise`.There is just one major problem: the number of inputs, $x_{t-1}, \ldots, x_1$ varies, depending on $t$.That is to say, the number increases with the amount of data that we encounter, and we will need an approximation to make this computationally tractable.Much of what follows in this chapter will revolve around how to estimate $P(x_t \mid x_{t-1}, \ldots, x_1)$ efficiently. In a nutshell it boils down to two strategies as follows.First, assume that the potentially rather long sequence $x_{t-1}, \ldots, x_1$ is not really necessary.In this case we might content ourselves with some timespan of length $\tau$ and only use $x_{t-1}, \ldots, x_{t-\tau}$ observations. The immediate benefit is that now the number of arguments is always the same, at least for $t > \tau$. This allows us to train a deep network as indicated above. Such models will be called *autoregressive models*, as they quite literally perform regression on themselves.The second strategy, shown in :numref:`fig_sequence-model`, is to keep some summary $h_t$ of the past observations, and at the same time update $h_t$ in addition to the prediction $\hat{x}_t$.This leads to models that estimate $x_t$ with $\hat{x}_t = P(x_t \mid h_{t})$ and moreover updates of the form $h_t = g(h_{t-1}, x_{t-1})$. Since $h_t$ is never observed, these models are also called *latent autoregressive models*.:label:`fig_sequence-model`Both cases raise the obvious question of how to generate training data. One typically uses historical observations to predict the next observation given the ones up to right now. Obviously we do not expect time to stand still. However, a common assumption is that while the specific values of $x_t$ might change, at least the dynamics of the sequence itself will not. This is reasonable, since novel dynamics are just that, novel and thus not predictable using data that we have so far. Statisticians call dynamics that do not change *stationary*.Regardless of what we do, we will thus get an estimate of the entire sequence via$$P(x_1, \ldots, x_T) = \prod_{t=1}^T P(x_t \mid x_{t-1}, \ldots, x_1).$$Note that the above considerations still hold if we deal with discrete objects, such as words, rather than continuous numbers. The only difference is that in such a situation we need to use a classifier rather than a regression model to estimate $P(x_t \mid x_{t-1}, \ldots, x_1)$. Markov ModelsRecall the approximation that in an autoregressive model we use only $x_{t-1}, \ldots, x_{t-\tau}$ instead of $x_{t-1}, \ldots, x_1$ to estimate $x_t$. Whenever this approximation is accurate we say that the sequence satisfies a *Markov condition*. In particular, if $\tau = 1$, we have a *first-order Markov model* and $P(x)$ is given by$$P(x_1, \ldots, x_T) = \prod_{t=1}^T P(x_t \mid x_{t-1}) \text{ where } P(x_1 \mid x_0) = P(x_1).$$Such models are particularly nice whenever $x_t$ assumes only a discrete value, since in this case dynamic programming can be used to compute values along the chain exactly. For instance, we can compute $P(x_{t+1} \mid x_{t-1})$ efficiently:$$\begin{aligned}P(x_{t+1} \mid x_{t-1})&= \frac{\sum_{x_t} P(x_{t+1}, x_t, x_{t-1})}{P(x_{t-1})}\\&= \frac{\sum_{x_t} P(x_{t+1} \mid x_t, x_{t-1}) P(x_t, x_{t-1})}{P(x_{t-1})}\\&= \sum_{x_t} P(x_{t+1} \mid x_t) P(x_t \mid x_{t-1})\end{aligned}$$by using the fact that we only need to take into account a very short history of past observations: $P(x_{t+1} \mid x_t, x_{t-1}) = P(x_{t+1} \mid x_t)$.Going into details of dynamic programming is beyond the scope of this section. Control and reinforcement learning algorithms use such tools extensively. CausalityIn principle, there is nothing wrong with unfolding $P(x_1, \ldots, x_T)$ in reverse order. After all, by conditioning we can always write it via$$P(x_1, \ldots, x_T) = \prod_{t=T}^1 P(x_t \mid x_{t+1}, \ldots, x_T).$$In fact, if we have a Markov model, we can obtain a reverse conditional probability distribution, too. In many cases, however, there exists a natural direction for the data, namely going forward in time. It is clear that future events cannot influence the past. Hence, if we change $x_t$, we may be able to influence what happens for $x_{t+1}$ going forward but not the converse. That is, if we change $x_t$, the distribution over past events will not change. Consequently, it ought to be easier to explain $P(x_{t+1} \mid x_t)$ rather than $P(x_t \mid x_{t+1})$. For instance, it has been shown that in some cases we can find $x_{t+1} = f(x_t) + \epsilon$ for some additive noise $\epsilon$, whereas the converse is not true :cite:`Hoyer.Janzing.Mooij.ea.2009`. This is great news, since it is typically the forward direction that we are interested in estimating.The book by Peters et al. hasexplained more on this topic :cite:`Peters.Janzing.Scholkopf.2017`.We are barely scratching the surface of it. TrainingAfter reviewing so many statistical tools,let us try this out in practice.We begin by generating some data.To keep things simple we generate our sequence data by using a sine function with some additive noise for time steps $1, 2, \ldots, 1000$.
###Code
%matplotlib inline
from d2l import tensorflow as d2l
import tensorflow as tf
T = 1000 # Generate a total of 1000 points
time = tf.range(1, T + 1, dtype=tf.float32)
x = tf.sin(0.01 * time) + tf.random.normal([T], 0, 0.2)
d2l.plot(time, [x], 'time', 'x', xlim=[1, 1000], figsize=(6, 3))
###Output
_____no_output_____
###Markdown
Next, we need to turn such a sequence into features and labels that our model can train on.Based on the embedding dimension $\tau$ we map the data into pairs $y_t = x_t$ and $\mathbf{x}_t = [x_{t-\tau}, \ldots, x_{t-1}]$.The astute reader might have noticed that this gives us $\tau$ fewer data examples, since we do not have sufficient history for the first $\tau$ of them.A simple fix, in particular if the sequence is long,is to discard those few terms.Alternatively we could pad the sequence with zeros.Here we only use the first 600 feature-label pairs for training.
###Code
tau = 4
features = tf.Variable(tf.zeros((T - tau, tau)))
for i in range(tau):
features[:, i].assign(x[i: T - tau + i])
labels = tf.reshape(x[tau:], (-1, 1))
batch_size, n_train = 16, 600
# Only the first `n_train` examples are used for training
train_iter = d2l.load_array((features[:n_train], labels[:n_train]),
batch_size, is_train=True)
###Output
_____no_output_____
###Markdown
Here we keep the architecture fairly simple:just an MLP with two fully-connected layers, ReLU activation, and squared loss.
###Code
# Vanilla MLP architecture
def get_net():
net = tf.keras.Sequential([tf.keras.layers.Dense(10, activation='relu'),
tf.keras.layers.Dense(1)])
return net
# Least mean squares loss
# Note: L2 Loss = 1/2 * MSE Loss. TensorFlow has MSE Loss that is slightly
# different from MXNet's L2Loss by a factor of 2. Hence we halve the loss
# value to get L2Loss in TF
loss = tf.keras.losses.MeanSquaredError()
###Output
_____no_output_____
###Markdown
Now we are ready to train the model. The code below is essentially identical to the training loop in previous sections,such as :numref:`sec_linear_concise`.Thus, we will not delve into much detail.
###Code
def train(net, train_iter, loss, epochs, lr):
trainer = tf.keras.optimizers.Adam()
for epoch in range(epochs):
for X, y in train_iter:
with tf.GradientTape() as g:
out = net(X)
l = loss(y, out) / 2
params = net.trainable_variables
grads = g.gradient(l, params)
trainer.apply_gradients(zip(grads, params))
print(f'epoch {epoch + 1}, '
f'loss: {d2l.evaluate_loss(net, train_iter, loss):f}')
net = get_net()
train(net, train_iter, loss, 5, 0.01)
###Output
epoch 1, loss: 0.432611
###Markdown
PredictionSince the training loss is small, we would expect our model to work well. Let us see what this means in practice. The first thing to check is how well the model is able to predict what happens just in the next time step,namely the *one-step-ahead prediction*.
###Code
onestep_preds = net(features)
d2l.plot([time, time[tau:]], [x.numpy(), onestep_preds.numpy()],
'time',
'x',
legend=['data', '1-step preds'],
xlim=[1, 1000],
figsize=(6, 3))
###Output
_____no_output_____
###Markdown
The one-step-ahead predictions look nice, just as we expected.Even beyond 604 (`n_train + tau`) observations the predictions still look trustworthy.However, there is just one little problem to this:if we observe sequence data only until time step 604, we cannot hope to receive the inputs for all the future one-step-ahead predictions.Instead, we need to work our way forward one step at a time:$$\hat{x}_{605} = f(x_{601}, x_{602}, x_{603}, x_{604}), \\\hat{x}_{606} = f(x_{602}, x_{603}, x_{604}, \hat{x}_{605}), \\\hat{x}_{607} = f(x_{603}, x_{604}, \hat{x}_{605}, \hat{x}_{606}),\\\hat{x}_{608} = f(x_{604}, \hat{x}_{605}, \hat{x}_{606}, \hat{x}_{607}),\\\hat{x}_{609} = f(\hat{x}_{605}, \hat{x}_{606}, \hat{x}_{607}, \hat{x}_{608}),\\\ldots$$Generally, for an observed sequence up to $x_t$, its predicted output $\hat{x}_{t+k}$ at time step $t+k$ is called the *$k$-step-ahead prediction*. Since we have observed up to $x_{604}$, its $k$-step-ahead prediction is $\hat{x}_{604+k}$.In other words, we will have to use our own predictions to make multistep-ahead predictions.Let us see how well this goes.
###Code
multistep_preds = tf.Variable(tf.zeros(T))
multistep_preds[:n_train + tau].assign(x[:n_train + tau])
for i in range(n_train + tau, T):
multistep_preds[i].assign(tf.reshape(net(
tf.reshape(multistep_preds[i - tau: i], (1, -1))), ()))
d2l.plot([time, time[tau:], time[n_train + tau:]], [
x.numpy(),
onestep_preds.numpy(), multistep_preds[n_train + tau:].numpy()
],
'time',
'x',
legend=['data', '1-step preds', 'multistep preds'],
xlim=[1, 1000],
figsize=(6, 3))
###Output
_____no_output_____
###Markdown
As the above example shows, this is a spectacular failure. The predictions decay to a constant pretty quickly after a few prediction steps.Why did the algorithm work so poorly?This is ultimately due to the fact that the errors build up.Let us say that after step 1 we have some error $\epsilon_1 = \bar\epsilon$.Now the *input* for step 2 is perturbed by $\epsilon_1$, hence we suffer some error in the order of $\epsilon_2 = \bar\epsilon + c \epsilon_1$ for some constant $c$, and so on. The error can diverge rather rapidly from the true observations. This is a common phenomenon. For instance, weather forecasts for the next 24 hours tend to be pretty accurate but beyond that the accuracy declines rapidly. We will discuss methods for improving this throughout this chapter and beyond.Let us take a closer look at the difficulties in $k$-step-ahead predictionsby computing predictions on the entire sequence for $k = 1, 4, 16, 64$.
###Code
max_steps = 64
features = tf.Variable(tf.zeros((T - tau - max_steps + 1, tau + max_steps)))
# Column `i` (`i` < `tau`) are observations from `x` for time steps from
# `i + 1` to `i + T - tau - max_steps + 1`
for i in range(tau):
features[:, i].assign(x[i: i + T - tau - max_steps + 1].numpy())
# Column `i` (`i` >= `tau`) are the (`i - tau + 1`)-step-ahead predictions for
# time steps from `i + 1` to `i + T - tau - max_steps + 1`
for i in range(tau, tau + max_steps):
features[:, i].assign(tf.reshape(net((features[:, i - tau: i])), -1))
steps = (1, 4, 16, 64)
d2l.plot([time[tau + i - 1:T - max_steps + i] for i in steps],
[features[:, (tau + i - 1)].numpy() for i in steps],
'time',
'x',
legend=[f'{i}-step preds' for i in steps],
xlim=[5, 1000],
figsize=(6, 3))
###Output
_____no_output_____ |
primer/example7.ipynb | ###Markdown
MQL versus TF-QuerySee [tfVersusMql](tfVersusMql.ipynb) for an introduction. LoadingWe load the Text-Fabric program and the BHSA data.
###Code
%load_ext autoreload
%autoreload 2
from tf.app import use
from util import getTfVerses, getShebanqData, compareResults, MQL_RESULTS
VERSION = "2017"
# A = use('bhsa', hoist=globals(), version=VERSION)
A = use("bhsa:clone", checkout="clone", hoist=globals(), version=VERSION)
###Output
_____no_output_____
###Markdown
Example 7[Reinoud Oosting: verb שׂים ('to set/place') with double object](https://shebanq.ancient-data.org/hebrew/query?version=2017&id=4334)```[clause FOCUS [phrase function IN (PreO, PtcO) [word sp = verb AND vs = qal AND lex = "FJM[" ] ] .. [phrase function = Objc ]]OR[clause FOCUS [phrase function = Objc ] .. [phrase function IN (PreO, PtcO) [word sp = verb AND vs = qal AND lex = "FJM[" ] ]]OR[clause FOCUS [phrase typ = VP AND NOT function IN(PreO, PtcO) [word sp = verb AND vs = qal AND lex = "FJM[" ] ] .. [phrase function = Objc ] .. [phrase function = Objc ]]OR[clause FOCUS [phrase function = Objc ] .. [phrase typ = VP AND NOT function IN (PreO, PtcO) [word sp = verb AND vs = qal AND lex = "FJM[" ] ] .. [phrase function = Objc ]]OR[clause FOCUS [phrase function = Objc ] .. [phrase function = Objc ] .. [phrase typ = VP AND NOT function IN (PreO, PtcO) [word sp = verb AND vs = qal AND lex = "FJM[" ] ]]```
###Code
(verses, words) = getShebanqData(A, MQL_RESULTS, 7)
###Output
62 results in 61 verses with 348 words
###Markdown
There is no `OR` in TF-Query.Instead, we run a separate query for each alternative and combine the results.However, we can rewrite the first two alternatives into one query.Note that they both specify a clause in which 2 phrases of a certain type occur.The two alternatives specify the two different orders in which these phrases occur.In TF-query there is no implicit order between the members of a template,so we do not have to separate cases.In MQL there is the `UNORDERED GROUP` construction with the same effect, which Reinoud could have used.The same holds for alternatives 3, 4, 5, which are merely order variants of 3 phrases within a clause.In TF we have to stipulate that the two `Objc` phrases are not the same one,because in TF-Query it is not assumed that the different blocks should be matched bydifferent parts in the text.We could do that by means of the inequality operator:``` phrase function=Objc phrase function=Objc```but that will duplicate the results, because if phrase1, phrase2 is a result, then phrase2, phrase1 is also a result.So it is better to stipulate that one of them comes before the other:``` phrase function=Objc < phrase function=Objc```
###Code
query1 = """
clause
phrase function=PreO|PtcO
word sp=verb vs=qal lex=FJM[
phrase function=Objc
"""
query2 = """
clause
phrase typ=VP function#PreO|PtcO
word sp=verb vs=qal lex=FJM[
phrase function=Objc
< phrase function=Objc
"""
results1 = A.search(query1)
results2 = A.search(query2)
###Output
0.84s 21 results
1.31s 41 results
###Markdown
The number of results nicely add up to the expected 62.
###Code
(tfVerses1, tfWords1) = getTfVerses(A, results1, (0,))
(tfVerses2, tfWords2) = getTfVerses(A, results2, (0,))
###Output
21 verses
108 words
40 verses
240 words
###Markdown
We combine the verses and words and test for equality.
###Code
tfVerses = sorted(set(tfVerses1) | set(tfVerses2))
tfWords = sorted(set(tfWords1) | set(tfWords2))
compareResults(A, verses, words, tfVerses, tfWords)
###Output
VERSES EQUAL
WORDS EQUAL
###Markdown
In order to show results in the natural order, we have to merge them.
###Code
results = sorted(results1 + results2)
###Output
_____no_output_____
###Markdown
Note that the results of the first query have one member less than the results of the second query.Let's find the first result of the first query in the merged list.
###Code
for (i, r) in enumerate(results):
if len(r) == 4:
break
i + 1
A.show(results, end=3, condenseType="clause")
###Output
_____no_output_____ |
notebooks/inefficiency-analysis.ipynb | ###Markdown
Imports
###Code
#Spark Imports
import pyspark
from pyspark import SparkContext
from pyspark.sql import SparkSession
from pyspark.sql.window import Window
from pyspark.sql import functions as F
from pyspark.sql import types as T
#Python Standard Libs Imports
import json
import urllib2
import sys
from datetime import datetime
from os.path import isfile, join, splitext
from glob import glob
#Imports to enable visualizations
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
###Output
_____no_output_____
###Markdown
Functions Basic Functions
###Code
def rename_columns(df, list_of_tuples):
for (old_col, new_col) in list_of_tuples:
df = df.withColumnRenamed(old_col, new_col)
return df
def read_folders(path, sqlContext, sc, initial_date, final_date, folder_suffix):
extension = splitext(path)[1]
if extension == "":
path_pattern = path + "/*/part-*"
if "hdfs" in path:
URI = sc._gateway.jvm.java.net.URI
Path = sc._gateway.jvm.org.apache.hadoop.fs.Path
FileSystem = sc._gateway.jvm.org.apache.hadoop.fs.FileSystem
Configuration = sc._gateway.jvm.org.apache.hadoop.conf.Configuration
hdfs = "/".join(path_pattern.split("/")[:3])
dir = "/" + "/".join(path_pattern.split("/")[3:])
fs = FileSystem.get(URI(hdfs), Configuration())
status = fs.globStatus(Path(dir))
files = map(lambda file_status: str(file_status.getPath()), status)
else:
files = glob(path_pattern)
#print initial_date, final_date
#print datetime.strptime(files[0].split('/')[-2],('%Y_%m_%d' + folder_suffix))
files = filter(lambda f: initial_date <= datetime.strptime(f.split("/")[-2], ('%Y_%m_%d' + folder_suffix)) <=
final_date, files)
#print len(files)
#print files
if folder_suffix == '_od':
return reduce(lambda df1, df2: df1.unionAll(df2),
map(lambda f: read_hdfs_folder(sqlContext,f), files))
else:
return reduce(lambda df1, df2: df1.unionAll(df2),
map(lambda f: read_buste_data_v3(sqlContext,f), files))
else:
return read_file(path, sqlContext)
def read_hdfs_folder(sqlContext, folderpath):
data_frame = sqlContext.read.csv(folderpath, header=True,
inferSchema=True,nullValue="-")
return data_frame
def read_buste_data_v3(sqlContext, folderpath):
data_frame = read_hdfs_folder(sqlContext,folderpath)
data_frame = data_frame.withColumn("date", F.unix_timestamp(F.col("date"),'yyyy_MM_dd'))
return data_frame
def printdf(df,l=10):
return df.limit(l).toPandas()
def get_timestamp_in_tz(unixtime_timestamp,ts_format,tz):
return F.from_utc_timestamp(F.from_unixtime(unixtime_timestamp, ts_format),tz)
###Output
_____no_output_____
###Markdown
OTP Functions
###Code
def get_otp_itineraries(otp_url,o_lat,o_lon,d_lat,d_lon,date,time,verbose=False):
otp_http_request = 'routers/ctba/plan?fromPlace={},{}&toPlace={},{}&mode=TRANSIT,WALK&date={}&time={}'
otp_request_url = otp_url + otp_http_request.format(o_lat,o_lon,d_lat,d_lon,date,time)
if verbose:
print otp_request_url
return json.loads(urllib2.urlopen(otp_request_url).read())
def get_executed_trip_schedule(otp_url,o_lat,o_lon,d_lat,d_lon,date,time,route,start_stop_id,verbose=False):
INTERMEDIATE_OTP_DATE = datetime.strptime("2017-06-30", "%Y-%m-%d")
DEF_AGENCY_NAME = 'URBS'
DEF_AGENCY_ID = 1
router_id = ''
date_timestamp = datetime.strptime(date, "%Y-%m-%d")
if (date_timestamp <= INTERMEDIATE_OTP_DATE):
router_id = 'ctba-2017-1'
else:
router_id = 'ctba-2017-2'
otp_http_request = 'routers/{}/plan?fromPlace={},{}&toPlace={},{}&mode=TRANSIT,WALK&date={}&time={}&numItineraries=1&preferredRoutes={}_{}&startTransitStopId={}_{}&maxWalkDistance=150&maxTransfers=0'
otp_request_url = otp_url + otp_http_request.format(router_id,o_lat,o_lon,d_lat,d_lon,date,time,DEF_AGENCY_NAME,route,DEF_AGENCY_ID,start_stop_id)
if verbose:
print otp_request_url
return json.loads(urllib2.urlopen(otp_request_url).read())
def get_otp_suggested_trips(od_matrix,otp_url):
trips_otp_response = {}
counter = 0
for row in od_matrix.collect():
id=long(row['user_trip_id'])
start_time = row['o_base_datetime'].split(' ')[1]
trip_plan = get_otp_itineraries(otp_url,row['o_shape_lat'], row['o_shape_lon'], row['shapeLat'], row['shapeLon'],row['date'],start_time)
trips_otp_response[id] = trip_plan
counter+=1
return trips_otp_response
def get_otp_scheduled_trips(od_matrix,otp_url):
trips_otp_response = {}
counter = 0
for row in od_matrix.collect():
id=long(row['user_trip_id'])
start_time = row['o_base_datetime'].split(' ')[1]
trip_plan = get_executed_trip_schedule(otp_url,row['o_shape_lat'], row['o_shape_lon'], row['shapeLat'], row['shapeLon'],
row['date'],start_time,row['route'],row['o_stop_id'])
trips_otp_response[id] = trip_plan
counter+=1
return trips_otp_response
def extract_otp_trips_legs(otp_trips):
trips_legs = []
for trip in otp_trips.keys():
if 'plan' in otp_trips[trip]:
itinerary_id = 1
for itinerary in otp_trips[trip]['plan']['itineraries']:
date = otp_trips[trip]['plan']['date']/1000
leg_id = 1
for leg in itinerary['legs']:
route = leg['route'] if leg['route'] != '' else None
fromStopId = leg['from']['stopId'].split(':')[1] if leg['mode'] == 'BUS' else None
toStopId = leg['to']['stopId'].split(':')[1] if leg['mode'] == 'BUS' else None
start_time = long(leg['startTime'])/1000
end_time = long(leg['endTime'])/1000
duration = (end_time - start_time)/60
trips_legs.append((date,trip,itinerary_id,leg_id,start_time,end_time,leg['mode'],route,fromStopId,toStopId, duration))
leg_id += 1
itinerary_id += 1
return trips_legs
def prepare_otp_legs_df(otp_legs_list):
labels=['date','user_trip_id','itinerary_id','leg_id','otp_start_time','otp_end_time','mode','route','from_stop_id','to_stop_id','otp_duration_mins']
otp_legs_df = sqlContext.createDataFrame(otp_legs_list, labels) \
.withColumn('date',F.from_unixtime(F.col('date'),'yyyy-MM-dd')) \
.withColumn('otp_duration_mins',((F.col('otp_end_time') - F.col('otp_start_time'))/60)) \
.withColumn('otp_start_time',F.from_unixtime(F.col('otp_start_time'),'yyyy-MM-dd HH:mm:ss').astype('timestamp')) \
.withColumn('otp_end_time',F.from_unixtime(F.col('otp_end_time'),'yyyy-MM-dd HH:mm:ss').astype('timestamp')) \
.withColumn('route', F.col('route').astype('integer')) \
.withColumn('from_stop_id', F.col('from_stop_id').astype('integer')) \
.withColumn('to_stop_id', F.col('to_stop_id').astype('integer')) \
.orderBy(['date','user_trip_id','itinerary_id','otp_start_time'])
return otp_legs_df
###Output
_____no_output_____
###Markdown
Analysis Functions
###Code
def advance_od_matrix_start_time(od_matrix,extra_seconds):
return od_matrix.withColumn('o_datetime', F.concat(F.col('date'), F.lit(' '), F.col('o_timestamp'))) \
.withColumn('d_datetime', F.concat(F.col('date'), F.lit(' '), F.col('timestamp'))) \
.withColumn('executed_duration', (F.unix_timestamp('d_datetime') - F.unix_timestamp('o_datetime'))/60) \
.withColumn('o_base_datetime', F.from_unixtime(F.unix_timestamp(F.col('o_datetime'),'yyyy-MM-dd HH:mm:ss') - extra_seconds, 'yyyy-MM-dd HH:mm:ss')) \
def get_df_stats(df,filtered_df,df_label,filtered_df_label):
df_size = df.count()
filtered_df_size = filtered_df.count()
print "Total", df_label,":", df_size
print "Total", filtered_df_label, ":", filtered_df_size, "(", 100*(filtered_df_size/float(df_size)), "%)"
def get_filtered_df_stats(filtered_df,full_df_size,filtered_df_label,full_df_label):
filtered_df_size = filtered_df.count()
print filtered_df_label, "in Total", full_df_label, ":", filtered_df_size, "(", 100*(filtered_df_size/float(full_df_size)), "%)"
def clean_buste_data(buste_data):
return buste_data.select(["date","route","busCode","tripNum","stopPointId","timestamp"]) \
.na.drop(subset=["date","route","busCode","tripNum","stopPointId","timestamp"]) \
.dropDuplicates(['date','route','busCode','tripNum','stopPointId']) \
.withColumn('route',F.col('route').astype('float')) \
.withColumn('date',F.from_unixtime(F.col('date'),'yyyy-MM-dd')) \
.withColumn('timestamp',F.from_unixtime(F.unix_timestamp(F.concat(F.col('date'),F.lit(' '),F.col('timestamp')), 'yyyy-MM-dd HH:mm:ss')))
def find_otp_bus_legs_actual_start_time(otp_legs_df,clean_bus_trips_df):
w = Window.partitionBy(['date','user_trip_id','itinerary_id','route','from_stop_id']).orderBy(['timediff'])
return otp_legs_df \
.withColumn('stopPointId', F.col('from_stop_id')) \
.join(clean_bus_trips_df, ['date','route','stopPointId'], how='inner') \
.na.drop(subset=['timestamp']) \
.withColumn('timediff',F.abs(F.unix_timestamp(F.col('timestamp')) - F.unix_timestamp(F.col('otp_start_time')))) \
.drop('otp_duration') \
.withColumn('rn', F.row_number().over(w)) \
.where(F.col('rn') == 1) \
.select(['date','user_trip_id','itinerary_id','leg_id','route','busCode','tripNum','from_stop_id','otp_start_time','timestamp','to_stop_id','otp_end_time']) \
.withColumnRenamed('timestamp','from_timestamp')
def find_otp_bus_legs_actual_end_time(otp_legs_st,clean_bus_trips):
return otp_legs_st \
.withColumnRenamed('to_stop_id','stopPointId') \
.join(clean_bus_trips, ['date','route','busCode','tripNum','stopPointId'], how='inner') \
.na.drop(subset=['timestamp']) \
.withColumn('timediff',F.abs(F.unix_timestamp(F.col('timestamp')) - F.unix_timestamp(F.col('otp_end_time')))) \
.withColumnRenamed('timestamp', 'to_timestamp') \
.withColumnRenamed('stopPointId','to_stop_id') \
.orderBy(['date','route','stopPointId','timediff'])
def clean_otp_legs_actual_time_df(otp_legs_st_end_df):
return otp_legs_start_end \
.select(['date','user_trip_id','itinerary_id','leg_id','route','busCode','tripNum','from_stop_id','from_timestamp','to_stop_id','to_timestamp']) \
.withColumn('actual_duration_mins', (F.unix_timestamp(F.col('to_timestamp')) - F.unix_timestamp(F.col('from_timestamp')))/60) \
.orderBy(['date','user_trip_id','itinerary_id','leg_id']) \
.filter('actual_duration_mins > 0')
def combine_otp_suggestions_with_bus_legs_actual_time(otp_suggestions,bus_legs_actual_time):
return otp_legs_df \
.join(clean_otp_legs_actual_time, on=['date','user_trip_id','itinerary_id','leg_id', 'route', 'from_stop_id','to_stop_id'], how='left_outer') \
.withColumn('considered_duration_mins', F.when(F.col('mode') == F.lit('BUS'), F.col('actual_duration_mins')).otherwise(F.col('otp_duration_mins'))) \
.withColumn('considered_start_time', F.when(F.col('mode') == F.lit('BUS'), F.col('from_timestamp')).otherwise(F.col('otp_start_time')))
def select_itineraries_fully_identified(otp_itineraries_legs):
itineraries_not_fully_identified = otp_itineraries_legs \
.filter((otp_itineraries_legs.mode == 'BUS') & (otp_itineraries_legs.busCode.isNull())) \
.select(['date','user_trip_id','itinerary_id']).distinct()
itineraries_fully_identified = otp_itineraries_legs.select(['date','user_trip_id','itinerary_id']).subtract(itineraries_not_fully_identified)
return otp_itineraries_legs.join(itineraries_fully_identified, on=['date','user_trip_id','itinerary_id'], how='inner')
def rank_otp_itineraries_by_actual_duration(trips_itineraries):
itineraries_window = Window.partitionBy(['date','user_trip_id']).orderBy(['actual_duration_mins'])
return trips_itineraries.withColumn('rank', F.row_number().over(itineraries_window))
def get_trips_itineraries_pool(trips_otp_alternatives,od_mat):
return trips_otp_alternatives \
.union(od_mat \
.withColumn('itinerary_id', F.lit(0)) \
.withColumnRenamed('executed_duration','duration') \
.withColumnRenamed('o_datetime', 'alt_start_time') \
.select(['date','user_trip_id','itinerary_id','duration','alt_start_time'])) \
.orderBy(['date','user_trip_id','itinerary_id'])
def determining_trips_alternatives_feasibility(otp_itineraries_legs,od_mat):
trips_itineraries_possibilities = otp_itineraries_legs \
.groupBy(['date', 'user_trip_id', 'itinerary_id']) \
.agg(F.sum('considered_duration_mins').alias('duration'), \
F.first('considered_start_time').alias('alt_start_time')) \
.orderBy(['date','user_trip_id','itinerary_id']) \
.join(od_mat \
.withColumnRenamed('o_datetime','exec_start_time') \
.select(['date','user_trip_id','exec_start_time']),
on=['date','user_trip_id']) \
.withColumn('start_diff', (F.abs(F.unix_timestamp(F.col('exec_start_time')) - F.unix_timestamp(F.col('alt_start_time')))/60))
filtered_trips_possibilities = trips_itineraries_possibilities \
.filter(F.col('start_diff') <= 20) \
.drop('exec_start_time', 'start_diff')
return (trips_itineraries_possibilities,filtered_trips_possibilities)
def select_best_trip_itineraries(itineraries_pool):
return rank_otp_itineraries_by_actual_duration(itineraries_pool).filter('rank == 1') \
.drop('rank')
def compute_improvement_capacity(best_itineraries,od_mat):
return od_mat \
.withColumnRenamed('o_datetime','exec_start_time') \
.select(['date','user_trip_id','cardNum','birthdate','gender','exec_start_time','executed_duration']) \
.join(best_itineraries, on=['date','user_trip_id']) \
.withColumn('imp_capacity', F.col('executed_duration') - F.col('duration'))
###Output
_____no_output_____
###Markdown
Main Code Reading itinerary alternatives data
###Code
all_itineraries = read_hdfs_folder(sqlContext, '/local/tarciso/masters/data/bus_trips/test/single-day-test/2017_05_09/all_itineraries/')
printdf(all_itineraries)
all_itineraries.count()
all_itineraries.agg(F.countDistinct(all_itineraries.user_trip_id).alias('c')).collect()
###Output
_____no_output_____
###Markdown
Filtering trips for whose executed itineraries there is no schedule information
###Code
def filter_trips_alternatives(trips_alternatives):
min_trip_dur = 10
max_trip_dur = 50
max_trip_start_diff = 20
return trips_alternatives[(trips_alternatives['actual_duration_mins'] >= min_trip_dur) & (trips_alternatives['actual_duration_mins'] <= max_trip_dur)] \
.withColumn('start_diff',F.abs(F.unix_timestamp(F.col('exec_start_time')) - F.unix_timestamp(F.col('actual_start_time')))/60) \
.filter('start_diff <= 20')
def filter_trips_with_insufficient_alternatives(trips_alternatives):
num_trips_alternatives = trips_alternatives.groupby(['date','user_trip_id']).count().withColumnRenamed('count','num_alternatives')
trips_with_executed_alternative = trips_alternatives[trips_alternatives['itinerary_id'] == 0].select(['user_trip_id'])
return trips_alternatives.join(trips_with_executed_alternative, on='user_trip_id', how='inner') \
.join(num_trips_alternatives, on=['date','user_trip_id'], how='inner') \
.filter('num_alternatives > 1') \
.orderBy(['user_trip_id','itinerary_id'])
exec_itineraries_with_scheduled_info = all_itineraries[(all_itineraries['itinerary_id'] == 0) & (all_itineraries['planned_duration_mins'].isNotNull())] \
.select('user_trip_id')
printdf(exec_itineraries_with_scheduled_info)
clean_itineraries = filter_trips_with_insufficient_alternatives(filter_trips_alternatives(all_itineraries))
clean_itineraries2 = filter_trips_with_insufficient_alternatives(filter_trips_alternatives(all_itineraries.join(exec_itineraries_with_scheduled_info, on='user_trip_id', how='inner')))
printdf(clean_itineraries)
clean_itineraries.count()
clean_itineraries.agg(F.countDistinct(clean_itineraries.user_trip_id).alias('c')).collect()
###Output
_____no_output_____
###Markdown
Adding metadata for further analysis
###Code
def get_trip_len_bucket(trip_duration):
if (trip_duration < 10):
return '<10'
elif (trip_duration < 20):
return '10-20'
elif (trip_duration < 30):
return '20-30'
elif (trip_duration < 40):
return '30-40'
elif (trip_duration < 50):
return '40-50'
elif (trip_duration >= 50):
return '50+'
else:
return 'NA'
clean_itineraries = clean_itineraries.withColumn('trip_length_bucket',get_trip_len_bucket(F.col('exec_duration_mins')))
###Output
_____no_output_____
###Markdown
Compute Inefficiency Metrics 
###Code
def select_best_itineraries(trips_itineraries,metric_name):
itineraries_window = Window.partitionBy(['date','user_trip_id']).orderBy([metric_name])
return trips_itineraries.withColumn('rank', F.row_number().over(itineraries_window)) \
.filter('rank == 1') \
.drop('rank')
###Output
_____no_output_____
###Markdown
Observed Inefficiency
###Code
#Choose best itinerary for each trip by selecting the ones with lower actual duration
best_trips_itineraries = select_best_itineraries(clean_itineraries,'actual_duration_mins')
printdf(best_trips_itineraries)
trips_inefficiency = best_trips_itineraries \
.withColumn('dur_diff',(F.col('exec_duration_mins') - F.col('actual_duration_mins'))) \
.withColumn('observed_inef', F.col('dur_diff')/F.col('exec_duration_mins'))
printdf(trips_inefficiency, l=20)
sns.distplot(trips_inefficiency.toPandas().observed_inef)
sns.violinplot(trips_inefficiency.toPandas().observed_inef)
pos_trips_inefficiency = trips_inefficiency[trips_inefficiency['observed_inef'] > 0]
printdf(pos_trips_inefficiency)
###Output
_____no_output_____
###Markdown
Schedule Inefficiency
###Code
shortest_planned_itineraries = select_best_itineraries(clean_itineraries.na.drop(subset='planned_duration_mins'),'planned_duration_mins') \
.select('date','user_trip_id','planned_duration_mins','actual_duration_mins') \
.withColumnRenamed('planned_duration_mins','shortest_scheduled_planned_duration') \
.withColumnRenamed('actual_duration_mins','shortest_scheduled_observed_duration')
printdf(shortest_planned_itineraries)
rec_inef_i = best_trips_itineraries \
.withColumnRenamed('actual_duration_mins','shortest_observed_duration') \
.join(shortest_planned_itineraries, on=['date','user_trip_id'], how='inner') \
.select(['date','user_trip_id','shortest_observed_duration','shortest_scheduled_observed_duration']) \
.withColumn('rec_inef',(F.col('shortest_scheduled_observed_duration') - F.col('shortest_observed_duration'))/F.col('shortest_scheduled_observed_duration'))
printdf(rec_inef_i)
sns.distplot(rec_inef_i[rec_inef_i['rec_inef'] > 0].toPandas().rec_inef)
sns.violinplot(rec_inef_i.toPandas().rec_inef)
###Output
_____no_output_____
###Markdown
User choice plan inefficiency
###Code
best_scheduled_itineraries = select_best_itineraries(clean_itineraries2,'planned_duration_mins') \
.select(['date','user_trip_id','planned_duration_mins']) \
.withColumnRenamed('planned_duration_mins','best_planned_duration_mins')
printdf(best_scheduled_itineraries)
plan_inef = clean_itineraries2.join(best_scheduled_itineraries, on=['date','user_trip_id'], how='inner') \
.filter('itinerary_id == 0') \
.select(['date','user_trip_id','planned_duration_mins','best_planned_duration_mins']) \
.withColumn('plan_inef',(F.col('planned_duration_mins') - F.col('best_planned_duration_mins'))/(F.col('planned_duration_mins')))
printdf(plan_inef)
sns.distplot(plan_inef.toPandas().plan_inef)
###Output
_____no_output_____
###Markdown
System Schedule Deviation$$\begin{equation*} {Oe - Op}\end{equation*}$$
###Code
sched_deviation = clean_itineraries \
.filter('itinerary_id > 0') \
.withColumn('sched_dev',F.col('actual_duration_mins') - F.col('planned_duration_mins'))
printdf(sched_deviation)
sns.distplot(sched_deviation.toPandas().sched_dev)
###Output
_____no_output_____
###Markdown
User stop waiting time offset$$\begin{equation*} {start(Oe) - start(Op)}\end{equation*}$$
###Code
user_boarding_timediff = clean_itineraries \
.filter('itinerary_id > 0') \
.withColumn('boarding_timediff',(F.unix_timestamp('actual_start_time') - F.unix_timestamp('planned_start_time'))/60)
printdf(user_boarding_timediff)
sns.distplot(user_boarding_timediff.toPandas().boarding_timediff)
###Output
_____no_output_____ |
time_dependent.ipynb | ###Markdown
Loading and basic analysis of the simulation log recordsFunctionality is similar to the accompanying python [script](./src/time_dependent.py). Please feel free to adjust them to your needs.
###Code
# uncomment to plot into separate windows
#%matplotlib
from src.records import Records
from src.time_dependent import import_log_files
from src.time_dependent import plot_timedata
###Output
_____no_output_____
###Markdown
Set the directory to the log files and the min, max Monte Carlo run indexes:
###Code
path = './data/'
run_first = 28
run_last = 29
###Output
_____no_output_____
###Markdown
Import data from the files:
###Code
recs, pat = import_log_files(path, [run_first, run_last])
###Output
_____no_output_____
###Markdown
The log file is a record of time-dependent parameters. Thsese evolve in real time measured in seconds. The correct time values are ensured by application of the Gillespie algorithm.
###Code
# Acceptable units: 'd', 'hours', 'min', 's', 'secs'
Records.scale_time_to(recs, 'min')
###Output
_____no_output_____
###Markdown
Prepare some vatiables for common use:
###Code
# extract time for convenience:
t = [r.t for r in recs]
# set line lables to reflect run indexes:
labels = [f'run {i}' for i in range(len(recs))]
###Output
_____no_output_____
###Markdown
System free energy is represented by the reaction scores:
###Code
vv = [[sc['val'] for sc in r.score.values()] for r in recs]
scores_total = [[sum(u) for u in zip(*v)] for v in vv]
plot_timedata('total scores',
t, scores_total,
n=len(recs), labels=labels, figsize=(12, 6))
###Output
_____no_output_____
###Markdown
Plot evolution of the the number of nodes, by node degree (1 to 3):
###Code
Records.plot_nodes(recs, pat, figsize=(12, 6))
###Output
_____no_output_____
###Markdown
... and the number of segments, by segment type. The type is specified by degrees of the nodes:the reaction permit four segment tpes: 11, 13, 33 and 22 (the latter designetes a disconnected cycle)
###Code
Records.plot_segments_by_type(recs, pat, figsize=(12, 6))
###Output
_____no_output_____
###Markdown
Here is the total number of segments:
###Code
plot_timedata('total number of segments',
t, [r.mtn for r in recs],
n=len(recs), labels=labels, figsize=(12, 6))
###Output
_____no_output_____
###Markdown
and the number of segment clusters (disconnected graph components):
###Code
plot_timedata('number of clusters',
t, [r.cln for r in recs],
n=len(recs), labels=labels, figsize=(12, 6))
###Output
_____no_output_____ |
ai_semiconductors/notebooks/OutlierDetection/PCA_NewData.ipynb | ###Markdown
PCA using ``pyOD``- what DFT data is anomalous? Removing 10% of the data that appears anomalous based on the "target" values calculated from DFT, or the "descriptor" values.
###Code
def myPCA(dataframe, data_type, n_components=None, n_selected_components=None, contamination=0.1):
array = np.array(dataframe[data_type])
# using PCA model from pymod
# model will identify ~ 10% of data as outliers
clf = PCA(contamination=contamination, n_components=n_components, n_selected_components=n_selected_components)
# fitting the data
clf.fit(array)
# classifying the targets as either inliers(0) or outliers(1)
ypred = clf.predict(array)
# df of outliers
df_outlier = dataframe[ypred == 1]
# df without outliers
df_nooutlier = dataframe[ypred == 0]
return df_outlier, df_nooutlier
###Output
_____no_output_____
###Markdown
Using ``df`` PCA with target vals
###Code
df_pca_out_tar, df_pca_in_tar = myPCA(df, output)
###Output
_____no_output_____
###Markdown
PCA with descriptor vals
###Code
df_pca_out_des, df_pca_in_des = myPCA(df, descriptors)
###Output
_____no_output_____
###Markdown
Similar outlier rows between the PCA models
###Code
def similar_df(df1, df2):
df_comm = pd.concat([df1, df2])
df_comm = df_comm.reset_index(drop=True)
df_gpby = df_comm.groupby(list(df_comm.columns))
idx = [x[0] for x in df_gpby.groups.values() if len(x) != 1]
return df_comm.reindex(idx)
sim = similar_df(df_pca_out_tar,df_pca_out_des)
#sim
###Output
_____no_output_____
###Markdown
Differences between dataframes
###Code
def diff_df(df1, df2):
df_diff = pd.concat([df1,df2]).drop_duplicates(keep=False)
return df_diff
diff = diff_df(df_pca_out_tar,df_pca_out_des)
#diff
counter(df_pca_out_tar, 'Type')
counter(df_pca_in_tar, 'Type')
counter(df_pca_out_des, 'Type')
counter(df_pca_in_des, 'Type')
###Output
Total entries: 767
###Markdown
Using ``df_nooutliers``
###Code
dfnout_pca_out_tar, dfnout_pca_in_tar = myPCA(df_nooutliers, output)
counter(dfnout_pca_out_tar, 'Type')
dfnout_pca_out_des, dfnout_pca_in_des = myPCA(df_nooutliers, descriptors)
#dfnout_pca_in_des
#dfnout_pca_out_des
counter(dfnout_pca_out_des, 'Type')
###Output
Total entries: 77
###Markdown
------- Comparing the effect of number of components on how PCA picks outliers- the only real difference I saw was going down to 2 components
###Code
all_out, all_no = myPCA(df_nooutliers, descriptors)
twenty_out, twenty_no = myPCA(df_nooutliers, descriptors, n_components=20, n_selected_components=20)
#similar_df(all_out, twenty_out)
#diff_df(all_out, twenty_out)
###Output
_____no_output_____
###Markdown
------------------------------ Evaluating RFR on data after PCA
###Code
def RFR_abbr(df, o_start=4, o_end=10):
'''
o_start: int. column index of target value. (4 is the beginning)
o_end: int. column index of target value. (10 is the end)
'''
descriptors = df.columns[10:]
output = df.columns[o_start:o_end]
train,test = train_test_split(df,test_size=0.22, random_state=130)
clf = RandomForestRegressor(n_jobs=2, random_state=130)
frames_list = []
train_rmse_list = []
test_rmse_list = []
for o in output:
clf.fit(train[descriptors], train[o])
trainpred = clf.predict(train[descriptors])
testpred = clf.predict(test[descriptors])
train_rmse = mean_squared_error(train[o],trainpred, squared=False)
test_rmse = mean_squared_error(test[o],testpred, squared=False)
train_rmse_list.append(train_rmse)
test_rmse_list.append(test_rmse)
d = {'output': output, 'train rmse': train_rmse_list, 'test rmse': test_rmse_list}
rmse_df = pd.DataFrame(data=d)
return rmse_df
def RFR_type(df, o_start=4, o_end=10):
descriptors = df.columns[10:]
output = df.columns[o_start:o_end]
train,test = train_test_split(df,test_size=0.22, random_state=130)
clf = RandomForestRegressor(n_jobs=2, random_state=130)
train_26 = train[train['Type']=='II-VI']
train_35 = train[train['Type']=='III-V']
train_44 = train[train['Type']=='IV-IV']
test_26 = test[test['Type']=='II-VI']
test_35 = test[test['Type']=='III-V']
test_44 = test[test['Type']=='IV-IV']
traintest_list = [(train_26, test_26),(train_35, test_35),(train_44, test_44)]
tt_dict = {}
for tt in traintest_list:
key = str(tt[0].Type.unique())
train_rmse_list = []
test_rmse_list = []
for o in output:
clf.fit(train[descriptors], train[o])
trainpred = clf.predict(tt[0][descriptors])
testpred = clf.predict(tt[1][descriptors])
train_rmse = mean_squared_error(tt[0][o],trainpred, squared=False)
test_rmse = mean_squared_error(tt[1][o],testpred, squared=False)
train_rmse_list.append(train_rmse)
test_rmse_list.append(test_rmse)
#print('train', train_rmse_list)
#print('test', test_rmse_list)
d = {'output': output, 'train rmse': train_rmse_list, 'test rmse': test_rmse_list}
rmse_df = pd.DataFrame(data=d)
tt_dict[key] = (rmse_df)
return tt_dict
###Output
_____no_output_____
###Markdown
PCA target
###Code
RFR_abbr(df_pca_in_tar)
RFR_type(df_pca_in_tar)
###Output
_____no_output_____
###Markdown
PCA descriptors
###Code
RFR_abbr(df_pca_in_des)
RFR_type(df_pca_in_des)
###Output
_____no_output_____
###Markdown
df_nooutliers (formation energy values > 10 eV removed)
###Code
RFR_abbr(dfnout_pca_in_tar)
RFR_type(dfnout_pca_in_tar)
RFR_abbr(dfnout_pca_in_des)
RFR_type(dfnout_pca_in_des)
###Output
_____no_output_____ |
lab3.ipynb | ###Markdown
AI in Fact and Fiction - Summer 2021Natural Language ProceesingIn this lab, we will explore several natural lanugage processing techniques (including deep learning models) to perform some useful language tasks.* Use [Google Colab](https://colab.research.google.com/github/AIFictionFact/Summer2021/blob/master/lab3.ipynb) to run the python code, and to complete any missing lines of code.* You might find it helpful to save this notebook on your Google Drive.* Please make sure to fill the required information in the **Declaration** cell.* Once you complete the lab, please download the .ipynb file (File --> Download .ipynb).* Then, please use the following file naming convention to rename the downloaded python file lab3_YourRCS.ipynb (make sure to replace 'YourRCS' with your RCS ID, for example 'lab3_senevo.ipynb').* Submit the .ipynb file in LMS.Due Date/Time: Friday, Jul 23 1.00 PM ETEstimated Time Needed: 4 hoursTotal Tasks: 15Total Points: 50 **Declaration***Your Name* :*Your RCS ID* :*Collaborators (if any)* :*Online Resources consulted (if any):* Part 1 - Data Cleaning and Exploratory Data AnalysisData cleaning is a time consuming and unenjoyable task, yet it's a very important one. Keep in mind, "garbage in, garbage out". Feeding dirty data into a model will give us results that are meaningless.Specifically, we'll be walking through:1. **Getting the data** - in this case, we'll be scraping data from a website2. **Cleaning the data** - we will walk through popular text pre-processing techniques3. **Organizing the data** - we will organize the cleaned data into a way that is easy to input into other algorithmsThe output of this part of the lab will be clean, organized data in two standard text formats:* Corpus - a collection of text* Document-Term Matrix - word counts in matrix formatWe will try to scrape IMDB movie reviews from the IMDB website in this part. Getting the DataThis is the part where you have to do a bit of data sleuthing. I checked the IMDB Website and discovered that the movie reviews are available at https://www.imdb.com/title/[movie_id]/reviews, and that each individual review is in an HTML tag called "content."
###Code
# Web scraping, pickle imports
import requests
from bs4 import BeautifulSoup
import pickle
# Scrapes the reviews
def url_to_review(url):
'''Returns review data specifically from imdb.com.'''
page = requests.get(url).text
soup = BeautifulSoup(page, "html.parser")
reviews = []
for row in soup.find_all(class_="content"):
reviews.append(row.text)
return reviews
# Names of the movies we have seen / will see in this class
movies = ['The Day the Earth Stood Still',
'2001: A Space Odyssey',
'Short Circuit']
# Movie Review URLs on IMDB
urls = ['https://www.imdb.com/title/tt0043456/reviews',
'https://www.imdb.com/title/tt0062622/reviews',
'https://www.imdb.com/title/tt0091949/reviews']
# This may takes a few minutes to run
reviews = [url_to_review(u) for u in urls]
print(reviews)
###Output
_____no_output_____
###Markdown
A good practice is to save (pickle) the files for later use. Also, note how we are replacing the spaces with underscores in the movie name.
###Code
# # Make a new directory to hold the text files. You need to run this only once.
# !mkdir reviews
for i, movie in enumerate(movies):
movie_file_name = movie.replace(" ", "_")
with open("reviews/" + movie_file_name + ".txt", "wb") as file:
pickle.dump(reviews[i], file)
###Output
_____no_output_____
###Markdown
Now let's load the pickled files.
###Code
# Load pickled files
data = {}
for i, movie in enumerate(movies):
movie_file_name = movie.replace(" ", "_")
with open("reviews/" + movie_file_name + ".txt", "rb") as file:
data[movie] = pickle.load(file)
###Output
_____no_output_____
###Markdown
Let's double check if the data has been loaded properly.
###Code
# Double check to make sure data has been loaded properly
data.keys()
###Output
_____no_output_____
###Markdown
More checks.
###Code
data['The Day the Earth Stood Still'][:2]
###Output
_____no_output_____
###Markdown
Task 1 (5 points)Write code to append your two favorite movies to the `movies` list and the `urls` list. Retrieve the reviews into a variable called `my_reviews`, and pickle those new movie reviews. Load the pickled files, print the total number of reviews for each movie, and the last review in the dataset for each movie.
###Code
# Type code for Task 1 here.
###Output
_____no_output_____
###Markdown
Cleaning the DataWhen dealing with numerical data, data cleaning often involves removing null values and duplicate data, dealing with outliers, etc. With text data, there are some common data cleaning techniques, which are also known as text pre-processing techniques.With text data, this cleaning process can go on forever. There's always an exception to every cleaning step. So, we're going to follow the MVP (minimum viable product) approach - start simple and iterate. Here are a bunch of things you can do to clean your data. We're going to execute just the common cleaning steps here and the rest can be done at a later point to improve our results.**Common data cleaning steps on all text:*** Make text all lower case* Remove punctuation* Remove numerical values* Remove common non-sensical text (/n)* Tokenize text* Remove stop words**More data cleaning steps after tokenization:** * Stemming / lemmatization* Parts of speech tagging* Create bi-grams or tri-grams* Deal with typos* And more...
###Code
# Let's take a look at our data again
next(iter(data.keys()))
# Notice that our dictionary is currently in key: movie, value: list of text format
next(iter(data.values()))
# We are going to change this to key: movie, value: string format
def combine_text(list_of_text):
'''Takes a list of text and combines them into one large chunk of text.'''
combined_text = ' '.join(list_of_text)
return combined_text
# Combine it!
data_combined = {key: [combine_text(value)] for (key, value) in data.items()}
###Output
_____no_output_____
###Markdown
We can either keep it in dictionary format or put it into a pandas dataframe.
###Code
import pandas as pd
pd.set_option('max_colwidth',150)
data_df = pd.DataFrame.from_dict(data_combined).transpose()
data_df.columns = ['review']
data_df = data_df.sort_index()
data_df
###Output
_____no_output_____
###Markdown
Let's take a look at the reviews for "The Day the Earth Stood Still"
###Code
data_df.review.loc['The Day the Earth Stood Still']
###Output
_____no_output_____
###Markdown
Apply a first round of text cleaning techniques.
###Code
# Apply a first round of text cleaning techniques
import re
import string
def clean_text_round1(text):
'''Make text lowercase, remove text in square brackets,
remove punctuation and remove words containing numbers.'''
text = text.lower()
text = re.sub('\[.*?\]', '', text)
text = re.sub('[%s]' % re.escape(string.punctuation), '', text)
text = re.sub('\w*\d\w*', '', text)
return text
round1 = lambda x: clean_text_round1(x)
###Output
_____no_output_____
###Markdown
Let's take a look at the updated text.
###Code
data_clean = pd.DataFrame(data_df.review.apply(round1))
data_clean
###Output
_____no_output_____
###Markdown
Task 2 (5 points)Let's apply a second round of cleaning to get rid of some additional punctuation and non-sensical text that was missed the first time around. Hint: we do not want the `\n`. Similary, please check the reviews to see if there are any such characters we need to clean out. Please complete the `clean_text_round2` function.
###Code
# Apply a second round of cleaning
def clean_text_round2(text):
'''Get rid of some additional punctuation and non-sensical text that was missed the first time around.'''
# Type your code here
return text
round2 = lambda x: clean_text_round2(x)
###Output
_____no_output_____
###Markdown
Organizing The DataWe mentioned earlier that the output of this notebook will be clean, organized data in two standard text formats:* Corpus - a collection of text* Document-Term Matrix - word counts in matrix format**Corpus**We already created a corpus in an earlier step. The definition of a corpus is a collection of texts, and they are all put together neatly in a pandas dataframe here.
###Code
# Let's take a look at our dataframe
data_df
# Let's pickle it for later use
data_df.to_pickle("corpus.pkl")
###Output
_____no_output_____
###Markdown
**Document-Term Matrix**For many of the techniques we'll be doing later in this lab, the text must be tokenized, meaning broken down into smaller pieces. The most common tokenization technique is to break down text into words. We can do this using scikit-learn's CountVectorizer, where every row will represent a different document and every column will represent a different word.In addition, with CountVectorizer, we can remove stop words. Stop words are common words that add no additional meaning to text such as 'a', 'the', etc.
###Code
# We are going to create a document-term matrix using CountVectorizer,
# and exclude common English stop words
from sklearn.feature_extraction.text import CountVectorizer
cv = CountVectorizer(stop_words='english')
data_cv = cv.fit_transform(data_clean.review)
data_dtm = pd.DataFrame(data_cv.toarray(), columns=cv.get_feature_names())
data_dtm.index = data_clean.index
data_dtm
###Output
_____no_output_____
###Markdown
Let's pickle it for later use.
###Code
data_dtm.to_pickle("dtm.pkl")
###Output
_____no_output_____
###Markdown
Let's also pickle the cleaned data (before we put it in document-term matrix format) and the CountVectorizer object.
###Code
data_clean.to_pickle('data_clean.pkl')
pickle.dump(cv, open("cv.pkl", "wb"))
###Output
_____no_output_____
###Markdown
Task 3 (5 points)Play around with CountVectorizer's parameters. (Type your code in the cell below.)What is ngram_range? What is min_df? and max_df? (This is a written question, and please type your answer in the cell below the next.)
###Code
# Type your code to experiment with the CountVectorizer's parameters (2 points)
###Output
_____no_output_____
###Markdown
__What is ngram_range?__ (1 point)_Type your answer here___What is min_df?__ (1 point)_Type your answer here___What is max_df?__ (1 point)_Type your answer here_ Exploratory Data AnalysisAfter the data cleaning step where we put our data into a few standard formats, the next step is to take a look at the data and see if what we're looking at makes sense. Before applying any fancy algorithms, it's always important to explore the data first.When working with numerical data, some of the exploratory data analysis (EDA) techniques we can use include finding the average of the data set, the distribution of the data, the most common values, etc. The idea is the same when working with text data. We are going to find some more obvious patterns with EDA before identifying the hidden patterns with machines learning (ML) techniques. We are going to look at the following for each comedian:1. **Most common words** - find these and create word clouds2. **Size of vocabulary** - look number of unique words Most Common WordsRead in the document-term matrix.
###Code
data = pd.read_pickle('dtm.pkl')
data = data.transpose()
data.head()
###Output
_____no_output_____
###Markdown
Find the top 30 words in the reviews.
###Code
top_dict = {}
for c in data.columns:
top = data[c].sort_values(ascending=False).head(30)
top_dict[c]= list(zip(top.index, top.values))
top_dict
###Output
_____no_output_____
###Markdown
Print the top 15 words in each movie review.
###Code
for movie, top_words in top_dict.items():
print(movie)
print(', '.join([word for word, count in top_words[0:14]]))
print('---')
###Output
_____no_output_____
###Markdown
At this point, we could go on and create word clouds. However, by looking at these top words, you can see that some of them have very little meaning and could be added to a stop words list, so let's do just that.
###Code
# Look at the most common top words --> add them to the stop word list
from collections import Counter
# Let's first pull out the top 30 words for each comedian
words = []
for movie in data.columns:
top = [word for (word, count) in top_dict[movie]]
for t in top:
words.append(t)
words
###Output
_____no_output_____
###Markdown
Let's aggregate this list and identify the most common words along with how many times they occur.
###Code
Counter(words).most_common()
###Output
_____no_output_____
###Markdown
If all the movies have it as a top word, exclude it from the list.
###Code
add_stop_words = [word for word, count in Counter(words).most_common() if count == len(movies)]
add_stop_words
###Output
_____no_output_____
###Markdown
Let's update our document-term matrix with the new list of stop words.
###Code
from sklearn.feature_extraction import text
from sklearn.feature_extraction.text import CountVectorizer
# Read in cleaned data
data_clean = pd.read_pickle('data_clean.pkl')
# Add new stop words
stop_words = text.ENGLISH_STOP_WORDS.union(add_stop_words)
# Recreate document-term matrix
cv = CountVectorizer(stop_words=stop_words)
data_cv = cv.fit_transform(data_clean.review)
data_stop = pd.DataFrame(data_cv.toarray(), columns=cv.get_feature_names())
data_stop.index = data_clean.index
# Pickle it for later use
pickle.dump(cv, open("cv_stop.pkl", "wb"))
data_stop.to_pickle("dtm_stop.pkl")
###Output
_____no_output_____
###Markdown
Let's make some word clouds!First, install the Wordclouds, if not installed already.
###Code
#!pip install wordcloud
from wordcloud import WordCloud
import matplotlib.pyplot as plt
wc = WordCloud(stopwords=stop_words, background_color="white", colormap="Dark2",
max_font_size=150, random_state=42)
# Reset the output dimensions
plt.rcParams['figure.figsize'] = [16, 6]
# Create subplots for each movie
for index, movie in enumerate(data.columns):
wc.generate(data_clean.review[movie])
plt.subplot(3, 4, index+1)
plt.imshow(wc, interpolation="bilinear")
plt.axis("off")
plt.title(movie)
plt.show()
###Output
_____no_output_____
###Markdown
Find the number of unique words that each set of movie reviews have.
###Code
# Identify the non-zero items in the document-term matrix, meaning that the word occurs at least once
unique_list = []
for movie in data.columns:
uniques = data[movie].to_numpy().nonzero()[0].size
unique_list.append(uniques)
# Create a new dataframe that contains this unique word count
data_words = pd.DataFrame(list(zip(movies, unique_list)), columns=['movie', 'unique_words'])
data_unique_sort = data_words.sort_values(by='unique_words')
data_unique_sort
###Output
_____no_output_____
###Markdown
Let's plot our findings.
###Code
import numpy as np
y_pos = np.arange(len(data_words))
plt.subplot(1, 2, 1)
plt.barh(y_pos, data_unique_sort.unique_words, align='center')
plt.yticks(y_pos, data_unique_sort.movie)
plt.title('Number of Unique Words', fontsize=20)
###Output
_____no_output_____
###Markdown
**Analysis of Specific Movies**Since these three movies feature Robots, Fiction, and Aliens, let's see how many times those words are mentioned in these movie reviews.
###Code
Counter(words).most_common()
###Output
_____no_output_____
###Markdown
Let's isolate these words.
###Code
# Let's isolate these words
data_ff_words = data.transpose()[['robot', 'fiction', 'scifi', 'alien']]
data_ff = pd.concat([data_ff_words.robot, data_ff_words.fiction + data_ff_words.scifi, data_ff_words.alien], axis=1)
data_ff.columns = ['robot', 'fiction', 'alien']
data_ff
###Output
_____no_output_____
###Markdown
Task 5 (2 points)What are some other techniques you can use to analyze the dataset? (This is a written task). _Please type your answer here._ Part 2 - Sentiment AnalysisSo far, all of the analysis we've done has been pretty generic - looking at counts, creating scatter plots, etc. These techniques could be applied to numeric data as well.When it comes to text data, there are a few popular techniques that we'll be going through in the next few tasks, starting with sentiment analysis. A few key points to remember with sentiment analysis.**TextBlob Module:** Linguistic researchers have labeled the sentiment of words based on their domain expertise. Sentiment of words can vary based on where it is in a sentence. The TextBlob module allows us to take advantage of these labels.**Sentiment Labels:** Each word in a corpus is labeled in terms of polarity and subjectivity (there are more labels as well, but we're going to ignore them for now). A corpus' sentiment is the average of these. * **Polarity:** How positive or negative a word is. -1 is very negative. +1 is very positive. * **Subjectivity:** How subjective, or opinionated a word is. 0 is fact. +1 is very much an opinion.Let's take a look at the sentiment of the various movie reviews.We'll start by reading in the corpus, which preserves word order. Let's inspect the `corpus` real quickly.
###Code
data = pd.read_pickle('corpus.pkl')
data
###Output
_____no_output_____
###Markdown
We need to install TextBlob, if not already installed.
###Code
#!pip install textblob
###Output
_____no_output_____
###Markdown
Let's create quick lambda functions to find the polarity and subjectivity of each review.
###Code
from textblob import TextBlob
pol = lambda x: TextBlob(x).sentiment.polarity
sub = lambda x: TextBlob(x).sentiment.subjectivity
data['polarity'] = data['review'].apply(pol)
data['subjectivity'] = data['review'].apply(sub)
data
###Output
_____no_output_____
###Markdown
Let's plot the results.
###Code
plt.rcParams['figure.figsize'] = [10, 8]
for index, movie in enumerate(data.index):
x = data.polarity.loc[movie]
y = data.subjectivity.loc[movie]
plt.scatter(x, y, color='blue')
plt.text(x+.001, y+.001, movie, fontsize=10)
plt.xlim(-.01, .2)
plt.title('Sentiment Analysis', fontsize=20)
plt.xlabel('<-- Negative -------- Positive -->', fontsize=15)
plt.ylabel('<-- Facts -------- Opinions -->', fontsize=15)
plt.show()
###Output
_____no_output_____
###Markdown
Task 6 (3 points)The sentiment we obtained was for the entire corpus. Please obtain the sentiment values for the first 5 reviews for each of the three movies.Please check out the TextBlob's sentiment analysis API for more information. https://textblob.readthedocs.io/en/dev/quickstart.htmlsentiment-analysis
###Code
# Type your answer here.
###Output
_____no_output_____
###Markdown
Part 3 - Topic ModelingAnother popular text analysis technique is called topic modeling. The ultimate goal of topic modeling is to find various topics that are present in your corpus. Each document in the corpus will be made up of at least one topic, if not multiple topics.We will be covering the steps on how to do **Latent Dirichlet Allocation (LDA)**, which is one of many topic modeling techniques. It was specifically designed for text data.To use a topic modeling technique, you need to provide (1) a document-term matrix and (2) the number of topics you would like the algorithm to pick up.Once the topic modeling technique is applied, your job as a human is to interpret the results and see if the mix of words in each topic make sense. If they don't make sense, you can try changing up the number of topics, the terms in the document-term matrix, model parameters, or even try a different model.First, let's read in our document-term matrix.
###Code
data = pd.read_pickle('dtm_stop.pkl')
data
###Output
_____no_output_____
###Markdown
Install the necessary modules for LDA with gensim (if not installed already).
###Code
#!pip install gensim
###Output
_____no_output_____
###Markdown
Import the necessary modules for LDA with gensim.
###Code
from gensim import matutils, models
import scipy.sparse
# import logging
# logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO)
###Output
_____no_output_____
###Markdown
One of the required inputs is a term-document matrix.
###Code
tdm = data.transpose()
tdm.head()
###Output
_____no_output_____
###Markdown
We're going to put the term-document matrix into a new gensim format, from df --> sparse matrix --> gensim corpus.
###Code
sparse_counts = scipy.sparse.csr_matrix(tdm)
corpus = matutils.Sparse2Corpus(sparse_counts)
###Output
_____no_output_____
###Markdown
Gensim also requires dictionary of the all terms and their respective location in the term-document matrix.
###Code
cv = pickle.load(open("cv_stop.pkl", "rb"))
id2word = dict((v, k) for k, v in cv.vocabulary_.items())
###Output
_____no_output_____
###Markdown
Now that we have the corpus (term-document matrix) and id2word (dictionary of location: term), we need to specify two other parameters - the number of topics and the number of passes. Let's start the number of topics at 2, see if the results make sense, and increase the number from there.
###Code
lda = models.LdaModel(corpus=corpus, id2word=id2word, num_topics=2, passes=10)
lda.print_topics()
###Output
_____no_output_____
###Markdown
LDA for num_topics = 3
###Code
lda = models.LdaModel(corpus=corpus, id2word=id2word, num_topics=3, passes=10)
lda.print_topics()
###Output
_____no_output_____
###Markdown
LDA for num_topics = 4
###Code
lda = models.LdaModel(corpus=corpus, id2word=id2word, num_topics=4, passes=10)
lda.print_topics()
###Output
_____no_output_____
###Markdown
These topics aren't looking too great. We've tried modifying our parameters. Let's try modifying our terms list as well.One popular trick is to look only at terms that are from one part of speech (only nouns, only adjectives, etc.).We will need to dowload the following packages from nltk.
###Code
import nltk
nltk.download('punkt')
nltk.download('averaged_perceptron_tagger')
###Output
_____no_output_____
###Markdown
Let's create a function to pull out nouns from a string of text.
###Code
from nltk import word_tokenize, pos_tag
def nouns(text):
'''Given a string of text, tokenize the text and pull out only the nouns.'''
is_noun = lambda pos: pos[:2] == 'NN'
tokenized = word_tokenize(text)
all_nouns = [word for (word, pos) in pos_tag(tokenized) if is_noun(pos)]
return ' '.join(all_nouns)
###Output
_____no_output_____
###Markdown
Read in the cleaned data, before the CountVectorizer step.
###Code
data_clean = pd.read_pickle('data_clean.pkl')
data_clean
###Output
_____no_output_____
###Markdown
Apply the nouns function to the transcripts to filter only on nouns.
###Code
data_nouns = pd.DataFrame(data_clean.review.apply(nouns))
data_nouns
###Output
_____no_output_____
###Markdown
Create a new document-term matrix using only nouns.
###Code
# Re-add the additional stop words since we are recreating the document-term matrix
add_stop_words = ['like', 'im', 'know', 'just', 'dont', 'thats', 'right', 'people',
'youre', 'got', 'gonna', 'time', 'think', 'yeah', 'said']
stop_words = text.ENGLISH_STOP_WORDS.union(add_stop_words)
# Recreate a document-term matrix with only nouns
cvn = CountVectorizer(stop_words=stop_words)
data_cvn = cvn.fit_transform(data_nouns.review)
data_dtmn = pd.DataFrame(data_cvn.toarray(), columns=cvn.get_feature_names())
data_dtmn.index = data_nouns.index
data_dtmn
# Create the gensim corpus
corpusn = matutils.Sparse2Corpus(scipy.sparse.csr_matrix(data_dtmn.transpose()))
# Create the vocabulary dictionary
id2wordn = dict((v, k) for k, v in cvn.vocabulary_.items())
# Let's start with 2 topics
ldan = models.LdaModel(corpus=corpusn, num_topics=2, id2word=id2wordn, passes=10)
ldan.print_topics()
###Output
_____no_output_____
###Markdown
Task 7 (2 points)Write the code to print 3 topics on the document-term matrix with nouns. (1 point)What are the three topics you would determine out of the results you see. _(This is a written answer question.)_ (1 point)
###Code
# Type your code here.
###Output
_____no_output_____
###Markdown
_Type your 3 chosen topics (1 point)_ Task 8 (5 points)Complete the function to pull out both nouns and adjectives from a string of text. Adjectives are marked as 'JJ' in nltk. (2 points)Apply the `nouns_adj` function to the reviews and determine the 3 best topics. (1 point)What are the 3 best topics? How do they compare to the previous topics you selected? (2 points)
###Code
def nouns_adj(text):
# Type your code to complete the function.
return #fix me
corpusna = "" #fix me
# Apply the `nouns_adj` function to the reviews and determine the 3 best topics
ldana = "" # fix me
###Output
_____no_output_____
###Markdown
_Please type your answer to "What are the 3 best topics"? (1 point)_ _Please type your answer to "How do they compare to the previous topics you selected?" (1 point)_ **Identify topics in the reviews for each movie**Let's take a look at which topic each set of movie reviews contains. If you have defined `corpusna` and `ldana` correctly above, the following code should run and display the topics for each movie based on their IMDB reviews.
###Code
corpus_transformed = ldana[corpusna]
list(zip([a for [(a,b)] in corpus_transformed], data_dtmna.index))
###Output
_____no_output_____
###Markdown
Part 4 - Word VectorsNext, we turn our attention to some of the mode advanced (and recent) deep learning NLP libraries to learn aboout vector representations of language .First, we will take a look at [Spacy](https://spacy.io).Let's first install spacy (if not installed already).
###Code
!pip install -U spacy
!python -m spacy download en_core_web_md
###Output
_____no_output_____
###Markdown
spaCy can compare two objects and predict how similar they are – for example, documents, spans or single tokens.The Doc, Token and Span objects have a .similarity method that takes another object and returns a floating point number between 0 and 1, indicating how similar they are.One thing that's very important: In order to use similarity, you need a larger spaCy model that has word vectors included.For example, the medium or large English model – but not the small one. So if you want to use vectors, always go with a model that ends in "md" or "lg". You can find more details on this in the [models documentation](https://spacy.io/models).Here's an example. Let's say we want to find out whether two documents are similar.First, we load the medium English model, "en_core_web_md".We can then create two doc objects and use the first doc's similarity method to compare it to the second.Here, a fairly high similarity score of 0.86 is predicted for "I like fast food" and "I like pizza".The same works for tokens.According to the word vectors, the tokens "pizza" and "pasta" are kind of similar, and receive a high score.
###Code
import spacy
# Load the model with vectors
nlp = spacy.load("en_core_web_md")
# Compare two documents
doc1 = nlp("I like fast food")
doc2 = nlp("I like pizza")
print(doc1.similarity(doc2))
###Output
_____no_output_____
###Markdown
Task 9 (2 points)Obtain 2 movies reviews from our mini-movie review corpus and see how similar they are.
###Code
# Type your code here
###Output
_____no_output_____
###Markdown
**Word vectors in Spacy**To give you an idea of what those vectors look like, here's an example.First, we load the medium model again, which ships with word vectors.Next, we can process a text and look up a token's vector using the .vector attribute.The result is a 300-dimensional vector of the word "movie".
###Code
# Load a larger model with vectors
nlp = spacy.load("en_core_web_md")
doc = nlp("movie")
# Access the vector via the token.vector attribute
print(doc.vector)
###Output
_____no_output_____
###Markdown
Predicting similarity can be useful for many types of applications. For example, to recommend a user similar texts based on the ones they have read. It can also be helpful to flag duplicate content, like posts on an online platform.
###Code
review1 = "I love the movie"
review2 = "I hate the movie"
doc1 = nlp(review1)
doc2 = nlp(review2)
print(doc1.similarity(doc2))
###Output
_____no_output_____
###Markdown
Task 10 (2 points)The similarity of the statements "I like the movie" and "I hate the movie" received a high score in the vector space, despite being opposites. What might this be? _(This is a written answer question)._ _Type your answer here._ Part 5 - Text Classification, Generation, and Summarization In this part of the lab, we will be exploring the [HuggingFace](https:/huggingface.co/) library that implements the state of the art transformer models we discussed in class.Let's first install `transformers` if not installed already.
###Code
!pip install transformers[sentencepiece]
###Output
_____no_output_____
###Markdown
Before we move on to text generation, let's see how transformers can perform some of the tasks we already covered in this lab.Note: these transformer models are really large. For example, BERT-large has 24-layers and a total of 340M parameters! Altogether it is 1.34GB, so expect these transformer models to take a couple minutes to download to your Colab instance. (Note that this download is not using your own network bandwidth or your Google Drive space--it's between the Google instance and wherever the model is stored on the web).**Sentiment Analysis**
###Code
from transformers import pipeline
classifier = pipeline("sentiment-analysis")
reviews = [
review1,
review2,
]
review_sentiment = classifier(reviews)
result = "\n".join("{} {}".format(x, y) for x, y in zip(reviews, review_sentiment))
print(result)
###Output
_____no_output_____
###Markdown
Task 11 (2 points)Using HuggingFace's transformer library, print the sentiment scores of at least two random movie reviews from each of the movies in our small IMDB corpus. If there are `n` movies, you must print at most `2n` sentiment scores.
###Code
#Type your code here
###Output
_____no_output_____
###Markdown
**Text classification**The sentiment analysis we saw earlier can be thought of a type of a binary classification problem. However, a more challenging task is where we need to classify texts that haven’t been labelled. This is a common scenario in real-world application because annotating text is usually time-consuming and requires domain expertise. For this use case, the **zero-shot-classification** pipeline in HuggingFace is very powerful: it allows you to specify which labels to use for the classification, so you don’t have to rely on the labels of the pretrained model. You’ve already seen how the model can classify a sentence as positive or negative using those two labels — but it can also classify the text using any other set of labels you like.We will use the description of the AI in Fact and Fiction class, and along with several candidate topics, let's see what the transformer model classifies this text to be. As you can see, the category "Education" has a higher score.
###Code
course_description = '''The class will explore current AI topics through reading, writing, programming,
and exploring some of the classic fiction that has former people's (mis)perceptions
of machine intelligence. This course will give students an appreciation on how to
separate fiction from fact, and how to critically evaluate the impact current and
upcoming AI topics will have on society.'''
text_classifier = pipeline("zero-shot-classification")
text_classifier(
course_description,
candidate_labels=["education", "politics", "business"],
)
###Output
_____no_output_____
###Markdown
Task 12 (4 points)Using the entire IMDB movie review corpus, and the individual sets of movie reviews for each of the three movies we have seen / will be seeing in class, classify them according to 3 distinct topics (these topics cannot be the sentiment, i.e., positive or negative, or it cannot be "review"). (3 points)What are your observations on the topic distribution across the 3 movies based on their reviews? (1 point) _(This is a written answer question.)_
###Code
# Type your code here
###Output
_____no_output_____
###Markdown
_Type your answer here_ **Text Generation**Now let’s see how to use a pipeline to generate some text. The main idea here is that you provide a prompt and the model will auto-complete it by generating the remaining text. This is similar to the predictive text feature that is found on many phones. Text generation involves randomness, so it’s normal if you don’t get the same results when you run the code again.
###Code
generator = pipeline("text-generation")
generator("In this course, we will teach you how to")
###Output
_____no_output_____
###Markdown
**Using a specific model**The previous example used the default model for text generation, but you can also choose a particular model from the [Transformer Model Hub](https://huggingface.co/models). Go to the Model Hub and click on the corresponding tag on the left to display only the supported models a given task, i.e., text generation.Let’s try the distilgpt2 model! Here’s how to load it in the same pipeline as before:
###Code
generator = pipeline("text-generation", model="distilgpt2")
generator(
"In this course, we will teach you how to",
max_length=30,
num_return_sequences=2,
)
###Output
_____no_output_____
###Markdown
Task 13 (3 points)Generate a movie review with at most 100 words for your favorite movie. You must use another model that is not `distilgpt2` for this task. Please check the available text generation models from the [Transformer Model Hub](https://huggingface.co/models) for this purpose. (2 points)How do you compare the quality of this review to the same review that would be generated from the `distilgpt2` model? (1 point) _(This is a written answer question.)_ **Text Summarization**Summarization is the task of reducing a text into a shorter text while keeping all (or most) of the important aspects referenced in the text. Here’s an example where we attempt to shorten the course description to 50 words:
###Code
summarizer = pipeline("summarization")
summarizer(course_description, max_length=20)
###Output
_____no_output_____
###Markdown
Task 14 (2 points)Shorten the entire movie review corpus (i.e., all the reviews from all the movies) to 100 words.
###Code
# Type your code here.
###Output
_____no_output_____
###Markdown
Part 6 - Question Answering **BERT**, or **B**idirectional **E**mbedding **R**epresentations from **T**ransformers, is a new method of training language representations which obtains state-of-the-art results on a wide array of Natural Language Processing (NLP) tasks. The academic paper can be found here: https://arxiv.org/abs/1810.04805. (You do not have to read it as part of this lab, but it is a good reference if you want to understand the inner-workings of BERT.) The model we are using in this lab is a pre-trained model released by Google that ran for many, many hours on Wikipedia, and [Book Corpus](https://arxiv.org/pdf/1506.06724.pdf), a dataset containing +10,000 books of different genres. For question answering, we could get decent results using a BERT model that's already been fine-tuned on the Stanford Question Answering Dataset (SQuAD) benchmark: https://rajpurkar.github.io/SQuAD-explorer/explore/v2.0/dev/. Import all the necessary libraries.
###Code
question_answerer = pipeline("question-answering")
question_answerer(
question="What is this course about",
context=course_description
)
###Output
_____no_output_____
###Markdown
Task 15 (3 points)Let's get some answers to some questions about the movie "The Day the Earth Stood Still" based on the reviews for that movie. You must compile at least 5 questions about the movie from the review. Your code must use a specific question answer model from the [Transformer Model Hub](https://huggingface.co/models). (2 points)What is the model you selected, and why did you select it? (you may compare it with some other model and describe pros and cons of your chosen model) (1 point) _(This is a written answer question.)_
###Code
#Type your code here
###Output
_____no_output_____
###Markdown
IBM Quantum Challenge Africa: Quantum Chemistry for HIV Table of Contents| Walk-through ||:-||[Preface](preface)||[Introduction](intro)||[Step 1 : Defining the Molecular Geometry](step_1)||[Step 2 : Calculating the Qubit Hamiltonian](step_2)||[Step 2a: Constructing the Fermionic Hamiltonion](step_3)||[Step 2b: Getting Ready to Convert to a Qubit Hamiltonian](step_2b)||[Step 3 : Setting up the Variational Quantum Eigensolver (VQE)](step_3)||[Step 3a: The V in VQE (i.e. the Variational form, a Trial state)](step_3a)||[Step 3b: The Q in VQE: the Quantum environment](step_3b)||[Step 3c: Initializing VQE](step_3c)||[Step 4 : Solving for the Ground-state](step_4)||||[The HIV Challenge](challenge)||[1. Refining Step 1: Varying the Molecule](refine_step_1)||[2. Refining Step 2: Reducing the quantum workload](refine_step_2)||[3. Refining Step 4: Energy Surface](refine_step_4)||[4. Refining Step 3a](refine_step_3a)||Exercises||[Exercise 3a: Molecular Definition of Macromolecule with Blocking Approach](exercise_3a)||[Exercise 3b: Classical-Quantum Treatment Conceptual Questions (Multiple-Choice)](exercise_3b)||[Exercise 3c: Energy Landscape, To bind or not to bind?](exercise_3c)||[Exercise 3d: The effect of more repetitions](exercise_3d)||[Exercise 3e: Open-ended: Find the best hardware_inspired_trial to minimize the Energy Error for the Macromolecule](exercise_3e)||[Quantum Chemistry Resources](qresource)|Preface**HIV is a virus that has presented an immense challenge for public health, globally**. The ensuing disease dynamics touch on multiple societal dimensions including nutrition, access to health, education and research funding. To compound the difficulties, the virus mutates rapidly with different strains having different geographic footprints. In particular, the HIV-1-C and HIV-2 strains predominate mostly in Africa. Due to disparities in funding, research for treatments of the African strains lags behind other programmes. African researchers are striving to address this imbalance and should consider adding the latest technologies such as quantum computing to their toolkits.**Quantum computing promises spectacular improvements in drug-design**. In particular, in order to design new anti-retrovirals it is important to perform **chemical simulations** to confirm that the anti-retroviral binds with the virus protein. Such simulations are notoriously hard and sometimes ineffective on classical supercomputers. Quantum computers promise more accurate simulations allowing for a better drug-design workflow.In detail: anti-retrovirals are drugs that bind with and block a virus protein, called protease, that cleaves virus polyproteins into smaller proteins, ready for packaging. The protease can be thought of as a chemical scissor. The anti-retroviral can be thought of as a sticky obstacle that disrupts the ability of the scissor to cut. With the protease blocked, the virus cannot make more copies of itself.Mutations in the viral protease changes the binding propensity of a given anti-retroviral. Hence, when a mutation occurs and an anti-retroviral no longer binds well, the goal becomes to adjust the anti-retroviral molecule to again bind strongly.**The main goal of this challenge is to explore whether a toy anti-retroviral molecule binds with a toy virus protease.**Along the way, this challenge introduces **state-of-the-art hybrid classical-quantum embedded chemistry modelling** allowing the splitting of the work-load between classical approximations and more accurate quantum calculations.Finally, you need to tweak the setup of the quantum chemistry algorithm (without having to understand the nuts and bolts of quantum computing) to achieve the best performance for ideal quantum computing conditions. *A video explaining how HIV infects and how anti-retroviral treatment works*:
###Code
from IPython.display import display, YouTubeVideo
YouTubeVideo('cSNaBui2IM8')
###Output
_____no_output_____
###Markdown
Walk-through: Calculating the Ground-state Energy for the Simplest Molecule in the Universe *Import relevant packages*
###Code
from qiskit import Aer
from qiskit_nature.drivers import PySCFDriver, UnitsType, Molecule
from qiskit_nature.problems.second_quantization.electronic import ElectronicStructureProblem
from qiskit_nature.mappers.second_quantization import JordanWignerMapper, BravyiKitaevMapper
from qiskit_nature.converters.second_quantization import QubitConverter
from qiskit_nature.transformers import ActiveSpaceTransformer
from qiskit_nature.algorithms import GroundStateEigensolver, BOPESSampler
from qiskit.algorithms import NumPyMinimumEigensolver
from qiskit.utils import QuantumInstance
from qiskit_nature.circuit.library.ansatzes import UCCSD
from qiskit_nature.circuit.library.initial_states import HartreeFock
from qiskit.circuit.library import TwoLocal
from qiskit.algorithms import VQE
from qiskit.algorithms.optimizers import COBYLA
from functools import partial as apply_variation_to_atom_pair
import numpy as np
import matplotlib.pyplot as plt
###Output
/opt/conda/lib/python3.8/site-packages/pyscf/lib/misc.py:47: H5pyDeprecationWarning: Using default_file_mode other than 'r' is deprecated. Pass the mode to h5py.File() instead.
h5py.get_config().default_file_mode = 'a'
###Markdown
IntroductionIn the HIV Challenge, we are tasked with investigating whether the toy anti-retroviral molecule binds with and therefore, disrupts the toy protease molecule. Successful binding is determined by a lower total ground-state energy for the molecules when they are close together (forming a single macromolecule) compared to far apart.Total ground-state energy refers to the sum of the energies concerning the arrangement of the electrons and the nuclei. The nuclear energy is easy to calculate classically. It is the energy of the electron distribution (i.e. molecular spin-orbital occupation) that is extremely difficult and requires a quantum computer.We start with a walk-through tutorial, where we calculate the ground-state energy of a simple molecule and leave the more complicated set-up to the challenge section. The ground-state of a molecule in some configuration consists of the locations of the nuclei, together with some distribution of electrons around the nuclei. The nucleus-nucleus, nuclei-electron and electron-electron forces/energy of attraction and repulsion are captured in a matrix called the **Hamiltonian**. Since the nuclei are relatively massive compared to the electrons, they move at a slower time-scale than the electrons. This allows us to split the calculation into two parts: placing the nuclei and calculating the electron distribution, followed by moving the nuclei and recalculating the electron distribution until a minimum total energy distribution is reached: Algorithm: Find_total_ground_statePlace nuclei Repeat until grid completed or no change in total_energy: - calculate electronic ground-state - total_energy = (nuclei repulsion + electronic energy) - move nuclei (either in grid or following gradient)return total_energy In the walk-through, we simply fix the nuclei positions; however, later, in the challenge section, we allow for a varying one-dimensional intermolecular distance between the anti-retroviral and the protease molecules, which represents the anti-retroviral approaching the protease molecule in an attempt to bind. Step 1: Defining the Molecular Geometry For this walk-through, we work with the simplest non-trivial molecule possible: H$_2$, the hydrogen gas molecule.*The first thing to do is to fix the location of each nucleus. This is specified as a python list of nuclei, where each nucleus (as a list) contains a string corresponding to the atomic species and its 3D co-ordinates (as another list). We also specify the overall charge, which tells Qiskit to automatically calculate the number of needed electrons to produce that charge:*
###Code
hydrogen_molecule = Molecule(geometry=
[['H', [0., 0., 0.]],
['H', [0., 0., 0.735]]],
charge=0, multiplicity=1)
###Output
_____no_output_____
###Markdown
Step 2: Calculating the Qubit Hamiltonian Once nuclei positions are fixed (the nucleus-nucleus forces are temporarily irrelevant), the only part of the Hamiltonian that then needs to be calculated on the quantum computer is the detailed electron-electron interaction. The nuclei-electron and a rough mean field electron-electron interaction can be pre-computed as *allowed molecular orbitals* on a classical computer via the, so called, Hartree-Fock approximation. With these allowed molecular orbitals and their pre-calculated overlaps, Qiskit automatically produces an interacting electron-electron **fermionic molecular-orbital Hamiltonian** (called Second Quantization). The molecular orbital and overlap pre-calculation are provided by classical packages, e.g. PySCF, and connected to Qiskit via a so-called *driver*, in particular, we use the PySCFDriver. Step 2a: Constructing the Fermionic Hamiltonion *We specify the driver to the classical software package that is to be used to calculate the resulting orbitals of the provided molecule after taking into account the nuclei-electron and mean-field interactions. The `basis` option selects the basis set in which the molecular orbitals are to be expanded in. `sto3g` is the smallest available basis set:*
###Code
molecular_hydrogen_orbital_maker = PySCFDriver(molecule=hydrogen_molecule, unit=UnitsType.ANGSTROM, basis='sto3g')
###Output
_____no_output_____
###Markdown
*Qiskit provides a helpful Class named the ElectronicStructureProblem, which calls the driver in the right way to construct the molecular orbitals. We initialise ElectronicStructureProblem with the driver (which already has the molecular information stored in it from the previous step):*
###Code
hydrogen_fermionic_hamiltonian = ElectronicStructureProblem(molecular_hydrogen_orbital_maker)
###Output
_____no_output_____
###Markdown
*Here, we instruct the ElectronicStructureProblem object to go ahead and create the fermionic molecular-orbital Hamiltonian (which gets stored internally):*
###Code
hydrogen_fermionic_hamiltonian.second_q_ops()
print("Completed running classical package.\nFermionic molecular-orbital Hamiltonian calculated and stored internally.")
print("An example of HF info available: Orbital Energies", hydrogen_fermionic_hamiltonian._molecule_data_transformed.orbital_energies)
###Output
Completed running classical package.
Fermionic molecular-orbital Hamiltonian calculated and stored internally.
An example of HF info available: Orbital Energies [-0.58062892 0.67633625]
###Markdown
(If this step is not run explicitly, and its outputs are not used in an intermediary step, the final ground_state solving step would run it automatically.) Step 2b: Getting Ready to Convert to a Qubit Hamiltonian Above, *fermionic* is a term to describe the behaviour of electrons (having an anti-symmetric wave-function obeying the Pauli Exclusion principle). In order to use the quantum computer we need to map the electrons (which exhibit fermionic behavior) to the quantum computer's qubits (which have closely related spin behaviour: Pauli Exclusion but not necessarily anti-symmetric). This mapping is a generic process, independent of the driver above. There are multiple mapping methods available, each with pros and cons, and constitutes something to experiment with. *For now, we select the simplest qubit mapper/converter called the Jordan-Wigner Mapper:*
###Code
map_fermions_to_qubits = QubitConverter(JordanWignerMapper())
# e.g. alternative:
# map_fermions_to_qubits = QubitConverter(BravyiKitaevMapper())
###Output
_____no_output_____
###Markdown
(Note, we have just chosen the mapper above, it has not yet been applied to the fermionic Hamiltonian.) Step 3: Setting up the Variational Quantum Eigensolver (VQE)Now that we have defined the molecule and its mapping onto a quantum computer, we need to select an algorithm to solve for the ground state. There are two well-known approaches: Quantum Phase Estimation (QPE) and VQE. The first requires fault-tolerant quantum computers that have not yet been built. The second is suitable for current day, noisy **depth**-restricted quantum computers, because it is a hybrid quantum-classical method with short-depth quantum circuits. By *depth* of the circuit, it suffices to know that quantum computers can only be run for a short while, before noise completely scrambles the results.Therefore, for now, we only explore the VQE method. Furthermore, VQE offers many opportunities to tweak its configuration; thus, as an end-user you gain experience in quantum black-box tweaking. VQE is an algorithm for finding the ground-state of a molecule (or any Hamiltonian in general). It is a hybrid quantum-classical algorithm, which means that the algorithm consists of two interacting stages, a quantum stage and a classical stage. During the quantum stage, a trial molecular state is created on the quantum computer. The trial state is specified by a collection of **parameters** which are provided and adjusted by the classical stage. After the trial state is created, its energy is calculated on the quantum computer (by a few rounds of quantum-classical measurements). The result is finally available classically. At this stage, a classical optimization algorithm looks at the previous energy levels and the new energy level and decides how to adjust the trial state parameters. This process repeats until the energy essentially stops decreasing. The output of the whole algorithm is the final set of parameters that produced the winning approximation to the ground-state and its energy level. Step 3a: The V in VQE (i.e. the Variational form, a Trial state)VQE works by 'searching' for the electron orbital occupation distribution with the lowest energy, called the ground-state. The quantum computer is repeatedly used to calculate the energy of the search trial state.The trial state is specified by a collection of (randomly initialized) parameters that move the state around, in our search for the ground-state (we're minimizing the energy cost-function). The form of the 'movement' is something that can be tweaked (i.e., the definition of the structure of the *ansatz*/trial). There are two broad approaches we could follow. The first, let's call it *Chemistry-Inspired Trial-states*, is to use domain knowledge of what we expect the ground-state to look like from a chemistry point of view and build that into our trial state. The second, let's call it *Hardware-Inspired Trial-states*, is to simply try and create trial states that have as wide a reach as possible while taking into account the architecure of the available quantum computers. *Chemistry-Inspired Trial-states*Since chemistry gives us domain-specific prior information (e.g., the number of orbitals and electrons and the actual Hartree-Fock approximation), it makes sense to guide the trial state by baking this knowledge into the form of the trial. *From the HF approximation we get the number of orbitals and from that we can calculate the number of spin orbitals:*
###Code
hydrogen_molecule_info = hydrogen_fermionic_hamiltonian.molecule_data_transformed
num_hydrogen_molecular_orbitals = hydrogen_molecule_info.num_molecular_orbitals
num_hydrogen_spin_orbitals = 2 * num_hydrogen_molecular_orbitals
###Output
_____no_output_____
###Markdown
*Furthermore, we can also extract the number of electrons (spin up and spin down):*
###Code
num_hydrogen_electrons_spin_up_spin_down = (hydrogen_molecule_info.num_alpha, hydrogen_molecule_info.num_beta)
###Output
_____no_output_____
###Markdown
*With the number of spin orbitals, the number of electrons able to fill them and the mapping from fermions to qubits, we can construct an initial quantum computing state for our trial state:*
###Code
hydrogen_initial_state = HartreeFock(num_hydrogen_spin_orbitals,
num_hydrogen_electrons_spin_up_spin_down,
map_fermions_to_qubits)
###Output
_____no_output_____
###Markdown
*Finally, Qiskit provides a Class (Unitary Coupled Cluster Single and Double excitations, `UCCSD`) that takes the above information and creates a parameterised state inspired by the HF approximation, that can be iteratively adjusted in our attempt to find the ground-state:*
###Code
hydrogen_chemistry_inspired_trial = UCCSD(map_fermions_to_qubits,
num_hydrogen_electrons_spin_up_spin_down,
num_hydrogen_spin_orbitals,
initial_state=hydrogen_initial_state)
###Output
_____no_output_____
###Markdown
*Hardware-Inspired Trial-states*The problem with the above "chemistry-inspired" trial-states, is that they are quite deep, quickly using up the available depth of current-day quantum computers. A potential solution is to forgo this chemistry knowledge and try to represent arbitrary states with trial states that are easy to prepare and parametrically "move" around on current hardware. There are two quantum operations that can be used to try and reach arbitrary states: mixing (our term for *conditional sub-space rotation*) and rotating (*unconditional rotation*). Detailed knowledge of how these operations and their sub-options work are not really needed, especially because it is not immediately obvious which settings produce the best results. Mixing (also called Entanglement maps)There are a set of available mixing strategies, that you may experiment with. This is specified with two arguments, *`entanglement`* (choosing what to mix) and *`entanglement_blocks`* (choosing how to mix):Possible *`entanglement`* values: `'linear'`, `'full'`, `'circular'`, `'sca'`Possible *`entanglement_blocks`* values: `'cz'`, `'cx'`For our purposes, it is acceptable to simply choose the first option for each setting. RotationThere are a set of available *parameterized* rotation strategies. The rotation strategies are specified as a single argument, *`rotation_blocks`*, in the form of a list of any combination of the following possibilities:Possible *`rotation_blocks`*: `'ry'`, `'rx'`,`'rz'`,`'h'`, ...Typically, this is the only place that parameters are introduced in the trial state. One parameter is introduced for every rotation, corresponding to the angle of rotation around the associated axis. (Note, `'h'` does not have any parameters and so can not be selected alone.)Again, for our purposes, an acceptable choice is the first option alone in the list. *Qiskit provides a Class called `TwoLocal` for creating random trial states by local operations only. The number of **rounds** of the local operations is specified by the argument `reps`:*
###Code
hardware_inspired_trial = TwoLocal(rotation_blocks = ['ry'], entanglement_blocks = 'cz',
entanglement='linear', reps=2)
###Output
_____no_output_____
###Markdown
(Note, this trial state does not depend on the molecule.) *Just for convenience, let's choose between the two approaches by assiging the choice to a variable:*
###Code
hydrogen_trial_state = hydrogen_chemistry_inspired_trial
# OR
# hydrogen_trial_state = hardware_inspired_trial
###Output
_____no_output_____
###Markdown
Step 3b: The Q in VQE: the Quantum environment Since VQE runs on a quantum computer, it needs information about this stage. For testing purposes, this can even be a simulation, both in the form of noise-free or noisy simulations. Ultimately, we would want to run VQE an actual (albeit noisy) quantum hardware and hopefully, in the not-too-distant future, achieve results unattainable classically. For this challenge, let us pursue noise-free simulation only. Noise-Free Simulation*To set up a noise-free simulation:*
###Code
noise_free_quantum_environment = QuantumInstance(Aer.get_backend('statevector_simulator'))
###Output
_____no_output_____
###Markdown
Step 3c: Initializing VQE Qiskit Nature provides a class called VQE, that implements the VQE algorithm. *It is initialized in a generic way (without reference to the molecule or the Hamiltonian) and requires the two pieces of information from above: the trial state and the quantum environment:*
###Code
hydrogen_vqe_solver = VQE(ansatz=hydrogen_trial_state, quantum_instance=noise_free_quantum_environment)
###Output
_____no_output_____
###Markdown
(Note, the vqe solver is only tailored to hydrogen if the trial state is the hydrogen_chemistry_inspired_trial.) Step 4: Solving for the Ground-state **Qiskit Nature provides a class called GroundStateEigensolver to calculate the ground-state of a molecule.**This class first gets initialised with information that is independent of any molecule. It can then be applied to specific molecules using the same generic setup.To initialise a GroundStateEigensolver object, we need to provide the two generic algorithmic sub-components from above, the mapping method (Step 2b) and the solving method (Step 3). For testing purposes, an alternative to the VQE solver is a classical solver (see numpy_solver below).
###Code
hydrogen_ground_state = GroundStateEigensolver(map_fermions_to_qubits, hydrogen_vqe_solver)
###Output
_____no_output_____
###Markdown
We are finally ready to solve for the ground-state energy of our molecule.We apply the GroundStateEigensolver to the fermionic Hamiltonian (Step 2a) which has encoded in it the molecule (Step 1). The already specified mapper and VQE solver is then automatically applied for us to produce the ground-state (approximation).
###Code
hydrogen_ground_state_info = hydrogen_ground_state.solve(hydrogen_fermionic_hamiltonian)
print(hydrogen_ground_state_info)
###Output
=== GROUND STATE ENERGY ===
* Electronic ground state energy (Hartree): -1.857275030145
- computed part: -1.857275030145
~ Nuclear repulsion energy (Hartree): 0.719968994449
> Total ground state energy (Hartree): -1.137306035696
=== MEASURED OBSERVABLES ===
0: # Particles: 2.000 S: 0.000 S^2: 0.000 M: -0.000
=== DIPOLE MOMENTS ===
~ Nuclear dipole moment (a.u.): [0.0 0.0 1.3889487]
0:
* Electronic dipole moment (a.u.): [0.0 0.0 1.38894841]
- computed part: [0.0 0.0 1.38894841]
> Dipole moment (a.u.): [0.0 0.0 0.00000029] Total: 0.00000029
(debye): [0.0 0.0 0.00000074] Total: 0.00000074
###Markdown
As you can see, we have calculated the Ground-state energy of the electron distribution: -1.85 HartreeFrom the placement of the nuclei, we are also conveniently given the repulsion energy (a simple classical calculation).Finally, when it comes to the ground-state of the overall molecule it is the total ground state energy that we are trying to minimise.So the next step would be to move the nuclei and recalculate the **total ground state energy** in search of the stable nuclei positions. To end our discussion, let us compare the quantum-calculated energy to an accuracy-equivalent (but slower) classical calculation.
###Code
#Alternative Step 3b
numpy_solver = NumPyMinimumEigensolver()
#Alternative Step 4
ground_state_classical = GroundStateEigensolver(map_fermions_to_qubits, numpy_solver)
hydrogen_ground_state_info_classical = ground_state_classical.solve(hydrogen_fermionic_hamiltonian)
hydrogen_energy_classical = hydrogen_ground_state_info.computed_energies[0]
print("Ground-state electronic energy (via classical calculations): ", hydrogen_energy_classical, "Hartree")
###Output
Ground-state electronic energy (via classical calculations): -1.857275030145182 Hartree
###Markdown
The agreement to so many decimal places tells us that, for this particular Hamiltonian, the VQE process is accurately finding the lowest eigenvalue (and interestingly, the ansatz/trial does not fail to capture the ground-state, probably because it spans the entire Hilbert space). However, when comparing to nature or very accurate classical simulations of $H_2$, we find that the energy is only accurate to two decimal places, e.g. total energy VQE: -1.137 Hartree vs highly accurate classical simulation: -1.166 Hartree, which only agrees two decimal places. The reason for this is that in our above treatment there are sources of modelling error including: the placement of nuclei and a number of approximations that come with the Hartree-Fock expansion. For $H_2$ these can be addressed, but ultimately, in general, the more tricky of these sources can never be fully handled because finding the perfect ground-state is QMA-complete, i.e. the quantum version of NP-complete (i.e. 'unsolvable' for certain Hamiltonians). Then again, nature itself is not expected to be finding this perfect ground-state, so future experimention is needed to see how close a given quantum computing solution approximates nature's solution. Walk-through Finished *** The HIV ChallengeNow that we have completed the walk-through, we frame the challenge as the task to refine steps 1-4 while answering related questions. 1. Refining Step 1: Varying the MoleculeIn Step 1, we defined our molecule. For the challenge, we need to firstly define a new molecule, corresponding to our toy protease molecule (the *scissor*) with an approaching toy anti-retroviral (the *blocker*), forming a *macromolecule*. Secondly, we need to instruct Qiskit to vary the approach distance. Let's learn how to do the second step with the familiar hydrogen molecule. *Here is how to specify the type of molecular variation we are interested in (namely, changing the approach distance in absolute steps)*:
###Code
molecular_variation = Molecule.absolute_stretching
#Other types of molecular variation:
#molecular_variation = Molecule.relative_stretching
#molecular_variation = Molecule.absolute_bending
#molecular_variation = Molecule.relative_bending
###Output
_____no_output_____
###Markdown
*Here is how we specify which atoms the variation applies to. The numbers refer to the index of the atom in the geometric definition list. The first atom of the specified atom_pair, is moved closer to the left-alone second atom:*
###Code
specific_molecular_variation = apply_variation_to_atom_pair(molecular_variation, atom_pair=(1, 0))
###Output
_____no_output_____
###Markdown
*Finally, here is how we alter the original molecular definition that you have already seen in the walk-through:*
###Code
hydrogen_molecule_stretchable = Molecule(geometry=
[['H', [0., 0., 0.]],
['H', [0., 0., 0.735]]],
charge=0, multiplicity=1,
degrees_of_freedom=[specific_molecular_variation])
###Output
_____no_output_____
###Markdown
If we wanted to test that the variation is working, we could manually specify a given amount of variation (Qiskit calls it a *perturbation*) and then see what the new geometry is:
###Code
hydrogen_molecule_stretchable.perturbations = [0.1]
###Output
_____no_output_____
###Markdown
(If the above were not specified, a perturbation of zero would be assumed, defaulting to the original geometry.)
###Code
hydrogen_molecule_stretchable.geometry
###Output
_____no_output_____
###Markdown
Notice how only the second atom of our geometry list (index 1, specified first in the atom_pair) has moved closer to the other atom by the amount we specified. When it comes time to scanning across different approach distances this is very helpfully automated by Qiskit. Specifying the Protease+Anti-retroviral Macromolecule ProteaseA real protease molecule is made up of two polypeptide chains of around one hundred amino-acids in each chain (the two chains are folded together), with neighbouring pairs connected by the so-called *peptide-bond*.For our toy protease molecule, we have decided to take inspiration from this peptide bond since it is the basic building structure holding successive amino acids in proteins together. It is one of the most important factors in determining the chemistry of proteins, including protein folding in general and the HIV protease's cleaving ability, in particular.To simplify the calculations, let us choose to focus on the O=C-N part of molecule. We keep and also add enough hydrogen atoms to try and make the molecule as realistic as possible (indeed, HCONH$_2$, Formamide, is a stable molecule, which, incidentally, is an ionic solvent, so it does "cut" ionic bonds).Making O=C-N our toy protease molecule is an extreme simplification, but nevertheless biologically motivated.Here is our toy protease:```"O": (1.1280, 0.2091, 0.0000)"N": (-1.1878, 0.1791, 0.0000)"C": (0.0598, -0.3882, 0.0000)"H": (-1.3085, 1.1864, 0.0001)"H": (-2.0305, -0.3861, -0.0001)"H": (-0.0014, -1.4883, -0.0001)```Just for fun, you may imagine that this molecule is a pair of scissors, ready to cut the HIV master protein (Gag-Pol polyprotein), in the process of making copies of the HI virus: Anti-retroviralThe anti-retroviral is a molecule that binds with the protease to **inhibit/block the cleaving mechanism**. For this challenge, we select a single carbon atom to be our stand-in for the anti-retroviral molecule. MacromoleculeEven though the two molecules are separate in our minds, when they approach, they form a single macro-molecule, with the outer-electrons forming molecular orbitals around all the atoms.As explained in the walk-through, the quantum electronic distribution is calculated for fixed atom positions, thus we have to separately place the atoms. For the first and second task, let us fix the protease's co-ordinates and only vary the anti-retroviral's position along a straight line.We arbitrarily select a line of approach passing through a given point and approaching the nitrogen atom. This "blocking" approach tries to obstruct the scissor from cutting. If it "sticks", it's working and successfully disrupts the duplication efforts of the HIV. Exercise 3a: Molecular Definition of Macromolecule with Blocking ApproachConstruct the molecular definition and molecular variation to represent the anti-retroviral approaching the nitrogen atom, between the "blades": ``` "C": (-0.1805, 1.3955, 0.0000) ``` Write your answer code here: Create a your molecule in the cell below. Make sure to name the molecule `macromolecule`.
###Code
## Add your code here
molecular_variation = Molecule.absolute_stretching
specific_molecular_variation = apply_variation_to_atom_pair(molecular_variation, atom_pair=(6, 2))
macromolecule = Molecule(geometry=
[['O', [1.1280, 0.2091, 0.0000]],
['C', [0.0598, -0.3882, 0.0000]],
['N', [-1.1878, 0.1791, 0.0000]],
['H', [-1.3085, 1.1864, 0.0001]],
['H', [-2.0305, -0.3861, -0.0001]],
['H', [-0.0014, -1.4883, -0.0001]],
['C', [-0.1805, 1.3955, 0.0000]]],
charge=0, multiplicity=1,
degrees_of_freedom=[specific_molecular_variation])
##
###Output
_____no_output_____
###Markdown
To submit your molecule to the grader, run the cell below.
###Code
from qc_grader import grade_ex3a
grade_ex3a(molecule=macromolecule)
###Output
Submitting your answer for ex3/partA. Please wait...
Congratulations 🎉! Your answer is correct and has been submitted.
###Markdown
2. Refining Step 2: Reducing the quantum workload In Step 2, we constructed the qubit Hamiltonian. If we tried to apply Step 2 and beyond to our macromolecule above, the ground state calculation simulation would fail. The reason is because since we specified a zero charge, Qiskit knows that it must work with 30 (= 2\*6+7+8+3\*1) electrons. After second quantization, this translates into, say, 60 spin-orbitals which requires 60 qubits. 60 qubits is beyond our ability to simulate classically and while there are IBM Quantum systems with more than 60 qubits available, the noise levels are currently too high to produce accurate results when using that many qubits. Thus, for the purpose of this Challenge we need to reduce the number of qubits. Fortunately, this is well-motivated from a chemistry point of view as well: the classical Hartree-Fock approximation for core-electrons is sometimes sufficient to obtain accurate chemical results. Doubly fortunately, Qiskit has just recently been extended to seamlessly allow for users to specify that certain electrons should receive quantum-computing treatment while the remaining electrons should be classically approximated. Even as more qubits come on online, this facility may prove very useful in allowing near-term quantum computers to tackle very large molecules that would otherwise be out of reach. *Therefore, we next demonstrate how to instruct Qiskit to give a certain number of electrons quantum-computing treatment:*
###Code
macro_molecular_orbital_maker = PySCFDriver(molecule=macromolecule, unit=UnitsType.ANGSTROM, basis='sto3g')
split_into_classical_and_quantum = ActiveSpaceTransformer(num_electrons=2, num_molecular_orbitals=2)
macro_fermionic_hamiltonian = ElectronicStructureProblem(macro_molecular_orbital_maker, [split_into_classical_and_quantum])
###Output
_____no_output_____
###Markdown
Above, Qiskit provides a class called **ActiveSpaceTransformer** that takes in two arguments. The first is the number of electrons that should receive quantum-computing treatment (selected from the outermost electrons, counting inwards). The second is the number of orbitals to allow those electrons to roam over (around the so-called Fermi level). It is the second number that determines how many qubits are needed. Exercise 3b: Classical-Quantum Treatment Conceptual Questions (Multiple-Choice)Q1: Why does giving quantum treatment to outer electrons of the macromolecule first, make more heuristic sense?```A: Outer electrons have higher binding energies and therefore swing the ground state energy more, therefore requiring quantum treatment.B: Outer electrons exhibit more quantum interference because their orbitals are more spread out.C: Inner core-electrons typically occupy orbitals more straightforwardly, because they mostly orbit a single nucleus and therefore do not lower the energy much by interacting/entangling with outer electrons.```Q2: For a fixed number of quantum-treatment electrons, as you increase the number of orbitals that those electrons roam over (have access to), does the calculated ground-state energy approach the asymptotic energy from above or below?```A: The asymptotic energy is approached from above, because as you increase the possible orbitals that the electrons have access to, the lower the ground state could be.B: The asymptotic energy is approached from below, because as you increase the possible orbitals the more accurate is your simulation, adding energy that was left out before.C: The asymptotic energy is approached from below, because as you increase the possible orbitals that the electrons have access to, the lower the ground state could be.D: The asymptotic energy is approached from above, because as you increase the possible orbitals the more accurate is your simulation, adding energy that was left out before.``` **Uncomment your answers to these multiple choice questions in the code-cell below. Run the cell to submit your answers.**
###Code
from qc_grader import grade_ex3b
## Q1
# answer_for_ex3b_q1 = 'A'
# answer_for_ex3b_q1 = 'B'
answer_for_ex3b_q1 = 'C'
##
#answer_for_ex3b_q1 = ''
## Q2
answer_for_ex3b_q2 = 'A'
# answer_for_ex3b_q2 = 'B'
# answer_for_ex3b_q2 = 'C'
# answer_for_ex3b_q2 = 'D'
##
#answer_for_ex3b_q2 = ''
grade_ex3b(answer_for_ex3b_q1, answer_for_ex3b_q2)
###Output
Submitting your answer for ex3/partB. Please wait...
Congratulations 🎉! Your answer is correct and has been submitted.
###Markdown
3. Refining Step 4: Energy Surface In Step 4, we ran the ground_state solver on a given molecule once only and we haven't yet explained how to instruct Qiskit to vary the molecular geometry using the specification introduced above. As explained in the introduction, changing the nuclei positions and comparing the total energy levels, is a method for finding the nuclei arrangement with the lowest energy. If the lowest energy is **not** at "infinity", this corresponds to a "stable" bound state of the molecule at the energy minimum. The energy as a function of atomic separation is thus a crucial object of study. This function is called the **Born-Oppenheimer Potential Energy Surface (BOPES)**. Qiskit provides a helpful python Class that manages this process of varying the geometry and repeatedly calling the ground_state solver: **BOPESSampler**.Let's demonstrate BOPESSampler for the hydrogen molecule.*The only steps of the hydrogen molecule walk-through that need to be re-run are Steps 1 and 2a:*
###Code
hydrogen_stretchable_molecular_orbital_maker = PySCFDriver(molecule=hydrogen_molecule_stretchable, unit=UnitsType.ANGSTROM, basis='sto3g')
hydrogen_stretchable_fermionic_hamiltonian = ElectronicStructureProblem(hydrogen_stretchable_molecular_orbital_maker)
###Output
_____no_output_____
###Markdown
*Secondly, here is how to call the sampler:*
###Code
energy_surface = BOPESSampler(gss=hydrogen_ground_state, bootstrap=False) # same solver suffices, since the trial is the same
perturbation_steps = np.linspace(-0.5, 2, 25) # 25 equally spaced points from -0.5 to 2, inclusive.
energy_surface_result = energy_surface.sample(hydrogen_stretchable_fermionic_hamiltonian, perturbation_steps)
###Output
/opt/conda/lib/python3.8/site-packages/qiskit_nature/algorithms/pes_samplers/bopes_sampler.py:192: DeprecationWarning:
The VQE.optimal_params property is deprecated as of Qiskit Terra 0.18.0
and will be removed no sooner than 3 months after the releasedate.
This information is part of the returned result object and can be
queried as VQEResult.optimal_point.
optimal_params = self._gss.solver.optimal_params # type: ignore
###Markdown
*Thirdly, here is how to produce the famous energy landscape plot:*
###Code
def plot_energy_landscape(energy_surface_result):
if len(energy_surface_result.points) > 1:
plt.plot(energy_surface_result.points, energy_surface_result.energies, label="VQE Energy")
plt.xlabel('Atomic distance Deviation(Angstrom)')
plt.ylabel('Energy (hartree)')
plt.legend()
plt.show()
else:
print("Total Energy is: ", energy_surface_result.energies[0], "hartree")
print("(No need to plot, only one configuration calculated.)")
plot_energy_landscape(energy_surface_result)
###Output
_____no_output_____
###Markdown
For extra intuition, you may think of the energy landscape as a mountain, next to a valley, next to a plateau that a ball rolls on (the x co-ordinate of the ball corresponds the separation between the two hydrogen atoms). If the ball is not rolling too fast down the plateau (right to left) it may settle in the valley. The ball slowly rolls down the plateau because the slope is positive (representing a force of attraction between the two hydrogen atoms). If the ball overshoots the minimum point of the valley, it meets the steep negative slope of the mountain and quickly rolls back (the hydrogen atoms repell each other).Notice the minimum is at zero. This is because we defined the hydrogen molecule's nuclei positions at the known ground state positions.By the way, if we had used the hardware_inspired_trial we would have produced a similiar plot, however it would have had bumps because the anzatz does not capture the electronic ground state equally well at different bond lengths. Exercise 3c: Energy Landscape, To bind or not to bind?The million-dollar question: Does our toy anti-retrovial bind and thus block the protease? - Search for the minimum from -0.5 to 5 for 30 points. - Give quantum-computing treatment to 2 electrons roaming over 2 orbitalsQ1. Submit the energy landscape for the anti-retroviral approaching the protease.Q2. Is there a clear minimum at a finite separation? Does binding occur?```A. Yes, there is a clear minimum at 0, so binding does occur.B. Yes, there is a clear minimum at infinity, so binding only happens at infinity.C. No, there is no clear minimum for any separation, so binding occurs because there is no seperation.D. No, there is no clear minimum for any separation, so there is no binding.```(Don't preempt the answer. Furthermore, the answer might change for other approaches and other settings, so please stick to the requested settings.) *Feel free to use the following function, which collects the entire walk-through and refinements to Step 2 and 4. It takes in a Molecule (of refinement Step 1 type), the inputs for the other refinements and boolean choice of whether to use VQE or the numpy solver:*
###Code
def construct_hamiltonian_solve_ground_state(
molecule,
num_electrons=2,
num_molecular_orbitals=2,
chemistry_inspired=True,
hardware_inspired_trial=None,
vqe=True,
perturbation_steps=np.linspace(-1, 1, 3),
):
"""Creates fermionic Hamiltonion and solves for the energy surface.
Args:
molecule (Union[qiskit_nature.drivers.molecule.Molecule, NoneType]): The molecule to simulate.
num_electrons (int, optional): Number of electrons for the `ActiveSpaceTransformer`. Defaults to 2.
num_molecular_orbitals (int, optional): Number of electron orbitals for the `ActiveSpaceTransformer`. Defaults to 2.
chemistry_inspired (bool, optional): Whether to create a chemistry inspired trial state. `hardware_inspired_trial` must be `None` when used. Defaults to True.
hardware_inspired_trial (QuantumCircuit, optional): The hardware inspired trial state to use. `chemistry_inspired` must be False when used. Defaults to None.
vqe (bool, optional): Whether to use VQE to calculate the energy surface. Uses `NumPyMinimumEigensolver if False. Defaults to True.
perturbation_steps (Union(list,numpy.ndarray), optional): The points along the degrees of freedom to evaluate, in this case a distance in angstroms. Defaults to np.linspace(-1, 1, 3).
Raises:
RuntimeError: `chemistry_inspired` and `hardware_inspired_trial` cannot be used together. Either `chemistry_inspired` is False or `hardware_inspired_trial` is `None`.
Returns:
qiskit_nature.results.BOPESSamplerResult: The surface energy as a BOPESSamplerResult object.
"""
# Verify that `chemistry_inspired` and `hardware_inspired_trial` do not conflict
if chemistry_inspired and hardware_inspired_trial is not None:
raise RuntimeError(
(
"chemistry_inspired and hardware_inspired_trial"
" cannot both be set. Either chemistry_inspired"
" must be False or hardware_inspired_trial must be none."
)
)
# Step 1 including refinement, passed in
# Step 2a
molecular_orbital_maker = PySCFDriver(
molecule=molecule, unit=UnitsType.ANGSTROM, basis="sto3g"
)
# Refinement to Step 2a
split_into_classical_and_quantum = ActiveSpaceTransformer(
num_electrons=num_electrons, num_molecular_orbitals=num_molecular_orbitals
)
fermionic_hamiltonian = ElectronicStructureProblem(
molecular_orbital_maker, [split_into_classical_and_quantum]
)
fermionic_hamiltonian.second_q_ops()
# Step 2b
map_fermions_to_qubits = QubitConverter(JordanWignerMapper())
# Step 3a
if chemistry_inspired:
molecule_info = fermionic_hamiltonian.molecule_data_transformed
num_molecular_orbitals = molecule_info.num_molecular_orbitals
num_spin_orbitals = 2 * num_molecular_orbitals
num_electrons_spin_up_spin_down = (
molecule_info.num_alpha,
molecule_info.num_beta,
)
initial_state = HartreeFock(
num_spin_orbitals, num_electrons_spin_up_spin_down, map_fermions_to_qubits
)
chemistry_inspired_trial = UCCSD(
map_fermions_to_qubits,
num_electrons_spin_up_spin_down,
num_spin_orbitals,
initial_state=initial_state,
)
trial_state = chemistry_inspired_trial
else:
if hardware_inspired_trial is None:
hardware_inspired_trial = TwoLocal(
rotation_blocks=["ry"],
entanglement_blocks="cz",
entanglement="linear",
reps=2,
)
trial_state = hardware_inspired_trial
# Step 3b and alternative
if vqe:
noise_free_quantum_environment = QuantumInstance(Aer.get_backend('statevector_simulator'))
solver = VQE(ansatz=trial_state, quantum_instance=noise_free_quantum_environment)
else:
solver = NumPyMinimumEigensolver()
# Step 4 and alternative
ground_state = GroundStateEigensolver(map_fermions_to_qubits, solver)
# Refinement to Step 4
energy_surface = BOPESSampler(gss=ground_state, bootstrap=False)
energy_surface_result = energy_surface.sample(
fermionic_hamiltonian, perturbation_steps
)
return energy_surface_result
###Output
_____no_output_____
###Markdown
Your answer The following code cells give a skeleton to call `construct_hamiltonian_solve_ground_state` and plot the results. Once you are confident with your results, submit them in the code-cell that follows.**Note: `construct_hamiltonian_solve_ground_state` will take some time to run (approximately 2 minutes). Do not worry if it doesn't return a result immediately.**
###Code
# Q1
# Calculate the energies
q1_energy_surface_result = construct_hamiltonian_solve_ground_state(
molecule=macromolecule,
num_electrons=2,
num_molecular_orbitals=2,
chemistry_inspired=True,
vqe=True,
perturbation_steps=np.linspace(-0.5, 5, 30),
)
# Plot the energies to visualize the results
plot_energy_landscape(energy_surface_result)
## Q2
#answer_for_ex3c_q2 = 'A'
# answer_for_ex3c_q2 = 'B'
# answer_for_ex3c_q2 = 'C'
answer_for_ex3c_q2 = 'D'
#answer_for_ex3c_q2 = ''
###Output
_____no_output_____
###Markdown
Once you are happy with the results you have acquired, submit the energies and parameters for `construct_hamiltonian_solve_ground_state` in the following cell. Change the values for all parameters, except `energy_surface`, to have the same value that you used in your call of `construct_hamiltonian_solve_ground_state`
###Code
from qc_grader import grade_ex3c
grade_ex3c(
energy_surface=q1_energy_surface_result.energies,
molecule=macromolecule,
num_electrons=2,
num_molecular_orbitals=2,
chemistry_inspired=True,
hardware_inspired_trial=None,
vqe=True,
perturbation_steps=np.linspace(-0.5, 5, 30),
q2_multiple_choice=answer_for_ex3c_q2
)
###Output
Submitting your answer for ex3/partC. Please wait...
Congratulations 🎉! Your answer is correct and has been submitted.
###Markdown
4. Refining Step 3a The last refinement is a lesson in how black-box tweaking can improve results.In Step 3a, the hardware_inspired_trial is designed to run on actual current-day hardware. Recall this line from the walk-through:
###Code
hardware_inspired_trial = TwoLocal(rotation_blocks = ['ry'], entanglement_blocks = 'cz',
entanglement='linear', reps=2)
###Output
_____no_output_____
###Markdown
Let us get a feel for the `reps` (repetition) parameter. This parameter controls how many rounds of mix and rotate are applied in the trial state. In more detail: there is an initial round of rotations, before mix (often containing no parameters) and another round of rotations are repeated. Certain gates don't generate parameters (e.g. `h`, `cz`). Each round of rotations adds an extra set of parameters that the classical optimizer adjusts in the search for the ground state.Let's relook at the simple hydrogen molecule and compute the "ideal" lowest energy electronic energy using the chemistry trial, the numpy solver and a single zero perturbation (i.e., no perturbations):
###Code
true_total_energy = construct_hamiltonian_solve_ground_state(
molecule=hydrogen_molecule_stretchable, # Step 1
num_electrons=2, # Step 2a
num_molecular_orbitals=2, # Step 2a
chemistry_inspired=True, # Step 3a
vqe=False, # Step 3b
perturbation_steps = [0]) # Step 4
plot_energy_landscape(true_total_energy)
###Output
Total Energy is: -1.137306035753395 hartree
(No need to plot, only one configuration calculated.)
###Markdown
We take this as the true value for the rest of our experiment.*Next, select `chemistry_inspired=False`, `vqe=True` and pass in a hardware trial with 1 round*:
###Code
# hardware_inspired_trial = TwoLocal(rotation_blocks = ['ry'], entanglement_blocks = 'cz',
# entanglement='linear', reps=1)
# quantum_calc_total_energy = construct_hamiltonian_solve_ground_state(
# molecule=hydrogen_molecule_stretchable, # Step 1
# num_electrons=2, # Step 2a
# num_molecular_orbitals=2, # Step 2a
# chemistry_inspired=False, # Step 3a
# hardware_inspired_trial=hardware_inspired_trial, # Step 3a
# vqe=True, # Step 3b
# perturbation_steps = [0]) # Step 4
# plot_energy_landscape(quantum_calc_total_energy)
hardware_inspired_trial = TwoLocal(rotation_blocks = ['ry'], entanglement_blocks = 'cz',
entanglement='linear', reps=2)
quantum_calc_total_energy = construct_hamiltonian_solve_ground_state(
molecule=hydrogen_molecule_stretchable, # Step 1
num_electrons=2, # Step 2a
num_molecular_orbitals=2, # Step 2a
chemistry_inspired=False, # Step 3a
hardware_inspired_trial=hardware_inspired_trial, # Step 3a
vqe=True, # Step 3b
perturbation_steps = [0]) # Step 4
plot_energy_landscape(quantum_calc_total_energy)
###Output
Total Energy is: -1.1373038685569221 hartree
(No need to plot, only one configuration calculated.)
###Markdown
*Notice the difference is small and positive:*
###Code
quantum_calc_total_energy.energies[0] - true_total_energy.energies[0]
###Output
_____no_output_____
###Markdown
*Let's see how many parameters are used to specify the trial state:*
###Code
total_number_of_parameters = len(hardware_inspired_trial._ordered_parameters)
print("Total number of adjustable parameters: ", total_number_of_parameters)
###Output
Total number of adjustable parameters: 12
###Markdown
Exercise 3d: The effect of more repetitions Q1: Try reps equal to 1 (done for you) and 2 and compare the errors. What happens to the error? Does it increase, decrease, or stay the same?Be aware that: - VQE is a statistical algorithm, so run it a few times before observing the pattern. - Going beyond 2 may not continue the pattern. - Note that `reps` is defined in `TwoLocal`Q2: Check the total number of parameters for reps equal 1 and 2. How many parameters are introduced per round of rotations? Write your answer here: **Enter your answer to the first multiple choice question in the code-cell below and add your answer for Q2. Run the cell to submit your answers.**
###Code
from qc_grader import grade_ex3d
## Q1
answer_for_ex3d_q1 = 'decreases'
#answer_for_ex3d_q1 = 'increases'
# answer_for_ex3d_q1 = 'stays the same'
##
#answer_for_ex3d_q1 = ''
## Q2
answer_for_ex3d_q2 = 4
##
grade_ex3d(answer_for_ex3d_q1, answer_for_ex3d_q2)
###Output
Submitting your answer for ex3/partD. Please wait...
Congratulations 🎉! Your answer is correct and has been submitted.
###Markdown
Exercise 3e: Open-ended: Find the best hardware_inspired_trial to minimize the Energy Error for the Macromolecule Turning to the macromolecule again. Using, `chemistry_inspired=False`, `vqe=True`, `perturbation_steps = [0]`, a maximum of 8 qubits, and your own hardware_inspired_trial with any combination of options from the walk-through; find the lowest energy. Your answer to this exercise includes all parameters passed to `construct_hamiltonian_solve_ground_state` and the result object it returns. This exercise is scored based on how close your computed energy $E_{computed}$ is to the "true" minimum energy of the macromolecule $E_{true}$. This score is calculated as shown below, rounded to the nearest integer. $$\text{score} = -10 \times \log_{10}{\left(\left\lvert{\frac{E_{true} - E_{computed}}{E_{true}}}\right\rvert\right)}$$ Achieving a smaller error in your computed energy will increase your score. For example, if the true energy is -42.141 and you compute -40.0, you would have a score of 13. Use the following code cell to trial different `hardware_inspired_trial`s.
###Code
# Modify the following variables
num_electrons = 2
num_molecular_orbitals = 2
hardware_inspired_trial = TwoLocal(4, rotation_blocks = ['ry'], entanglement_blocks = 'cz',
entanglement='full', reps=60)
#
computed_macromolecule_energy_result = construct_hamiltonian_solve_ground_state(
molecule=macromolecule,
num_electrons=num_electrons,
num_molecular_orbitals=num_molecular_orbitals,
chemistry_inspired=False,
hardware_inspired_trial=hardware_inspired_trial,
vqe=True,
perturbation_steps=[0],
)
###Output
_____no_output_____
###Markdown
Once you are ready to submit your answer, run the following code cell to have your computed energy scored. You can submit multiple times.
###Code
from qc_grader import grade_ex3e
grade_ex3e(
energy_surface_result=computed_macromolecule_energy_result,
molecule=macromolecule,
num_electrons=num_electrons,
num_molecular_orbitals=num_molecular_orbitals,
chemistry_inspired=False,
hardware_inspired_trial=hardware_inspired_trial,
vqe=True,
perturbation_steps=[0],
)
###Output
Submitting your answer for ex3/partE. Please wait...
Congratulations 🎉! Your answer is correct and has been submitted.
Your score is 91.
###Markdown
---------------- Quantum Chemistry Resources*Videos*- *Quantum Chemistry I: Obtaining the Qubit Hamiltonian* - https://www.youtube.com/watch?v=2XEjrwWhr88- *Quantum Chemistry II: Finding the Ground States* - https://www.youtube.com/watch?v=_UW6puuGa5E - https://www.youtube.com/watch?v=o4BAOKbcd3o*Tutorials*- https://qiskit.org/documentation/nature/tutorials/01_electronic_structure.html - https://qiskit.org/documentation/nature/tutorials/03_ground_state_solvers.html - https://qiskit.org/documentation/nature/tutorials/05_Sampling_potential_energy_surfaces.html*Code References*- UCCSD : https://qiskit.org/documentation/stubs/qiskit.chemistry.components.variational_forms.UCCSD.html- ActiveSpaceTransformer: https://qiskit.org/documentation/nature/stubs/qiskit_nature.transformers.second_quantization.electronic.ActiveSpaceTransformer.html?highlight=activespacetransformerqiskit_nature.transformers.second_quantization.electronic.ActiveSpaceTransformer Licensing and notes:- All images used, with gratitude, are listed below with their respective licenses: - https://de.wikipedia.org/wiki/Datei:Teppichschere.jpg by CrazyD is licensed under CC BY-SA 3.0 - https://commons.wikimedia.org/wiki/File:The_structure_of_the_immature_HIV-1_capsid_in_intact_virus_particles.png by MarinaVladivostok is licensed under CC0 1.0 - https://commons.wikimedia.org/wiki/File:Peptidformationball.svg by YassineMrabet is licensed under the public domain - The remaining images are either IBM-owned, or hand-generated by the authors of this notebook.- HCONH2 (Formamide) co-ordinates kindly provided by the National Library of Medicine: - `National Center for Biotechnology Information (2021). PubChem Compound Summary for CID 713, Formamide. https://pubchem.ncbi.nlm.nih.gov/compound/Formamide.`- For further information about the Pauli exclusion principle:https://en.wikipedia.org/wiki/Pauli_exclusion_principle- We would like to thank collaborators, Prof Yasien and Prof Munro from Wits for extensive assistance.- We would like to thank all the testers and feedback providers for their valuable input.
###Code
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
###Output
/opt/conda/lib/python3.8/site-packages/qiskit/aqua/__init__.py:86: DeprecationWarning: The package qiskit.aqua is deprecated. It was moved/refactored to qiskit-terra For more information see <https://github.com/Qiskit/qiskit-aqua/blob/main/README.md#migration-guide>
warn_package('aqua', 'qiskit-terra')
###Markdown
1.Create a list with tuples inside it(series) calculate he sum of the element in tuple and store the sum of tuples in second list
###Code
list=[(1,2,3),(4,5,6)]
list1=[]
for i in list:
list1.append(sum(i))
print(list1)
###Output
[6, 15]
###Markdown
wap to create a list and input numbers into it,then remove the repeated element from it and display it back.
###Code
lis=[]
n = int(input("Enter number of elements : "))
for i in range(0, n):
ele = int(input())
lis.append(ele)
print(lis)
res = []
for i in lis:
if i not in res:
res.append(i)
print ("The list after removing duplicates : " + str(res))
###Output
Enter number of elements : 5
5
5
6
1
4
[5, 5, 6, 1, 4]
The list after removing duplicates : [5, 6, 1, 4]
###Markdown
COMP 215 - LAB 2---------------- Name: Graham Swanston Date: January 20, 2022This lab exercise is mostly a review of strings, tuples, lists, dictionaries, and functions.We will also see how "list comprehension" provides a compact form for "list accumulator" algorithms.As usual, the first code cell simply imports all the modules we'll be using...
###Code
import json, requests
import matplotlib.pyplot as plt
from pprint import pprint
###Output
_____no_output_____
###Markdown
We'll answer some questions about movies and TV shows with the IMDb database: https://www.imdb.com/> using the IMDb API: https://imdb-api.com/apiYou can register for your own API key, or simply use the one provided below.Here's an example query: * search for TV Series with title == "Lexx"
###Code
API_KEY = 'k_ynffhhna'
title = 'lexx'
url = "https://imdb-api.com/en/API/SearchTitle/{key}/{title}".format(key=API_KEY, title=title)
response = requests.request("GET", url, headers={}, data={})
data = json.loads(response.text) # recall json.loads for lab 1
results = data['results']
pprint(results)
###Output
[{'description': '(1996) (TV Series)',
'id': 'tt0115243',
'image': 'https://imdb-api.com/images/original/MV5BOGFjMzQyMTYtMjQxNy00NjAyLWI2OWMtZGVhMjk4OGM3ZjE5XkEyXkFqcGdeQXVyNzMzMjU5NDY@._V1_Ratio0.7273_AL_.jpg',
'resultType': 'Title',
'title': 'Lexx'},
{'description': '(2008) (Video)',
'id': 'tt1833738',
'image': 'https://imdb-api.com/images/original/MV5BMjAyMTYzNjk4NV5BMl5BanBnXkFtZTcwNzE4MTU0NA@@._V1_Ratio0.7273_AL_.jpg',
'resultType': 'Title',
'title': 'Lexx'},
{'description': '(2018)',
'id': 'tt10800568',
'image': 'https://imdb-api.com/images/original/MV5BZWY5ODYwNzYtMmIyMS00YzhhLTg0OTAtODM1M2I5YzkxMzY1XkEyXkFqcGdeQXVyMTEwNDU1MzEy._V1_Ratio0.7273_AL_.jpg',
'resultType': 'Title',
'title': 'Lexxy Roxx: Lexy 360 - Der Film'},
{'description': '(2014) (Short)',
'id': 'tt4396272',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'resultType': 'Title',
'title': 'Lexxxus'},
{'description': '(2016) (Video) aka "Lexxzibé Inonime Nirek & Elmaniak: La '
'Belle Et La Bête (2016)"',
'id': 'tt14690226',
'image': 'https://imdb-api.com/images/original/MV5BN2NmNGYxZTgtYjg3MC00ZDZhLTk1ODUtM2E4NGYwYzQ3YTFiXkEyXkFqcGdeQXVyMTA2NzA1NDYz._V1_Ratio1.7727_AL_.jpg',
'resultType': 'Title',
'title': 'Mauvais augure feat. Nirek & Ced (Elmaniak) Auger: La Belle Et La '
'Bête'},
{'description': '(2018) (Short)',
'id': 'tt12646262',
'image': 'https://imdb-api.com/images/original/MV5BODczYTEwNTctYzAzYy00YjIzLThkNGQtMDdjYmU5NjI1MzAxXkEyXkFqcGdeQXVyMTIwNjM2NTQz._V1_Ratio2.3182_AL_.jpg',
'resultType': 'Title',
'title': 'Lexxe - Red Velvet'},
{'description': '(2020) (TV Series)',
'id': 'tt6964748',
'image': 'https://imdb-api.com/images/original/MV5BOTg4ZmQ5ZjItZTllZC00NzUzLTkwMTEtMjIzYzliZjk2ODUwXkEyXkFqcGdeQXVyMTEyMjM2NDc2._V1_Ratio0.7273_AL_.jpg',
'resultType': 'Title',
'title': 'Alex Rider'},
{'description': '(2004)',
'id': 'tt0346491',
'image': 'https://imdb-api.com/images/original/MV5BMTA1NDQ3OTY2NDVeQTJeQWpwZ15BbWU3MDI5MDc0MzM@._V1_Ratio0.7273_AL_.jpg',
'resultType': 'Title',
'title': 'Alexander'},
{'description': '(2015)',
'id': 'tt2268016',
'image': 'https://imdb-api.com/images/original/MV5BNDMyODU3ODk3Ml5BMl5BanBnXkFtZTgwNDc1ODkwNjE@._V1_Ratio0.7273_AL_.jpg',
'resultType': 'Title',
'title': 'Magic Mike XXL'}]
###Markdown
Next we extract the item we want from the data set by applying a "filter":
###Code
items = [item for item in results if item['title']=='Lexx' and "TV" in item['description']]
assert len(items) == 1
lexx = items[0]
pprint(lexx)
###Output
{'description': '(1996) (TV Series)',
'id': 'tt0115243',
'image': 'https://imdb-api.com/images/original/MV5BOGFjMzQyMTYtMjQxNy00NjAyLWI2OWMtZGVhMjk4OGM3ZjE5XkEyXkFqcGdeQXVyNzMzMjU5NDY@._V1_Ratio0.7273_AL_.jpg',
'resultType': 'Title',
'title': 'Lexx'}
###Markdown
Exercise 1In the code cell below, re-write the "list comprehension" above as a loop so you understand how it works.Notice how the "conditional list comprehension" is a compact way to "filter" items of interest from a large data set.
###Code
items = []
for i in results:
if i['title'] == 'Lexx' and "TV" in i['description']:
items.append(i)
assert len(items) == 1
pprint(items[0])
###Output
{'description': '(1996) (TV Series)',
'id': 'tt0115243',
'image': 'https://imdb-api.com/images/original/MV5BOGFjMzQyMTYtMjQxNy00NjAyLWI2OWMtZGVhMjk4OGM3ZjE5XkEyXkFqcGdeQXVyNzMzMjU5NDY@._V1_Ratio0.7273_AL_.jpg',
'resultType': 'Title',
'title': 'Lexx'}
###Markdown
Notice that the `lexx` dictionary contains an `id` field that uniquely identifies this record in the database.We can use the `id` to fetch other information about the TV series, for example,* get names of all actors in the TV Series Lexx
###Code
url = "https://imdb-api.com/en/API/FullCast/{key}/{id}".format(key=API_KEY, id=lexx['id'])
response = requests.request("GET", url, headers={}, data={})
data = json.loads(response.text)
actors = data['actors']
pprint(actors) # recall the slice operator (it's a long list!)
###Output
[{'asCharacter': 'Stanley H. Tweedle / ... 61 episodes, 1996-2002',
'id': 'nm0235978',
'image': 'https://imdb-api.com/images/original/MV5BMTYxODI3OTM5Ml5BMl5BanBnXkFtZTgwMjM4ODc3MjE@._V1_Ratio1.3182_AL_.jpg',
'name': 'Brian Downey'},
{'asCharacter': 'Kai / ... 61 episodes, 1996-2002',
'id': 'nm0573158',
'image': 'https://imdb-api.com/images/original/MV5BMTY3MjQ4NzE0NV5BMl5BanBnXkFtZTgwNDE4ODc3MjE@._V1_Ratio1.3182_AL_.jpg',
'name': 'Michael McManus'},
{'asCharacter': '790 / ... 57 episodes, 1996-2002',
'id': 'nm0386601',
'image': 'https://imdb-api.com/images/original/MV5BMjMyMDM1NzgzNF5BMl5BanBnXkFtZTgwOTM4ODc3MjE@._V1_Ratio1.3182_AL_.jpg',
'name': 'Jeffrey Hirschfield'},
{'asCharacter': 'Xev Bellringer / ... 55 episodes, 1998-2002',
'id': 'nm0781462',
'image': 'https://imdb-api.com/images/original/MV5BMTk2MDQ4NzExOF5BMl5BanBnXkFtZTcwOTMyNzcyMQ@@._V1_Ratio0.7273_AL_.jpg',
'name': 'Xenia Seeberg'},
{'asCharacter': 'The Lexx 46 episodes, 1996-2002',
'id': 'nm0302577',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Tom Gallant'},
{'asCharacter': 'Prince / ... 23 episodes, 2000-2002',
'id': 'nm0000911',
'image': 'https://imdb-api.com/images/original/MV5BMTgxMTY2NzM5NF5BMl5BanBnXkFtZTcwMDA5MDYxOA@@._V1_Ratio0.7727_AL_.jpg',
'name': 'Nigel Bennett'},
{'asCharacter': 'Bunny Priest / ... 16 episodes, 1999-2002',
'id': 'nm0954934',
'image': 'https://imdb-api.com/images/original/MV5BMTg2Mjk2Nzk5NV5BMl5BanBnXkFtZTcwNzYyODQzMQ@@._V1_Ratio0.7727_AL_.jpg',
'name': 'Patricia Zentilli'},
{'asCharacter': 'Bound Man / ... 8 episodes, 1996-2002',
'id': 'nm0317596',
'image': 'https://imdb-api.com/images/original/MV5BNjNiNzAwMjQtYTU1NC00NDkzLWI4OTktYjA0NWRiZjEzZmFkXkEyXkFqcGdeQXVyMTAwMzUyMzUy._V1_Ratio0.7273_AL_.jpg',
'name': 'Lex Gigeroff'},
{'asCharacter': 'Reginald J. Priest / ... 13 episodes, 2000-2002',
'id': 'nm0437708',
'image': 'https://imdb-api.com/images/original/MV5BMWFmNDI5YWEtMjRkYi00MTRhLTk5YjMtYTEwNTgyMWQ2ODk4XkEyXkFqcGdeQXVyNDM4NDA1Mg@@._V1_Ratio0.7273_AL_.jpg',
'name': 'Rolf Kanies'},
{'asCharacter': 'Lyekka / ... 10 episodes, 1998-2002',
'id': 'nm0936263',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Louise Wischermann'},
{'asCharacter': 'Divine Predecessor / ... 7 episodes, 1996-2002',
'id': 'nm0243082',
'image': 'https://imdb-api.com/images/original/MV5BMTc0MzA1NTExMl5BMl5BanBnXkFtZTcwMzU5NTgwOA@@._V1_Ratio0.7273_AL_.jpg',
'name': 'John Dunsworth'},
{'asCharacter': 'His Divine Shadow / ... 8 episodes, 1996-2002',
'id': 'nm0096168',
'image': 'https://imdb-api.com/images/original/MV5BMTI4NDQ2NzI0OF5BMl5BanBnXkFtZTcwMTM3MDkyMQ@@._V1_Ratio0.7727_AL_.jpg',
'name': 'Walter Borden'},
{'asCharacter': 'Mothbreeder / ... 3 episodes, 1998-2002',
'id': 'nm1116337',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'David Albiston'},
{'asCharacter': 'Vlad / ... 5 episodes, 2001-2002',
'id': 'nm0007392',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Minna Aaltonen'},
{'asCharacter': 'Megashadow Adjutant / ... 6 episodes, 1996-2000',
'id': 'nm0842105',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Clive Sweeney'},
{'asCharacter': 'Zev Bellringer 7 episodes, 1996-2000',
'id': 'nm0352230',
'image': 'https://imdb-api.com/images/original/MV5BNWU1MzZjZmYtYzkyOC00OGQ2LWI1ZWYtMzdkODgzNGYzNjU4XkEyXkFqcGdeQXVyMjM1OTk0NDQ@._V1_Ratio0.7273_AL_.jpg',
'name': 'Eva Habermann'},
{'asCharacter': 'Giggerota / ... 7 episodes, 1996-2002',
'id': 'nm0239294',
'image': 'https://imdb-api.com/images/original/MV5BYTMxOGRjMDEtZTkxMC00NWEyLTg2YjYtMjMzNmJiZmIzODcwXkEyXkFqcGdeQXVyMDYxMjk5MQ@@._V1_Ratio1.5000_AL_.jpg',
'name': 'Ellen Dubin'},
{'asCharacter': 'The Time Prophet / ... 5 episodes, 1996-2002',
'id': 'nm0131487',
'image': 'https://imdb-api.com/images/original/MV5BMjAyNzU1MTQyM15BMl5BanBnXkFtZTgwMDg4ODc3MjE@._V1_Ratio1.3182_AL_.jpg',
'name': 'Anna Cameron'},
{'asCharacter': 'Mantrid 5 episodes, 1998-2000',
'id': 'nm0489504',
'image': 'https://imdb-api.com/images/original/MV5BMjg1NWQ2ZTItMTU4MS00YTkyLWI1MzEtY2EzYTVlNDA1MmFjXkEyXkFqcGdeQXVyMTI3MDk3MzQ@._V1_Ratio1.6364_AL_.jpg',
'name': 'Dieter Laser'},
{'asCharacter': 'Fifi / ... 6 episodes, 1999-2001',
'id': 'nm0701146',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Jeff Pustil'},
{'asCharacter': 'Holo Cleric / ... 5 episodes, 1996-2001',
'id': 'nm0565774',
'image': 'https://imdb-api.com/images/original/MV5BNzhhYTNlNjQtNTc0NC00NGY3LTk1NTEtMGM0Njk2ZTJmOWRmXkEyXkFqcGdeQXVyMjM2ODExMQ@@._V1_Ratio0.7727_AL_.jpg',
'name': 'David McClelland'},
{'asCharacter': 'Dougall 4 episodes, 2001-2002',
'id': 'nm2624364',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Kevin Curran'},
{'asCharacter': 'Jood / ... 5 episodes, 1996-2001',
'id': 'nm0103267',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Jamie Bradley'},
{'asCharacter': 'Transport Major / ... 5 episodes, 1996-1999',
'id': 'nm0015193',
'image': 'https://imdb-api.com/images/original/MV5BMTA4MjQ1NzQ1ODheQTJeQWpwZ15BbWU3MDQ5ODI4MzI@._V1_Ratio1.0909_AL_.jpg',
'name': 'Jeremy Akerman'},
{'asCharacter': 'Child / ... 5 episodes, 1996-1999',
'id': 'nm0037627',
'image': 'https://imdb-api.com/images/original/MV5BMWZlYTM1NjctM2VjZi00NmM5LTgyOTEtM2E4OWJhNzk0NmY1XkEyXkFqcGdeQXVyMzU3NTAyNzQ@._V1_Ratio1.5000_AL_.jpg',
'name': 'Nicolás Artajo'},
{'asCharacter': 'Holo Lawyr / ... 5 episodes, 1996-2002',
'id': 'nm0201766',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'John Dartt'},
{'asCharacter': 'Video Customs Officer / ... 5 episodes, 1996-2001',
'id': 'nm0493351',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Chas Lawther'},
{'asCharacter': 'Mothbreeder / ... 1 episode, 2000-2002',
'id': 'nm2067344',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Todd Godin'},
{'asCharacter': 'Petrif / ... 4 episodes, 1996-2000',
'id': 'nm0797459',
'image': 'https://imdb-api.com/images/original/MV5BMTU0MTE3NDc3MV5BMl5BanBnXkFtZTYwNDQxMjEz._V1_Ratio1.4091_AL_.jpg',
'name': 'Robert Sigl'},
{'asCharacter': 'Joshua / ... 4 episodes, 1996-2000',
'id': 'nm0719881',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'David Renton'},
{'asCharacter': 'Holo Judge / ... 4 episodes, 1996-1999',
'id': 'nm0234734',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Lionel Doucette'},
{'asCharacter': 'Duke 5 episodes, 2000',
'id': 'nm0114460',
'image': 'https://imdb-api.com/images/original/MV5BMTQ5MDQ3ODY3N15BMl5BanBnXkFtZTcwNDEzNDc3Mg@@._V1_Ratio0.7273_AL_.jpg',
'name': 'Ralph Brown'},
{'asCharacter': 'May 5 episodes, 2000',
'id': 'nm0088304',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Anna Kathrin Bleuler'},
{'asCharacter': 'Anchorman / ... 4 episodes, 2001-2002',
'id': 'nm0030022',
'image': 'https://imdb-api.com/images/original/MV5BOTYyMjY2NTE4MF5BMl5BanBnXkFtZTgwNzYyNTM0MjE@._V1_Ratio1.3182_AL_.jpg',
'name': 'Tony Anholt'},
{'asCharacter': 'Tina 4 episodes, 2001-2002',
'id': 'nm0236502',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Tara Doyle'},
{'asCharacter': 'Lead Balloonist / ... 4 episodes, 2000-2002',
'id': 'nm1022857',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Gary Levert'},
{'asCharacter': 'Handler 2 / ... 4 episodes, 1999-2001',
'id': 'nm0522630',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Jon K. Loverin'},
{'asCharacter': 'Archaeologist / ... 4 episodes, 1996-2002',
'id': 'nm0905599',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Glenn Wadman'},
{'asCharacter': 'Matron / ... 3 episodes, 1997-2000',
'id': 'nm0653946',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Jennifer Overton'},
{'asCharacter': 'Brock / ... 3 episodes, 2000-2001',
'id': 'nm0380189',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Geoff Herod'},
{'asCharacter': 'Blue Team Member / ... 1 episode, 2000-2002',
'id': 'nm0335418',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Glen Grant'},
{'asCharacter': 'Megashadow Admiral 4 episodes, 1996-1997',
'id': 'nm0232195',
'image': 'https://imdb-api.com/images/original/MV5BMjMxODkxMDgzMV5BMl5BanBnXkFtZTgwNjU5MDg5MjE@._V1_Ratio1.3182_AL_.jpg',
'name': 'Richard Donat'},
{'asCharacter': 'Tem 4 episodes, 1996-1997',
'id': 'nm0107621',
'image': 'https://imdb-api.com/images/original/MV5BOWM1NTRhMDktMjE0ZS00NGYzLTg2OGItY2JjMzJiY2ZmNWE2XkEyXkFqcGdeQXVyOTY5NjI2Mg@@._V1_Ratio0.7273_AL_.jpg',
'name': 'Gil Brenton'},
{'asCharacter': 'Wig Girl 4 episodes, 1996-1997',
'id': 'nm1683263',
'image': 'https://imdb-api.com/images/original/MV5BMTIwNzY2MjEyMF5BMl5BanBnXkFtZTcwOTY5MzgyMQ@@._V1_Ratio0.7273_AL_.jpg',
'name': 'Barbara Kowa'},
{'asCharacter': 'Correction Center Guard 4 episodes, 1996-1997',
'id': 'nm0139610',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Bill Carr'},
{'asCharacter': 'Honar 4 episodes, 1996-1997',
'id': 'nm0848345',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Sanjay Talwar'},
{'asCharacter': 'Monk 4 episodes, 1996-1997',
'id': 'nm2675156',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Clemens von Tubeuf'},
{'asCharacter': 'Scientist 4 episodes, 1996-1997',
'id': 'nm0002268',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Gary Vermeir'},
{'asCharacter': 'Cluster Major 4 episodes, 1996-1997',
'id': 'nm0192345',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Jocelyn Cunningham'},
{'asCharacter': 'Rebel 4 episodes, 1996-1997',
'id': 'nm0536763',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Andrei Mahankov'},
{'asCharacter': 'E.J. Moss, Commander of Eagle 5 / ... 3 episodes, 1998-2002',
'id': 'nm0565569',
'image': 'https://imdb-api.com/images/original/MV5BMGNlY2U5YmQtMjVmZi00N2ZiLWEwODktODA3YTViNjRhYzIxXkEyXkFqcGdeQXVyNjUxMjc1OTM@._V1_Ratio2.4091_AL_.jpg',
'name': 'Stephen McHattie'},
{'asCharacter': 'Digby 3 episodes, 2001',
'id': 'nm0177620',
'image': 'https://imdb-api.com/images/original/MV5BMTk1OTcxOTc2OF5BMl5BanBnXkFtZTYwNjYxOTY0._V1_Ratio0.7273_AL_.jpg',
'name': 'Ryan Cooley'},
{'asCharacter': 'Big Angry Ed / ... 3 episodes, 1999-2001',
'id': 'nm1051853',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Mark A. Owen'},
{'asCharacter': 'First Lady Priest / ... 2 episodes, 1999-2001',
'id': 'nm0942476',
'image': 'https://imdb-api.com/images/original/MV5BMGE1ZTMzMWItZTAwMS00N2I3LThlMTktN2U0ZWQ2NTUyYzA3L2ltYWdlL2ltYWdlXkEyXkFqcGdeQXVyMTExNDQ2MTI@._V1_Ratio1.0909_AL_.jpg',
'name': 'Janet Wright'},
{'asCharacter': 'Moth Breeder / ... 2 episodes, 2001-2002',
'id': 'nm0564301',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Geoff McBride'},
{'asCharacter': 'Moth Breeder 2 episodes, 2001-2002',
'id': 'nm3579176',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Jenson Vaughan'},
{'asCharacter': 'Louie / ... 2 episodes, 1999-2002',
'id': 'nm0215581',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Louis Del Grande'},
{'asCharacter': 'Norb / ... 2 episodes, 1999',
'id': 'nm0565443',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Brandon McCarvell'},
{'asCharacter': 'Boork / ... 2 episodes, 1997-1998',
'id': 'nm0475202',
'image': 'https://imdb-api.com/images/original/MV5BMDcwNzViMDYtN2JhMy00MGNjLTkyMTMtNTViNzBlZjIwZDM3XkEyXkFqcGdeQXVyMTAwMzUyMzUy._V1_Ratio0.7273_AL_.jpg',
'name': 'Holger Kunkel'},
{'asCharacter': 'Davinia Silver / ... 2 episodes, 2001',
'id': 'nm1605007',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Andrea Green'},
{'asCharacter': 'Lomea / ... 2 episodes, 1999-2001',
'id': 'nm1036268',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Lauren Abrahams'},
{'asCharacter': '791 / ... 2 episodes, 1999-2002',
'id': 'nm0141499',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Brian Carter'},
{'asCharacter': 'Chief Handler 2 episodes, 2000',
'id': 'nm0123906',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Linda Busby'},
{'asCharacter': 'Joseph Van Helsing 2 episodes, 2001',
'id': 'nm0347423',
'image': 'https://imdb-api.com/images/original/MV5BMTU2Mjc3NDQxNF5BMl5BanBnXkFtZTgwMzQzNzg5NDE@._V1_Ratio0.7273_AL_.jpg',
'name': 'Peter Guinness'},
{'asCharacter': 'Dad / ... 2 episodes, 2001',
'id': 'nm0167706',
'image': 'https://imdb-api.com/images/original/MV5BMTc2NTAxMTI1NV5BMl5BanBnXkFtZTYwNTgyMTEz._V1_Ratio0.7273_AL_.jpg',
'name': 'Stephen Coats'},
{'asCharacter': 'Muffy / ... 2 episodes, 2001',
'id': 'nm0003723',
'image': 'https://imdb-api.com/images/original/MV5BMTc4NTYwODcxNF5BMl5BanBnXkFtZTYwMjk0OTcy._V1_Ratio0.7273_AL_.jpg',
'name': 'Angie Hill'},
{'asCharacter': 'Gordon 2 episodes, 2002',
'id': 'nm0292744',
'image': 'https://imdb-api.com/images/original/MV5BYWEwM2M1YzItNTkzNi00MDMyLWIzNDMtMGZiZDI2YWM4YTMzXkEyXkFqcGdeQXVyNDkzNDM2OA@@._V1_Ratio0.7273_AL_.jpg',
'name': 'Dan Fredenburgh'},
{'asCharacter': 'Dream Girl #2 / ... 2 episodes, 1999',
'id': 'nm1581443',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Laura Mae Nason'},
{'asCharacter': 'ATF Agent #1 / ... 2 episodes, 1998-2001',
'id': 'nm1254005',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Chris Duffy'},
{'asCharacter': 'Skankita 2 episodes, 2002',
'id': 'nm1131152',
'image': 'https://imdb-api.com/images/original/MV5BNTIxY2MzZWEtYWUxNC00NjI5LTg5NjAtYjAzNGYzNzU1OTljXkEyXkFqcGdeQXVyMjQwMDg0Ng@@._V1_Ratio0.7273_AL_.jpg',
'name': 'Marem Hassler'},
{'asCharacter': 'Road Worker / ... 2 episodes, 1999-2002',
'id': 'nm0671066',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Michael Pellerin'},
{'asCharacter': 'Root / ... 2 episodes, 2000-2002',
'id': 'nm0134227',
'image': 'https://imdb-api.com/images/original/MV5BM2QwYjZjYmYtZTNmYi00NTYzLTlmZTUtZTRjZjk0OTY2ZjEwXkEyXkFqcGdeQXVyMTAwMjQ1OTU@._V1_Ratio1.5000_AL_.jpg',
'name': 'Landy Cannon'},
{'asCharacter': 'Mandragora Morgana / ... 2 episodes, 2001',
'id': 'nm2094983',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Rachel Mooney'},
{'asCharacter': 'Flintokk, Head Pimp Sister / ... 2 episodes, 1999-2000',
'id': 'nm0803016',
'image': 'https://imdb-api.com/images/original/MV5BMTc4MTcwNDEwN15BMl5BanBnXkFtZTcwNjk5NTIzMQ@@._V1_Ratio0.7273_AL_.jpg',
'name': 'Stephen J.M. Sisk'},
{'asCharacter': 'Doily / ... 2 episodes, 1999-2000',
'id': 'nm2078873',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Andre Haines'},
{'asCharacter': 'Argon Protopi / ... 2 episodes, 1996-1999',
'id': 'nm0532262',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Alan MacGillivray'},
{'asCharacter': 'Reteep / ... 2 episodes, 1997',
'id': 'nm0164996',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Shaun Clarke'},
{'asCharacter': 'Commentator / ... 2 episodes, 2001-2002',
'id': 'nm0693788',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Graham Pountney'},
{'asCharacter': 'Rexal / ... 2 episodes, 1999-2001',
'id': 'nm0925425',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Sam White'},
{'asCharacter': 'Eco Tourist #2 / ... 2 episodes, 1999-2001',
'id': 'nm0807320',
'image': 'https://imdb-api.com/images/original/MV5BOWU4MGY3YWQtNTA0Ni00YjRkLTkwZDQtZDM0NmQ5MTBkOTY2XkEyXkFqcGdeQXVyMTQ5NjcwMQ@@._V1_Ratio1.5000_AL_.jpg',
'name': 'Andy Smith'},
{'asCharacter': 'Computer / ... 2 episodes, 1999-2001',
'id': 'nm1050691',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Angela Vermeir'},
{'asCharacter': 'Bellhop / ... 2 episodes, 1996-2002',
'id': 'nm2253598',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Jack Carr'},
{'asCharacter': 'Middle aged woman / ... 2 episodes, 1999-2001',
'id': 'nm0925456',
'image': 'https://imdb-api.com/images/original/MV5BMTk1MTE2MjQ0MV5BMl5BanBnXkFtZTgwMTQyNDEwMDI@._V1_Ratio0.7273_AL_.jpg',
'name': 'Sherry White'},
{'asCharacter': '790 Robot / ... 2 episodes, 1996-1997',
'id': 'nm0676914',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Mike Petersen'},
{'asCharacter': 'Pa Gollean / ... 1 episode, 1999',
'id': 'nm0001999',
'image': 'https://imdb-api.com/images/original/MV5BMTU2NjA2NDg5Nl5BMl5BanBnXkFtZTcwOTMxNzkyOA@@._V1_Ratio0.7273_AL_.jpg',
'name': 'Maury Chaykin'},
{'asCharacter': 'Original Xev / ... 2 episodes, 1996-2000',
'id': 'nm0385694',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Lisa Hynes'},
{'asCharacter': 'Priest / ... 1 episode, 2000',
'id': 'nm0950245',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Malcolm Younger'},
{'asCharacter': 'Desh / ... 1 episode, 1999-2002',
'id': 'nm0449643',
'image': 'https://imdb-api.com/images/original/MV5BMjAxMTY4NDUyOF5BMl5BanBnXkFtZTcwNTUwOTkyMQ@@._V1_Ratio0.7727_AL_.jpg',
'name': 'Amy Kerr'},
{'asCharacter': 'Peasant 1 episode, 2001',
'id': 'nm0375821',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Jeri-Matti Helppi'},
{'asCharacter': 'Druid Girl / ... 1 episode, 1999-2001',
'id': 'nm1120797',
'image': 'https://imdb-api.com/images/original/MV5BZTYzOTE0ODQtY2MxYy00YzZlLTkzNDItY2NmM2VhOGY1M2U2XkEyXkFqcGdeQXVyMjQwMDg0Ng@@._V1_Ratio0.7273_AL_.jpg',
'name': 'Cindy Sampson'},
{'asCharacter': 'Black Pawn #3 / ... 1 episode, 2001-2002',
'id': 'nm0949734',
'image': 'https://imdb-api.com/images/original/MV5BYTkxZmU4MzMtMTUzMi00MWUzLWFhZWQtMGZlZDk3NjlkNGRmXkEyXkFqcGdeQXVyMjQwMDg0Ng@@._V1_Ratio0.7273_AL_.jpg',
'name': 'Joshua Young'},
{'asCharacter': 'C.G. 1 episode, 1999',
'id': 'nm0850969',
'image': 'https://imdb-api.com/images/original/MV5BMGM2NDA1ZjMtZmZhYS00ZmQwLTgzNjAtNTJlYTdkYTc4NTM0XkEyXkFqcGdeQXVyODQ5NjYzODk@._V1_Ratio0.7273_AL_.jpg',
'name': 'Tom Tasse'},
{'asCharacter': 'Thief / ... 1 episode, 1999-2001',
'id': 'nm0924841',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Gordon Patrick White'},
{'asCharacter': 'Dr. Kazan 1 episode, 1998',
'id': 'nm0508996',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Simon Licht'},
{'asCharacter': 'The Dark Lady 1 episode, 1999',
'id': 'nm0952801',
'image': 'https://imdb-api.com/images/original/MV5BMjE1MDk2NzI1NF5BMl5BanBnXkFtZTcwOTU3ODgyMQ@@._V1_Ratio0.7273_AL_.jpg',
'name': 'Lenore Zann'},
{'asCharacter': 'Captain Jebbed 1 episode, 1999',
'id': 'nm0282088',
'image': 'https://imdb-api.com/images/original/MV5BMjA1NjA5Njc3NF5BMl5BanBnXkFtZTcwODM1Mjg4NA@@._V1_Ratio0.7273_AL_.jpg',
'name': 'Page Fletcher'},
{'asCharacter': 'Grand Prosecutor Jihana 1 episode, 1999',
'id': 'nm0291711',
'image': 'https://imdb-api.com/images/original/MV5BNjAzNDEyNTU2NF5BMl5BanBnXkFtZTcwNjA3NDYxMw@@._V1_Ratio0.7273_AL_.jpg',
'name': 'Nina Franoszek'},
{'asCharacter': 'Brizon 1 episode, 1999',
'id': 'nm0664387',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Earl Pastko'},
{'asCharacter': 'Enox 1 episode, 1999',
'id': 'nm0081735',
'image': 'https://imdb-api.com/images/original/MV5BODk1NTk5NGItZDNhYi00Nzk1LTgwZmMtNWJjYzYyNjlmNjc2XkEyXkFqcGdeQXVyNDI0NDgzNDk@._V1_Ratio0.7273_AL_.jpg',
'name': 'Andrew Bigelow'},
{'asCharacter': 'Brother Randor 1 episode, 1999',
'id': 'nm0123672',
'image': 'https://imdb-api.com/images/original/MV5BOGM4ZjMyMTItODQxYi00ZjkyLWJhM2EtMWE0NThmZjEwMTUzXkEyXkFqcGdeQXVyMjg4MDA4Mw@@._V1_Ratio0.7273_AL_.jpg',
'name': 'Matthew Burton'},
{'asCharacter': 'Master of Ceremonies 1 episode, 1999',
'id': 'nm0916152',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Jeremy Webb'},
{'asCharacter': 'Card Carrying Druid 1 episode, 2001',
'id': 'nm0104033',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Richard Braine'},
{'asCharacter': 'Deputy Festus Trout 1 episode, 2002',
'id': 'nm1591420',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Nick Cawdron'},
{'asCharacter': 'Poet Man 1 episode, 1997',
'id': 'nm0000347',
'image': 'https://imdb-api.com/images/original/MV5BMTc5MTQ2OTYwOF5BMl5BanBnXkFtZTYwMzEzMTA1._V1_Ratio0.7273_AL_.jpg',
'name': 'Tim Curry'},
{'asCharacter': 'Smoor 1 episode, 1997',
'id': 'nm0427480',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Andy Jones'},
{'asCharacter': 'Gubby Mok 1 episode, 1999',
'id': 'nm0733500',
'image': 'https://imdb-api.com/images/original/MV5BMTk5NjgyNTAzMV5BMl5BanBnXkFtZTcwNzIwOTgxOA@@._V1_Ratio0.7273_AL_.jpg',
'name': 'Wayne Robson'},
{'asCharacter': 'Heedia 1 episode, 1999',
'id': 'nm0909763',
'image': 'https://imdb-api.com/images/original/MV5BMTQzNTM1Njc5OV5BMl5BanBnXkFtZTYwMTExMzk1._V1_Ratio0.7273_AL_.jpg',
'name': 'Mary Walsh'},
{'asCharacter': 'Tad 1 episode, 1999',
'id': 'nm0124089',
'image': 'https://imdb-api.com/images/original/MV5BMTkzODA4NDQ4Ml5BMl5BanBnXkFtZTcwMjI3MDkyMQ@@._V1_Ratio0.9091_AL_.jpg',
'name': 'Andrew Bush'},
{'asCharacter': 'Sissy Gollean 1 episode, 1999',
'id': 'nm0198359',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Susan Quinn'},
{'asCharacter': 'Aulk 1 episode, 1999',
'id': 'nm0150315',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Diego Chambers'},
{'asCharacter': 'Brother Treygor 1 episode, 1999',
'id': 'nm0459570',
'image': 'https://imdb-api.com/images/original/MV5BMzU3NGI0ZWMtZDQxNS00YmNmLWI3N2QtYWYxYTAzYzk1YWExXkEyXkFqcGdeQXVyNTM3MDMyMDQ@._V1_Ratio1.3182_AL_.jpg',
'name': 'Matthias Klimsa'},
{'asCharacter': 'Slinka 1 episode, 1999',
'id': 'nm2333298',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Barbara Schmied'},
{'asCharacter': 'Rivet 1 episode, 2000',
'id': 'nm0687084',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Polly Jo Pleasence'},
{'asCharacter': 'Lily 1 episode, 2000',
'id': 'nm0351742',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Julia Haacke'},
{'asCharacter': 'Cellphone Druid 1 episode, 2001',
'id': 'nm0160484',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'David Christoffel'},
{'asCharacter': 'Dulcibella Sternflanks 1 episode, 2002',
'id': 'nm0001180',
'image': 'https://imdb-api.com/images/original/MV5BMjEyMTQ5NTE2M15BMl5BanBnXkFtZTYwNTc2NTI2._V1_Ratio0.7727_AL_.jpg',
'name': 'Britt Ekland'},
{'asCharacter': 'Amber 1 episode, 2002',
'id': 'nm1153173',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Polly Green'},
{'asCharacter': 'Bereaved Mom 1 episode, 2002',
'id': 'nm1102594',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Kathryn Fraser'},
{'asCharacter': 'Nurse / ... 1 episode, 1999',
'id': 'nm0445757',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Sandra Keller'},
{'asCharacter': 'Junior Gollean 1 episode, 1999',
'id': 'nm2087640',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Dave Carmichael'},
{'asCharacter': 'Groo 1 episode, 1999',
'id': 'nm2057642',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Sharon Timmins'},
{'asCharacter': 'Tish 1 episode, 2000',
'id': 'nm0503011',
'image': 'https://imdb-api.com/images/original/MV5BYmRhYTBlZGQtNTA3NS00ZjRhLWIwODctMWUyOTA1ZjdiMTY2XkEyXkFqcGdeQXVyMTAwMzUyMzUy._V1_Ratio0.7273_AL_.jpg',
'name': 'Sandra S. Leonhard'},
{'asCharacter': 'Wench 1 episode, 2000',
'id': 'nm0623818',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Terry Neason'},
{'asCharacter': 'Tulip 1 episode, 2000',
'id': 'nm1066713',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Hephzibah Tintner'},
{'asCharacter': 'Minx 1 episode, 2000',
'id': 'nm2070970',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Nicole Ciroth'},
{'asCharacter': 'Colin 1 episode, 2001',
'id': 'nm0263854',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Nick Ewans'},
{'asCharacter': 'Merle 1 episode, 2001',
'id': 'nm2075949',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Michael Best'},
{'asCharacter': 'Didi Figgleshrick 1 episode, 2002',
'id': 'nm1292663',
'image': 'https://imdb-api.com/images/original/MV5BZjZjY2YwYmMtZTNiZi00MTA3LThhZDAtZjA5MjRhZGIyN2RkXkEyXkFqcGdeQXVyNTAzNzE4NTQ@._V1_Ratio0.7727_AL_.jpg',
'name': 'Celia Henebury'},
{'asCharacter': 'Wyatt 1 episode, 2002',
'id': 'nm1357378',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Mason Phillips'},
{'asCharacter': 'FBI Lieutenant 1 episode, 2002',
'id': 'nm1472220',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Donald Chisholm'},
{'asCharacter': 'Thodin 1 episode, 1996',
'id': 'nm0000960',
'image': 'https://imdb-api.com/images/original/MV5BOTQ1Mzc4YjQtY2RlMC00ZjNiLWE5NmMtZDlhYzkyOGI1MWNmXkEyXkFqcGdeQXVyMjQwMDg0Ng@@._V1_Ratio0.8182_AL_.jpg',
'name': 'Barry Bostwick'},
{'asCharacter': 'Yottskry 1 episode, 1997',
'id': 'nm0000532',
'image': 'https://imdb-api.com/images/original/MV5BMTcxMjQxNzczM15BMl5BanBnXkFtZTcwMTg3MTMwNw@@._V1_Ratio0.7273_AL_.jpg',
'name': 'Malcolm McDowell'},
{'asCharacter': 'Snik 1 episode, 1997',
'id': 'nm0937760',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Gerry Wolff'},
{'asCharacter': 'Holo Woman 1 episode, 1997',
'id': 'nm3055126',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Kate Rose'},
{'asCharacter': 'L.L. Boosh 1 episode, 1998',
'id': 'nm0687999',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Roman Podhora'},
{'asCharacter': 'Dr. Funz 1 episode, 1998',
'id': 'nm0827811',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Oliver Stern'},
{'asCharacter': 'Nool 1 episode, 1999',
'id': 'nm0755518',
'image': 'https://imdb-api.com/images/original/MV5BOTE1OTMwMzgyOF5BMl5BanBnXkFtZTcwMTQzMzIwNQ@@._V1_Ratio1.5000_AL_.jpg',
'name': 'Benjamin Sadler'},
{'asCharacter': 'Rissha 1 episode, 1999',
'id': 'nm0377286',
'image': 'https://imdb-api.com/images/original/MV5BMzFkOTRhN2UtNjBiMS00OWMwLWEyNTEtNGI4MmRhMWUxNDc0XkEyXkFqcGdeQXVyMzM4MjM0Nzg@._V1_Ratio0.7727_AL_.jpg',
'name': 'Ellen-Ray Hennessy'},
{'asCharacter': 'Kanana 1 episode, 1999',
'id': 'nm0055955',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Nikki Barnett'},
{'asCharacter': 'Skye 1 episode, 1999',
'id': 'nm0574242',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Kerry McPherson'},
{'asCharacter': 'Kyoo 1 episode, 1999',
'id': 'nm1635103',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Paul McQuillan'},
{'asCharacter': 'Hammer 1 episode, 2000',
'id': 'nm0486734',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Diane Langton'},
{'asCharacter': 'Cab 1 episode, 2000',
'id': 'nm0719013',
'image': 'https://imdb-api.com/images/original/MV5BMDBhNDVlZGYtMzYxOS00MTkwLWIxZTAtZGQyMTA2ZmZkNjFlXkEyXkFqcGdeQXVyMjA2ODMxMTc@._V1_Ratio0.7273_AL_.jpg',
'name': 'Urs Remond'},
{'asCharacter': 'Dr. Bunz 1 episode, 2000',
'id': 'nm0427226',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Udo Jolly'},
{'asCharacter': 'Daisy 1 episode, 2000',
'id': 'nm0711890',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Sabrina Rattey'},
{'asCharacter': 'Oliver 1 episode, 2001',
'id': 'nm0086691',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Peter Blake'},
{'asCharacter': 'Puck 1 episode, 2001',
'id': 'nm0290344',
'image': 'https://imdb-api.com/images/original/MV5BZTBjNjU1YmQtNmY2NS00MmM3LWIwMjUtNmVhMDc5YzQxMDcyXkEyXkFqcGdeQXVyNTEzNTE1Njc@._V1_Ratio0.7727_AL_.jpg',
'name': 'Tim Frances'},
{'asCharacter': 'Executive 1 episode, 2001',
'id': 'nm0041033',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Howard Attfield'},
{'asCharacter': 'Native American Leader 1 episode, 2001',
'id': 'nm1797077',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Agumeuay Nakanakis'},
{'asCharacter': 'Tourist 1 episode, 2001',
'id': 'nm2102947',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Danielle Dawe'},
{'asCharacter': 'Older Woman 1 episode, 2001',
'id': 'nm1083224',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Lois Brown'},
{'asCharacter': 'Josh 1 episode, 2002',
'id': 'nm1276440',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Johnny Lomas'},
{'asCharacter': 'Queen of Sheba 1 episode, 2002',
'id': 'nm1322299',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Andrulla Blanchette'},
{'asCharacter': 'Burl 1 episode, 2002',
'id': 'nm0970833',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'John Diamond'},
{'asCharacter': "Zev's Mother 1 episode, 1997",
'id': 'nm2287155',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Rachel Grover'},
{'asCharacter': 'Dr. Veezra 1 episode, 1998',
'id': 'nm0311888',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Barbara Geiger'},
{'asCharacter': 'Fruitcake 1 episode, 1999-2000',
'id': 'nm0416404',
'image': 'https://imdb-api.com/images/original/MV5BNjBiMzkxYTktNTFkYS00MTI1LThjZGQtZWYzYmJjNmExMzM3XkEyXkFqcGdeQXVyMjQwMDg0Ng@@._V1_Ratio0.7273_AL_.jpg',
'name': 'David Lewis'},
{'asCharacter': 'Calico 1 episode, 1999',
'id': 'nm0809998',
'image': 'https://imdb-api.com/images/original/MV5BMDY1ZTllZDUtMGNmYi00N2NkLWI5M2MtOGUxMDNmYzJiZjQxXkEyXkFqcGdeQXVyMjQwMDg0Ng@@._V1_Ratio0.7273_AL_.jpg',
'name': 'Stacy Smith'},
{'asCharacter': 'Lissha 1 episode, 1999',
'id': 'nm3141671',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Susanna Metzner'},
{'asCharacter': 'Older Brother 1 episode, 1999',
'id': 'nm0405949',
'image': 'https://imdb-api.com/images/original/MV5BNmU1YzU0MzEtNzEzZi00ODI0LWI3ODktOTg2YmVjMTliY2Y3XkEyXkFqcGdeQXVyMjg4MDA4Mw@@._V1_Ratio0.7273_AL_.jpg',
'name': 'Martin Höner'},
{'asCharacter': 'Gibble 1 episode, 1999',
'id': 'nm0277235',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Bruce Fillmore'},
{'asCharacter': 'New Born 1 episode, 1999',
'id': 'nm2050293',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Joe Wynn'},
{'asCharacter': 'Daffodil 1 episode, 2000',
'id': 'nm0459819',
'image': 'https://imdb-api.com/images/original/MV5BZGQ4NDA5MGEtN2RhYy00YzI4LTllOWEtMjFiNWNlZjQ5MWU2XkEyXkFqcGdeQXVyMTA1MDM4Mjk1._V1_Ratio0.7273_AL_.jpg',
'name': 'Ina Paule Klink'},
{'asCharacter': 'Socket 1 episode, 2000',
'id': 'nm0119007',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Jelena Budimir'},
{'asCharacter': 'Zin 1 episode, 2000',
'id': 'nm1558070',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Hans Brückner'},
{'asCharacter': 'Fox 1 episode, 2000',
'id': 'nm1221774',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Katrin Schrake'},
{'asCharacter': 'The Warden 1 episode, 2001',
'id': 'nm0153002',
'image': 'https://imdb-api.com/images/original/MV5BMjI0ODI3MzY0N15BMl5BanBnXkFtZTcwODE1MzIyOA@@._V1_Ratio0.7273_AL_.jpg',
'name': 'Craig Charles'},
{'asCharacter': 'Vet 1 episode, 2001',
'id': 'nm0070779',
'image': 'https://imdb-api.com/images/original/MV5BMTg0NzkyMTIyM15BMl5BanBnXkFtZTgwMDk3NDQ5ODE@._V1_Ratio0.7273_AL_.jpg',
'name': 'Jay Benedict'},
{'asCharacter': 'George 1 episode, 2001',
'id': 'nm1896146',
'image': 'https://imdb-api.com/images/original/MV5BMjkwZDAwMDYtZTg3NS00Yzk4LWE0MDMtYTBhM2U1ZjgzNzhjXkEyXkFqcGdeQXVyMzQ0MjcxNTQ@._V1_Ratio1.5000_AL_.jpg',
'name': 'Brian Buckley'},
{'asCharacter': 'Mustafa Al Hambra 1 episode, 2001',
'id': 'nm0175773',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Alexis Conran'},
{'asCharacter': 'Dale 1 episode, 2001',
'id': 'nm2076074',
'image': 'https://imdb-api.com/images/original/MV5BOGYxYjZlYzQtZDc3ZS00YzU1LWE0ZTYtODYxMzZhY2ZhZjEwXkEyXkFqcGdeQXVyMjQwMDg0Ng@@._V1_Ratio0.7273_AL_.jpg',
'name': 'Bob Dearden'},
{'asCharacter': 'Oberon 1 episode, 2001',
'id': 'nm0330499',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Patrick Gordon'},
{'asCharacter': 'Cleasby 1 episode, 2002',
'id': 'nm1140344',
'image': 'https://imdb-api.com/images/original/MV5BNjM0MjFmNzAtMGRlMC00ZWM3LTgxMTgtZjAxMDdlNTNkOTAzXkEyXkFqcGdeQXVyNTgwOTM4Mzk@._V1_Ratio1.1364_AL_.jpg',
'name': 'Rupert Evans'},
{'asCharacter': 'Haley 1 episode, 2002',
'id': 'nm2104375',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Rebecca Mordan'},
{'asCharacter': 'A.F.R. #1 1 episode, 2002',
'id': 'nm1476405',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Kevin Deagle'},
{'asCharacter': 'Orlluk 1 episode, 1997',
'id': 'nm0476508',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Hussi Kutlucan'},
{'asCharacter': 'Mrs. Deebee 1 episode, 1998',
'id': 'nm0248231',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Eva Ebner'},
{'asCharacter': 'Navigator 1 episode, 1998',
'id': 'nm0168453',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Burgandy Code'},
{'asCharacter': 'Brother Deal 1 episode, 1999',
'id': 'nm0833882',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Tom Petry Strauss'},
{'asCharacter': 'Guard 1 1 episode, 1999',
'id': 'nm0778659',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Peter Scollin'},
{'asCharacter': 'Dream Girl #1 1 episode, 1999',
'id': 'nm1561629',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Lee-Anne Lowe'},
{'asCharacter': 'Glootus 1 episode, 1999',
'id': 'nm2078717',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Karl Lewis Johnston'},
{'asCharacter': 'Guard #1 1 episode, 1999',
'id': 'nm1587988',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Robin Johnson'},
{'asCharacter': 'The Wife 1 episode, 1999',
'id': 'nm3399723',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Rosemarie Friedrich'},
{'asCharacter': 'Lynx 1 episode, 2000',
'id': 'nm1054864',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Katja Richter'},
{'asCharacter': 'ATF Agent 1 episode, 2001',
'id': 'nm0558536',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'David Matheson'},
{'asCharacter': 'Earl 1 episode, 2001',
'id': 'nm1125610',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Rejean Cournoyer'},
{'asCharacter': 'Boy 1 episode, 2001',
'id': 'nm0153011',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'David Charles'},
{'asCharacter': 'ATF Agent 1 episode, 2001',
'id': 'nm1116865',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Mike Daly'},
{'asCharacter': 'French Diplomat 1 episode, 2001',
'id': 'nm1152556',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Stan Carew'},
{'asCharacter': 'Journalist #2 1 episode, 2001',
'id': 'nm1197604',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Karen Beverly'},
{'asCharacter': 'Marconi 1 episode, 2001',
'id': 'nm1554024',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Giovanni del Vecchio'},
{'asCharacter': 'Monk 1 episode, 2002',
'id': 'nm0407033',
'image': 'https://imdb-api.com/images/original/MV5BMTQ4NjE0MzAxOF5BMl5BanBnXkFtZTcwMjIwMDg4NQ@@._V1_Ratio1.5000_AL_.jpg',
'name': 'Togo Igawa'},
{'asCharacter': 'Ryan 1 episode, 2002',
'id': 'nm1015511',
'image': 'https://imdb-api.com/images/original/MV5BMmEwYTFjYmYtNDU3YS00NmEzLWJmYzktYzE1NGI4ZDRlN2VlXkEyXkFqcGdeQXVyMjY1MTYxOA@@._V1_Ratio0.7727_AL_.jpg',
'name': 'Finlay Robertson'},
{'asCharacter': 'Mort the Mortician 1 episode, 2002',
'id': 'nm1141990',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Rory MacGregor'},
{'asCharacter': 'Secretary of Defense 1 episode, 2002',
'id': 'nm1329655',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Doug Barron'},
{'asCharacter': 'Survivalist #2 1 episode, 2002',
'id': 'nm1476430',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Shawn Duggan'},
{'asCharacter': 'Corporal Harrison Birdie 1 episode, 2002',
'id': 'nm0258211',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Dennis Envoldsen'},
{'asCharacter': 'Grullek 1 episode, 1997',
'id': 'nm0115721',
'image': 'https://imdb-api.com/images/original/MV5BMzM5MzAwNzU5OF5BMl5BanBnXkFtZTcwMTY4ODkyMQ@@._V1_Ratio1.3182_AL_.jpg',
'name': 'Hans-Dieter Brückner'},
{'asCharacter': 'Administrator 1 episode, 1998',
'id': 'nm0787635',
'image': 'https://imdb-api.com/images/original/MV5BM2E1ZWM3OGMtODUyNy00MGVjLThkZGEtNTk2NGVmZGVmZWIyXkEyXkFqcGdeQXVyMjg4MDA4Mw@@._V1_Ratio0.7273_AL_.jpg',
'name': 'Errol Shaker'},
{'asCharacter': 'Rockhound 1 episode, 1998',
'id': 'nm1053933',
'image': 'https://imdb-api.com/images/original/MV5BZTY2ZGY2MDktMTcxNS00M2JlLTlmMTAtYzZhYTUxY2Y1NDY1XkEyXkFqcGdeQXVyNjYxMTgzMzQ@._V1_Ratio0.8636_AL_.jpg',
'name': 'John Davie'},
{'asCharacter': 'Varrtan 1 episode, 1999',
'id': 'nm0199139',
'image': 'https://imdb-api.com/images/original/MV5BZDlhMWFiZjEtZjNjMC00NWQwLTk2YWQtYmZkNjkzZjBlZjYxXkEyXkFqcGdeQXVyMjQwMDg0Ng@@._V1_Ratio1.5000_AL_.jpg',
'name': 'Noah Dalton Danby'},
{'asCharacter': 'Nympho 1 1 episode, 1999',
'id': 'nm0275767',
'image': 'https://imdb-api.com/images/original/MV5BMjJiZTMyMmItZDAxYy00MWNiLWI5ZDAtYzZmM2MxZDUxZjUxXkEyXkFqcGdeQXVyMjQwMDg0Ng@@._V1_Ratio0.8182_AL_.jpg',
'name': 'C.J. Lusby'},
{'asCharacter': 'Guard 3 1 episode, 1999',
'id': 'nm0295227',
'image': 'https://imdb-api.com/images/original/MV5BOTU2ZDRlNzEtZTY3MS00ZWI2LTlhYmMtYzY3NDRhMmU1NzViXkEyXkFqcGdeQXVyMjg4MDA4Mw@@._V1_Ratio0.7273_AL_.jpg',
'name': 'Harvey Friedman'},
{'asCharacter': '792 1 episode, 1999',
'id': 'nm0614885',
'image': 'https://imdb-api.com/images/original/MV5BODk4MDNjNTgtOGYzNS00NmU1LTg2OTMtNDRiOTIzNjkzZTgxXkEyXkFqcGdeQXVyMjQwMDg0Ng@@._V1_Ratio0.9545_AL_.jpg',
'name': 'Christian Murray'},
{'asCharacter': 'Time Prophet 1 episode, 1999',
'id': 'nm2055375',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Lorraine Segato'},
{'asCharacter': 'Brother Stack / ... 1 episode, 1999',
'id': 'nm0733973',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Philippe Roche'},
{'asCharacter': 'Gold Lamé Man 1 episode, 1999',
'id': 'nm8996935',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Christian Murray'},
{'asCharacter': 'Satin 1 episode, 2000',
'id': 'nm0813896',
'image': 'https://imdb-api.com/images/original/MV5BNWI1NjA4MGYtNDY5Mi00Y2IwLTk3MWQtODk5YzhkMTk4MGIwXkEyXkFqcGdeQXVyMjUyNDk2ODc@._V1_Ratio1.3182_AL_.jpg',
'name': 'Jimmy Somerville'},
{'asCharacter': 'Bruise 1 episode, 2000',
'id': 'nm2061535',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Rose Zone'},
{'asCharacter': 'Professor Shnoog 1 episode, 2001',
'id': 'nm0581378',
'image': 'https://imdb-api.com/images/original/MV5BM2NjYTA4NjEtZjFlOS00MWZmLWI4ZWQtMWE5YzkyZGQ4MDllXkEyXkFqcGdeQXVyMTQxMjk0Mg@@._V1_Ratio1.2273_AL_.jpg',
'name': 'Clive Merrison'},
{'asCharacter': 'Uther de Glastonbury, formerly known as Nigel Bumsen 1 '
'episode, 2001',
'id': 'nm0506912',
'image': 'https://imdb-api.com/images/original/MV5BZmI2YzNhODgtOTljMS00N2I2LWI5ZDEtY2JhODRhYzFmODUxXkEyXkFqcGdeQXVyMzk3NTUwOQ@@._V1_Ratio0.7727_AL_.jpg',
'name': 'Alun Lewis'},
{'asCharacter': 'Doctor 1 episode, 2001',
'id': 'nm0322424',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'John Gleeson'},
{'asCharacter': 'Newfie 1 episode, 2001',
'id': 'nm0290126',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'David Francis'},
{'asCharacter': 'Journalist #1 1 episode, 2001',
'id': 'nm0132665',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Lee J. Campbell'},
{'asCharacter': 'Marjorie 1 episode, 2001',
'id': 'nm1495685',
'image': 'https://imdb-api.com/images/original/MV5BOTI5MzEwZmMtZTAzNS00NzY4LThkNTYtMmYxNmM1OWE4MTY2XkEyXkFqcGdeQXVyMjQwMDg0Ng@@._V1_Ratio0.7727_AL_.jpg',
'name': 'Melanie Harris'},
{'asCharacter': 'Chad 1 episode, 2001',
'id': 'nm0189344',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'James Crossley'},
{'asCharacter': 'Local 1 episode, 2001',
'id': 'nm0227767',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Philip Dinn'},
{'asCharacter': 'Remo 1 episode, 2002',
'id': 'nm0191526',
'image': 'https://imdb-api.com/images/original/MV5BMTIyNjU4MTcyOF5BMl5BanBnXkFtZTcwODMxMDcyMQ@@._V1_Ratio0.7273_AL_.jpg',
'name': 'Seán Cullen'},
{'asCharacter': 'Devlin 1 episode, 2002',
'id': 'nm0361354',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Richard Hanson'},
{'asCharacter': 'Middle Aged Son 1 episode, 2002',
'id': 'nm0572557',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Geoffrey McLean'},
{'asCharacter': 'Brunnen-G General 1 episode, 1997',
'id': 'nm0559668',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Rainer Matsutani'},
{'asCharacter': 'Kuk 1 episode, 1997',
'id': 'nm0944178',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Arno Wyzniewski'},
{'asCharacter': 'Berg 1 episode, 1998',
'id': 'nm0225525',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Ian T. Dickinson'},
{'asCharacter': 'Rat II 1 episode, 1999',
'id': 'nm0920574',
'image': 'https://imdb-api.com/images/original/MV5BMjE3MjUzMDI0MF5BMl5BanBnXkFtZTcwNTU4MjYzOA@@._V1_Ratio0.7727_AL_.jpg',
'name': 'Milton Welsh'},
{'asCharacter': 'Liggum 1 episode, 1999',
'id': 'nm0271452',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Thorsten Feller'},
{'asCharacter': 'Dream Girl #3 1 episode, 1999',
'id': 'nm1605092',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Amy Lonergan'},
{'asCharacter': 'Nympho 2 1 episode, 1999',
'id': 'nm1604338',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Alison McMullin'},
{'asCharacter': 'Consort 1 episode, 1999',
'id': 'nm1093209',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Paul Day'},
{'asCharacter': 'Judge 1 episode, 1999',
'id': 'nm0802766',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Dick Sircom'},
{'asCharacter': 'Guard #3 1 episode, 1999',
'id': 'nm1581249',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Adrienne Horton'},
{'asCharacter': 'First Balloonist 1 episode, 2000',
'id': 'nm1284951',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Peter Baylis'},
{'asCharacter': 'Father Borscht 1 episode, 2001',
'id': 'nm0420383',
'image': 'https://imdb-api.com/images/original/MV5BMTM5NDc0OTA3M15BMl5BanBnXkFtZTcwNTA5NzkxMw@@._V1_Ratio0.7727_AL_.jpg',
'name': 'Lionel Jeffries'},
{'asCharacter': 'Titania 1 episode, 2001',
'id': 'nm0585278',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Mick Walter'},
{'asCharacter': 'Rooster 1 episode, 2001',
'id': 'nm1243577',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Jim Fowler'},
{'asCharacter': 'Produce Manager 1 episode, 2001',
'id': 'nm1197484',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Ken Shipley'},
{'asCharacter': 'Studio Guard 1 episode, 2001',
'id': 'nm2808969',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Tom Haney'},
{'asCharacter': 'General Klebstock 1 episode, 2002',
'id': 'nm0002243',
'image': 'https://imdb-api.com/images/original/MV5BMTM2ZWQ0MTctOTE2NS00ODc1LTg2NGQtZTY1MWJjNzczNjM1XkEyXkFqcGdeQXVyMjQwMDg0Ng@@._V1_Ratio0.7727_AL_.jpg',
'name': 'Sam Douglas'},
{'asCharacter': 'Joey 1 episode, 2002',
'id': 'nm1853701',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Mike Durling'},
{'asCharacter': 'Feppo 1 episode, 1997-1999',
'id': 'nm0352138',
'image': 'https://imdb-api.com/images/original/MV5BMTg1NzgzNTc3Ml5BMl5BanBnXkFtZTcwNjEyMTEzMQ@@._V1_Ratio0.7273_AL_.jpg',
'name': 'Michael Habeck'},
{'asCharacter': 'Nurse 1 episode, 1998',
'id': 'nm0018774',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Tatjana Alexander'},
{'asCharacter': 'Dead Female Body 1 episode, 1999',
'id': 'nm0281674',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Gabi Fleming'},
{'asCharacter': 'Hologram Guard 1 episode, 1999',
'id': 'nm0372682',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Lori Heath'},
{'asCharacter': 'Young Copying Brother 1 episode, 1999',
'id': 'nm2078407',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Adrian Mattiske'},
{'asCharacter': 'Peach 1 episode, 2000',
'id': 'nm0827048',
'image': 'https://imdb-api.com/images/original/MV5BZTQxM2E0YjUtMmRkMi00ZTlmLWIwNGUtZGZlMzk0YzA1NTBjXkEyXkFqcGdeQXVyNzM0OTE4NTM@._V1_Ratio0.9091_AL_.jpg',
'name': 'Janaya Stephens'},
{'asCharacter': 'Renfield 1 episode, 2001',
'id': 'nm0145290',
'image': 'https://imdb-api.com/images/original/MV5BMTczNTcwMjYzNF5BMl5BanBnXkFtZTgwMDcyNjc0MzE@._V1_Ratio1.3182_AL_.jpg',
'name': 'Keith-Lee Castle'},
{'asCharacter': 'Surgeon 1 episode, 2001',
'id': 'nm0676500',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Jeremy Peters'},
{'asCharacter': 'Secret Service Agent 1 episode, 2001',
'id': 'nm1795894',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Jason Hemsworth'},
{'asCharacter': 'Goth Prisoner 1 episode, 2001',
'id': 'nm1478121',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Andrea Dymond'},
{'asCharacter': 'Colonel Donald K. Gore 1 episode, 2002',
'id': 'nm0721866',
'image': 'https://imdb-api.com/images/original/MV5BMTY2MTUwNzUxNF5BMl5BanBnXkFtZTYwMzI3MzEz._V1_Ratio0.7273_AL_.jpg',
'name': 'Michael J. Reynolds'},
{'asCharacter': 'Older Husband 1 episode, 2002',
'id': 'nm1151991',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'William Parsons'},
{'asCharacter': 'Geekette 1 episode, 2002',
'id': 'nm0551072',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Nancy Marshall'},
{'asCharacter': 'Fat Man 1 episode, 1999',
'id': 'nm0172635',
'image': 'https://imdb-api.com/images/original/MV5BNTZmNDczNTYtOWM2MS00MjQyLTk4NjctOTRiMmI0Mjg0MGY1XkEyXkFqcGdeQXVyNDAwMDMzOQ@@._V1_Ratio0.7273_AL_.jpg',
'name': 'Rick Collins'},
{'asCharacter': 'Bound Man 1 episode, 1999',
'id': 'nm2074189',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Greg Cormier'},
{'asCharacter': 'Bodyguard 1 episode, 1999',
'id': 'nm3411715',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Thomas Arnicke'},
{'asCharacter': 'Pearl 1 episode, 2000',
'id': 'nm0611148',
'image': 'https://imdb-api.com/images/original/MV5BMTk3NTk5NDUwMF5BMl5BanBnXkFtZTcwMTQyNzMzOA@@._V1_Ratio0.7273_AL_.jpg',
'name': 'Wanja Mues'},
{'asCharacter': 'Pear 1 episode, 2000',
'id': 'nm0658437',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Robyn Palmer'},
{'asCharacter': 'Doris 1 episode, 2001',
'id': 'nm0410306',
'image': 'https://imdb-api.com/images/original/MV5BN2NhZmZlN2QtYjAwZi00ZmRjLWExOTgtNWJkYTcyMzg4NGNjXkEyXkFqcGdeQXVyMTA0MTE4NjUw._V1_Ratio0.7727_AL_.jpg',
'name': 'Martha Irving'},
{'asCharacter': 'Guard #2 1 episode, 2001',
'id': 'nm1254510',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Travis Ferris'},
{'asCharacter': 'FBI Agent #1 1 episode, 2002',
'id': 'nm0495717',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Kevin LeBlanc'},
{'asCharacter': 'Older Wife 1 episode, 2002',
'id': 'nm0690857',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Mary Alvena Poole'},
{'asCharacter': 'ATF Officer 1 episode, 2002',
'id': 'nm1417670',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Paul Jessen'},
{'asCharacter': 'Gorrett 1 episode, 1997',
'id': 'nm2294406',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Jim Petrie'},
{'asCharacter': 'First Babe 1 episode, 1999',
'id': 'nm0629437',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Terry Nicholas'},
{'asCharacter': 'Bodyguard 1 episode, 1999',
'id': 'nm0611004',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Al Mueller'},
{'asCharacter': 'Plum 1 episode, 2000',
'id': 'nm0029569',
'image': 'https://imdb-api.com/images/original/MV5BMTYzMDA1MTA1M15BMl5BanBnXkFtZTcwNDc2ODczMQ@@._V1_Ratio0.7273_AL_.jpg',
'name': 'Roberta Angelica'},
{'asCharacter': 'Silk 1 episode, 2000',
'id': 'nm0853640',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Roger Tebb'},
{'asCharacter': 'Leroy 1 episode, 2001',
'id': 'nm0537631',
'image': 'https://imdb-api.com/images/original/MV5BN2VkOWZjYmItMGFmYi00MWFhLWE2NWYtODU4YjgzNDEzNzFjXkEyXkFqcGdeQXVyNjUxMjc1OTM@._V1_Ratio0.7273_AL_.jpg',
'name': 'Robert Maillet'},
{'asCharacter': 'Father Pickle 1 episode, 2001',
'id': 'nm0446392',
'image': 'https://imdb-api.com/images/original/MV5BMTk0NTc2MzgzMF5BMl5BanBnXkFtZTgwMzg1MjU2MjE@._V1_Ratio1.3182_AL_.jpg',
'name': 'Frank Kelly'},
{'asCharacter': 'Nelson 1 episode, 2001',
'id': 'nm1071266',
'image': 'https://imdb-api.com/images/original/MV5BMTQ3NzM0MzgxNl5BMl5BanBnXkFtZTcwOTU5OTMzMQ@@._V1_Ratio0.8182_AL_.jpg',
'name': 'Richard Hards'},
{'asCharacter': 'Gypsy Servant 1 episode, 2001',
'id': 'nm1468537',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Arthur Spray'},
{'asCharacter': 'Chief Justice 1 episode, 2001',
'id': 'nm2087449',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Bill Jessome'},
{'asCharacter': 'Slave Girl 88 1 episode, 2002',
'id': 'nm0002872',
'image': 'https://imdb-api.com/images/original/MV5BOTUzMTI5NWUtNzg5MS00ZjA3LWIwYzItZjNmMzQ4MjkxMDA5XkEyXkFqcGdeQXVyMTQ3NDM0OQ@@._V1_Ratio0.9091_AL_.jpg',
'name': 'Kelsa Kinsly'},
{'asCharacter': 'Rod 1 episode, 2002',
'id': 'nm2007079',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Jesse Lund'},
{'asCharacter': 'Twin Daughter 1 episode, 2002',
'id': 'nm2009828',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Stephanie Redding'},
{'asCharacter': 'Kyyra 1 episode, 1997',
'id': 'nm0222208',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Sherry Devanney'},
{'asCharacter': 'Second Babe 1 episode, 1999',
'id': 'nm0939225',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Lisa Wong'},
{'asCharacter': 'Male Customer 1 episode, 1999',
'id': 'nm2122404',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Dave Maddeaux'},
{'asCharacter': 'Bodyguard 1 episode, 1999',
'id': 'nm3399554',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Mirko Szabo'},
{'asCharacter': 'Cherry 1 episode, 2000',
'id': 'nm1050717',
'image': 'https://imdb-api.com/images/original/MV5BMzdlNTgzNDUtNjkzYS00Mjc1LTg1YjMtNmExNzc3MmI4NjgxXkEyXkFqcGdeQXVyNTM3MDMyMDQ@._V1_Ratio1.3182_AL_.jpg',
'name': 'Mika Ward'},
{'asCharacter': 'Lace 1 episode, 2000',
'id': 'nm0874503',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Georg Tryphon'},
{'asCharacter': 'Count Dracul 1 episode, 2001',
'id': 'nm0822062',
'image': 'https://imdb-api.com/images/original/MV5BMjAwODgyMjI3Nl5BMl5BanBnXkFtZTcwNzQ2NzkxOA@@._V1_Ratio0.7273_AL_.jpg',
'name': 'John Standing'},
{'asCharacter': 'Biff 1 episode, 2001',
'id': 'nm0654334',
'image': 'https://imdb-api.com/images/original/MV5BZTYxYzk2MzEtNmE4Ni00NDU2LWIxYzUtNmYzMDM0Yjc4ZDYwXkEyXkFqcGdeQXVyMjQwMDg0Ng@@._V1_Ratio0.7727_AL_.jpg',
'name': 'Chris Owens'},
{'asCharacter': 'Sub-Warden Heidi 1 episode, 2001',
'id': 'nm0371593',
'image': 'https://imdb-api.com/images/original/MV5BNzBhNTUxOTktNjNmNi00NGE3LWI1NzItOTRiOTZhMGFkZjI0XkEyXkFqcGdeQXVyMjQwMDg0Ng@@._V1_Ratio0.9091_AL_.jpg',
'name': 'Hattie Hayridge'},
{'asCharacter': 'Marge 1 episode, 2001',
'id': 'nm0531626',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Bette MacDonald'},
{'asCharacter': 'Eco Tourist #1 1 episode, 2001',
'id': 'nm0498883',
'image': 'https://imdb-api.com/images/original/MV5BZjBkMTM5MjMtOWRmNC00NGI0LWEzMTktYjAzNzZkMjY4NmE1XkEyXkFqcGdeQXVyMTk1Nzk0MjM@._V1_Ratio0.7727_AL_.jpg',
'name': 'Madeleine Lefebvre'},
{'asCharacter': 'Lieutenant 1 episode, 2001',
'id': 'nm1528150',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Gareth Miller'},
{'asCharacter': 'The Mummy - Draco 1 episode, 2002',
'id': 'nm2017161',
'image': 'https://imdb-api.com/images/original/MV5BMTY5ODk0NTY3MV5BMl5BanBnXkFtZTgwODc1NDQ0NzE@._V1_Ratio1.2273_AL_.jpg',
'name': 'John Lebar'},
{'asCharacter': 'Tad 1 episode, 2002',
'id': 'nm1011675',
'image': 'https://imdb-api.com/images/original/MV5BYTA3ZjJkM2EtNDY0NS00MDQ4LWIwYjMtNDU1MmE0NWNhODE4XkEyXkFqcGdeQXVyNjUxMjc1OTM@._V1_Ratio0.7727_AL_.jpg',
'name': 'Ryan McCluskey'},
{'asCharacter': 'Dead Twin Daughter 1 episode, 2002',
'id': 'nm2012057',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Nicole Redding'},
{'asCharacter': 'Survivalist 1 episode, 2002',
'id': 'nm2006836',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Cleveland Sauer'},
{'asCharacter': 'Bleeding Cleric / ... 1 episode, 1997',
'id': 'nm0764643',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Joel Sapp'},
{'asCharacter': 'Bodyguard 1 episode, 1999',
'id': 'nm3410735',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Sebastian Kokot'},
{'asCharacter': 'Guard #1 1 episode, 2000',
'id': 'nm2072290',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Renate Spona'},
{'asCharacter': 'Leo 1 episode, 2001',
'id': 'nm0531704',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Ed Macdonald'},
{'asCharacter': 'Elderly Lady 1 episode, 2001',
'id': 'nm0390761',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Maggie Holland'},
{'asCharacter': 'Valentino 1 episode, 2001',
'id': 'nm0518486',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Nunzio Lombardo'},
{'asCharacter': 'Chip 1 episode, 2001',
'id': 'nm0605045',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Stephen Morgan'},
{'asCharacter': 'Store Guard 1 episode, 2001',
'id': 'nm2097292',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Dan Steeves'},
{'asCharacter': 'Stress Counselor 1 episode, 2002',
'id': 'nm0573909',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Marguerite McNeil'},
{'asCharacter': 'Frankie 1 episode, 2002',
'id': 'nm1851160',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Dominic Pallotta'},
{'asCharacter': 'Bodyguard 1 episode, 1999',
'id': 'nm3411004',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Oliver Stolz'},
{'asCharacter': 'Guard #2 1 episode, 2000',
'id': 'nm0935867',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Sabine Winterfeldt'},
{'asCharacter': 'Cedric 1 episode, 2001',
'id': 'nm1090815',
'image': 'https://imdb-api.com/images/original/MV5BOWViMDI0OGEtOGZkZS00OGZkLWEzYWYtNGJlZWY0NTk0M2E1XkEyXkFqcGdeQXVyMTc1MDkyMjI@._V1_Ratio1.0000_AL_.jpg',
'name': "Ross O'Hennessy"},
{'asCharacter': 'Cardinal Meinpo Duftet 1 episode, 2001',
'id': 'nm0513180',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Alec Linstead'},
{'asCharacter': 'Bartender 1 episode, 2001',
'id': 'nm1352678',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Douglas Mayr'},
{'asCharacter': 'Sheriff 1 episode, 2001',
'id': 'nm0716112',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'James Reeve'},
{'asCharacter': 'Piccalina 1 episode, 2002',
'id': 'nm1131200',
'image': 'https://imdb-api.com/images/original/MV5BOTY5YzFkMGUtMTlkYi00NWI4LTgxMGUtOWVhNzAyOTEyMmJkXkEyXkFqcGdeQXVyMjQwMDg0Ng@@._V1_Ratio0.7273_AL_.jpg',
'name': 'Laura Patch'},
{'asCharacter': 'Cabbie 1 episode, 2002',
'id': 'nm0816991',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Jeremiah Sparks'},
{'asCharacter': 'Guard #3 1 episode, 2000',
'id': 'nm0405952',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Thordis König'},
{'asCharacter': 'Businessman 1 episode, 2001',
'id': 'nm0894857',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'David Verrey'},
{'asCharacter': 'Bob 1 episode, 2001',
'id': 'nm0682642',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Justin Pierre'},
{'asCharacter': 'Mom 1 episode, 2001',
'id': 'nm0572638',
'image': 'https://imdb-api.com/images/original/MV5BM2MwMWZjMmEtZTU0ZC00MTkwLTlmNGItODY0NmNmYmM2NDA2XkEyXkFqcGdeQXVyNTM3MDMyMDQ@._V1_Ratio1.3182_AL_.jpg',
'name': 'Rhonda McLean'},
{'asCharacter': 'Truro 1 episode, 2001',
'id': 'nm8150015',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Julia Moore'},
{'asCharacter': 'Shower Nude #1 1 episode, 2001',
'id': 'nm1478452',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Lydia Klenck'},
{'asCharacter': 'Love Slave Wrestler 1 episode, 2002',
'id': 'nm1814933',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Tricia Taylor'},
{'asCharacter': 'Rex 1 episode, 2002',
'id': 'nm2005249',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Jason Sweeney'},
{'asCharacter': 'Dancing Twin #2 1 episode, 1997',
'id': 'nm2299792',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Lenuta Sim'},
{'asCharacter': 'Guard #4 1 episode, 2000',
'id': 'nm0278919',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Gina Fischer'},
{'asCharacter': 'Chief Guard 1 episode, 2000',
'id': 'nm1152032',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Craig Wood'},
{'asCharacter': 'Hank 1 episode, 2001',
'id': 'nm0799272',
'image': 'https://imdb-api.com/images/original/MV5BMWQ3ZjlhMzItYTZhOS00YTAwLWI1NTUtNjlkOTEzN2FjY2RjXkEyXkFqcGdeQXVyMjQwMDg0Ng@@._V1_Ratio0.7273_AL_.jpg',
'name': 'Silvio Simac'},
{'asCharacter': 'Phoebe 1 episode, 2001',
'id': 'nm0710254',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Heather Rankin'},
{'asCharacter': 'Cobra 1 episode, 2001',
'id': 'nm0669300',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'John Pearson'},
{'asCharacter': 'Shower Nude #2 1 episode, 2001',
'id': 'nm1478575',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Beth Mahaney'},
{'asCharacter': 'Junior 1 episode, 2001',
'id': 'nm2046002',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Bruce Murphy'},
{'asCharacter': 'Slave Girl 24 1 episode, 2002',
'id': 'nm0902794',
'image': 'https://imdb-api.com/images/original/MV5BZDdkN2U4YzQtMmJjNC00M2MxLWE3ZmYtYzg1NjkzMWY5NGU1XkEyXkFqcGdeQXVyMzk2NTI4Ng@@._V1_Ratio1.0000_AL_.jpg',
'name': 'Heidi von Palleske'},
{'asCharacter': 'Supervisor 1 episode, 2002',
'id': 'nm0956757',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Matt Zimmerman'},
{'asCharacter': 'Dancing Twin #1 1 episode, 1997',
'id': 'nm2294343',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Mariana Sim'},
{'asCharacter': 'Guard #5 1 episode, 2000',
'id': 'nm2067386',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Jana Piehl'},
{'asCharacter': 'Passenger 1 episode, 2001',
'id': 'nm1254810',
'image': 'https://imdb-api.com/images/original/MV5BYTZjNjJiZDEtMTA4NC00MmExLThmZjktYzE2ZThkYTk5ZjQ4XkEyXkFqcGdeQXVyMTI1MzM5MTYw._V1_Ratio0.9545_AL_.jpg',
'name': 'Jamie Sparks'},
{'asCharacter': 'Guard #1 1 episode, 2001',
'id': 'nm1053322',
'image': 'https://imdb-api.com/images/original/MV5BMzE4Nzc1NjQ0MV5BMl5BanBnXkFtZTcwODEyMjY3MQ@@._V1_Ratio0.7273_AL_.jpg',
'name': 'Peter James'},
{'asCharacter': 'Jacques 1 episode, 2001',
'id': 'nm2087442',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Raymond Solomon'},
{'asCharacter': 'Sharon 1 episode, 2001',
'id': 'nm0727218',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Maisie Rillie'},
{'asCharacter': 'Ridolan 1 episode, 2001',
'id': 'nm1254521',
'image': 'https://imdb-api.com/images/original/MV5BMTg3NjAyMjYwNl5BMl5BanBnXkFtZTYwNDU5Njgy._V1_Ratio1.0000_AL_.jpg',
'name': 'Andy Gatjen'},
{'asCharacter': 'Themselves 1 episode, 2001',
'id': 'nm3568557',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Shooglenifty'},
{'asCharacter': 'Pierce 1 episode, 2001',
'id': 'nm2077627',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Rupert Solomon'},
{'asCharacter': 'Malik 1 episode, 2001',
'id': 'nm2084755',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Marcos Troy'},
{'asCharacter': 'Self - Band 1 episode, 2001',
'id': 'nm5362965',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Malcolm Cosbie'},
{'asCharacter': 'Yoyal 1 episode, 1997',
'id': 'nm2296127',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'David Woods'},
{'asCharacter': "Farley's Assistant 1 episode, 2001",
'id': 'nm1107340',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Georgia Zaris'},
{'asCharacter': 'Cmdr. Bricklin 1 episode, 2001',
'id': 'nm0841741',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Jim Swansburg'},
{'asCharacter': 'Self - Band 1 episode, 2001',
'id': 'nm1333883',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Garry Finlayson'},
{'asCharacter': 'Self - Band 1 episode, 2001',
'id': 'nm2100136',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Craig Gaskin'},
{'asCharacter': 'Sergeant 1 episode, 1996',
'id': 'nm0531799',
'image': 'https://imdb-api.com/images/original/MV5BNDM1ZGY5ZWMtOTc5Yi00M2ZmLTlkYWItMjE5Y2QzNzAzMDUyXkEyXkFqcGdeQXVyMTQ4MjE0Mw@@._V1_Ratio1.0455_AL_.jpg',
'name': 'Josh MacDonald'},
{'asCharacter': 'Self - Band 1 episode, 2001',
'id': 'nm1178545',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Angus Grant'},
{'asCharacter': 'Self - Band 1 episode, 2001',
'id': 'nm2376149',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Ian MacLeod'},
{'asCharacter': 'Self - Band 1 episode, 2001',
'id': 'nm2102097',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Conrad Molleson'},
{'asCharacter': 'Cluster General 1 episode, 1996',
'id': 'nm2253009',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Horst Ulan'},
{'asCharacter': 'Fore Shadow Officer 1 episode, 1996',
'id': 'nm0877346',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Stephen J. Turnbull'},
{'asCharacter': 'Cleric 1 episode, 1996',
'id': 'nm2253244',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Andrew Smith'},
{'asCharacter': 'Computer 1 episode, 1996',
'id': 'nm2252814',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Janice Evens'},
{'asCharacter': 'Brain No. 14 1 episode, 1996',
'id': 'nm0800286',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Marty Simon'},
{'asCharacter': 'Holo Prosecutor 1 episode, 1996-1997',
'id': 'nm0724526',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Elizabeth Richardson'},
{'asCharacter': 'Slab Prisoner 1 episode, 1996',
'id': 'nm0752135',
'image': 'https://imdb-api.com/images/original/MV5BMTBlNjBmYzUtZTM3OS00NzU1LTk1NTEtZjk0YTMyMjU0YmZjXkEyXkFqcGdeQXVyMTAwMzUyMzUy._V1_Ratio0.7273_AL_.jpg',
'name': 'Joseph Rutten'},
{'asCharacter': 'Holo Official 1 episode, 1996',
'id': 'nm0746849',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Chris Rowntree'},
{'asCharacter': 'Bog 1 episode, 1997',
'id': 'nm0000442',
'image': 'https://imdb-api.com/images/original/MV5BMTI5MjE4MTg3MV5BMl5BanBnXkFtZTYwMjk0Mzgy._V1_Ratio0.8636_AL_.jpg',
'name': 'Rutger Hauer'},
{'asCharacter': 'Wist 1 episode, 1997',
'id': 'nm0414271',
'image': 'https://imdb-api.com/images/original/MV5BNjc5NDc4MzgtOTdjYS00MWMzLWIzMmYtNTgyOTRkZDQzOGVlXkEyXkFqcGdeQXVyMTAwMzUyMzUy._V1_Ratio0.7273_AL_.jpg',
'name': 'Doreen Jacobi'},
{'asCharacter': 'Air Force One Attendant 1 episode, 2002',
'id': 'nm1473933',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Darcy Lindzon'},
{'asCharacter': "Duke's Guard / ... (uncredited) 2 episodes, 1999-2000",
'id': 'nm1470619',
'image': 'https://imdb-api.com/images/original/MV5BZDgwZDg4NGEtOWU5NS00MTQ5LWEzOGMtNGRkNTUxZTQxM2FmXkEyXkFqcGdeQXVyMjQwMDg0Ng@@._V1_Ratio0.7273_AL_.jpg',
'name': 'David Alexander Miller'},
{'asCharacter': 'ATF Agent (uncredited) 2 episodes, 2001',
'id': 'nm2431076',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'J. William Grantham'},
{'asCharacter': '790 (uncredited) 1 episode, 1996',
'id': 'nm0183950',
'image': 'https://imdb-api.com/images/original/MV5BYWZhNmYzZDYtYTc2Ny00ZWQxLThhMTQtYzhmYTg4NzQxM2Y4XkEyXkFqcGdeQXVyMjQwMDg0Ng@@._V1_Ratio0.7273_AL_.jpg',
'name': 'Rick Courtney'},
{'asCharacter': 'Additional Girl (uncredited) 1 episode, 2000',
'id': 'nm1859486',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Alexander Baier'},
{'asCharacter': 'Klassp (uncredited) 1 episode, 2000',
'id': 'nm2005732',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Craig Dawson'},
{'asCharacter': 'Background (uncredited) 1 episode, 2001',
'id': 'nm0572623',
'image': 'https://imdb-api.com/images/original/nopicture.jpg',
'name': 'Nikki Timmons'},
{'asCharacter': 'French Diplomat (uncredited) 1 episode, 2001',
'id': 'nm1404336',
'image': 'https://imdb-api.com/images/original/MV5BNmU1YmQ5MDMtYmIxNS00MzYzLWE1M2UtOGQ0MTIzOTM0N2RiXkEyXkFqcGdeQXVyOTY1MjI3NA@@._V1_Ratio0.7727_AL_.jpg',
'name': 'Hank White'}]
###Markdown
Notice that the `asCharacter` field contains a number of different pieces of data as a single string, including the character name.This kind of "free-form" text data is notoriously challenging to parse... Exercise 2In the code cell below, write a python function that takes a string input (the text from `asCharacter` field)and returns the number of episodes, if available, or None.Hints:* notice this is a numeric value followed by the word "episodes"* recall str.split() and str.isdigit() and other string build-ins.Add unit tests to cover as many cases from the `actors` data set above as you can.
###Code
def episode_count(asCharString):
str_parse = asCharString['asCharacter'].split(' ', -3)
episodes = str_parse[-3]
print('This character appeared in', episodes, 'episodes.')
if episodes
for i in actors:
episode_count(i)
###Output
This character appeared in 61 episodes.
This character appeared in 61 episodes.
This character appeared in 57 episodes.
This character appeared in 55 episodes.
This character appeared in 46 episodes.
This character appeared in 23 episodes.
This character appeared in 16 episodes.
This character appeared in 8 episodes.
This character appeared in 13 episodes.
This character appeared in 10 episodes.
This character appeared in 7 episodes.
This character appeared in 8 episodes.
This character appeared in 3 episodes.
This character appeared in 5 episodes.
This character appeared in 6 episodes.
This character appeared in 7 episodes.
This character appeared in 7 episodes.
This character appeared in 5 episodes.
This character appeared in 5 episodes.
This character appeared in 6 episodes.
This character appeared in 5 episodes.
This character appeared in 4 episodes.
This character appeared in 5 episodes.
This character appeared in 5 episodes.
This character appeared in 5 episodes.
This character appeared in 5 episodes.
This character appeared in 5 episodes.
This character appeared in 1 episodes.
This character appeared in 4 episodes.
This character appeared in 4 episodes.
This character appeared in 4 episodes.
This character appeared in 5 episodes.
This character appeared in 5 episodes.
This character appeared in 4 episodes.
This character appeared in 4 episodes.
This character appeared in 4 episodes.
This character appeared in 4 episodes.
This character appeared in 4 episodes.
This character appeared in 3 episodes.
This character appeared in 3 episodes.
This character appeared in 1 episodes.
This character appeared in 4 episodes.
This character appeared in 4 episodes.
This character appeared in 4 episodes.
This character appeared in 4 episodes.
This character appeared in 4 episodes.
This character appeared in 4 episodes.
This character appeared in 4 episodes.
This character appeared in 4 episodes.
This character appeared in 4 episodes.
This character appeared in 3 episodes.
This character appeared in 3 episodes.
This character appeared in 3 episodes.
This character appeared in 2 episodes.
This character appeared in 2 episodes.
This character appeared in 2 episodes.
This character appeared in 2 episodes.
This character appeared in 2 episodes.
This character appeared in 2 episodes.
This character appeared in 2 episodes.
This character appeared in 2 episodes.
This character appeared in 2 episodes.
This character appeared in 2 episodes.
This character appeared in 2 episodes.
This character appeared in 2 episodes.
This character appeared in 2 episodes.
This character appeared in 2 episodes.
This character appeared in 2 episodes.
This character appeared in 2 episodes.
This character appeared in 2 episodes.
This character appeared in 2 episodes.
This character appeared in 2 episodes.
This character appeared in 2 episodes.
This character appeared in 2 episodes.
This character appeared in 2 episodes.
This character appeared in 2 episodes.
This character appeared in 2 episodes.
This character appeared in 2 episodes.
This character appeared in 2 episodes.
This character appeared in 2 episodes.
This character appeared in 2 episodes.
This character appeared in 2 episodes.
This character appeared in 2 episodes.
This character appeared in 2 episodes.
This character appeared in 1 episodes.
This character appeared in 2 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 2 episodes.
This character appeared in 2 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
This character appeared in 1 episodes.
###Markdown
Exercise 3In the code cell below, write a python function that takes a string input (the text from `asCharacter` field)and returns just the character name. This one may be even a little harder!Hints:* notice the character name is usually followed by a forward slash, `/`* don't worry if your algorithm does not perfectly parse every character's name --it may not really be possible to correclty handle all cases because the field format does not follow consistent rulesAdd unit tests to cover as many cases from the `actors` data set above as you can.
###Code
# Your code here
###Output
_____no_output_____
###Markdown
Exercise 4Using the functions you developed above, define 2 list comprehensions that:* create list of 2 tuples with (actor name, character description) for actors in Lexx (from `asCharacter` field)* create a list of dictionaries, with keys: 'actor' and 'character' for the same dataHint: this is a very simple problem - the goal is to learn how to build these lists using a comprehension.Pretty print (pprint) your lists to visually verify the results.
###Code
# your code here
###Output
_____no_output_____
###Markdown
Ćwiczenie 1
###Code
import csv
import numpy as np
import matplotlib.pyplot as plt
def read_csv_file_data(csv_file):
args = []
values = []
with open(csv_file, newline='') as file:
reader = csv.reader(file, delimiter=',')
for row in reader:
_x, _y = row
args.append(int(float(_x)))
values.append(float(_y))
return np.array(args), np.array(values)
CSV_FILE_NAME = './testfile.csv'
csv_X, csv_y = read_csv_file_data(CSV_FILE_NAME)
print(csv_X.shape)
print(csv_y.shape)
plt.figure()
plt.plot(csv_X)
plt.plot(csv_y)
del CSV_FILE_NAME
###Output
_____no_output_____
###Markdown
numpy.polyfit
###Code
poly_order = 11
poly_1 = np.polyfit(csv_X, csv_y, poly_order)
print(poly_1)
def predict_using_polynomial(poly_fit, x):
_y = 0
for i in range(0, len(poly_fit) - 1):
_exp = len(poly_fit) - i - 1
_coeff = poly_fit[i]
_y += _coeff * (x ** _exp)
_y += poly_fit[len(poly_fit) - 1]
return _y
for i in range(5500, 5515):
_pred = predict_using_polynomial(poly_1, i)
print( _pred, csv_y[i] )
del poly_1
del _pred
###Output
_____no_output_____
###Markdown
sklearn.pipeline.Pipeline
###Code
import sklearn.preprocessing as skp
import sklearn.linear_model as skl
import sklearn.pipeline as skpl
poly_transform = [
('polynomial', skp.PolynomialFeatures(degree=poly_order)),
('modal', skl.LinearRegression())
]
csv_Xr = csv_X.reshape(-1, 1)
pipe = skpl.Pipeline(poly_transform)
pipe.fit(csv_Xr, csv_y)
poly_pred = pipe.predict(csv_Xr)
sorted_zip = sorted(zip(csv_X, poly_pred))
X_poly, poly_pred = zip(*sorted_zip)
plt.figure(figsize=(10,6))
plt.scatter(csv_X, csv_y, s=15)
plt.plot(X_poly, poly_pred, color='k')
plt.show()
del pipe
del sorted_zip
del X_poly
del poly_pred
del csv_Xr
del poly_order
###Output
_____no_output_____
###Markdown
sklearn.linear_model.LinearRegression
###Code
import sklearn.model_selection as sks
import sklearn.preprocessing as skp
poly_order = 19
X_train, X_test, y_train, y_test = sks.train_test_split(csv_X, csv_y, test_size=0.6)
poly_reg = skp.PolynomialFeatures(degree=poly_order)
csv_X_r = csv_X.reshape(-1, 1)
X_ = poly_reg.fit_transform(csv_X_r)
X_test_ = poly_reg.fit_transform(X_test.reshape(-1, 1))
lin_reg = skl.LinearRegression(normalize=True)
lin_reg.fit(X_, csv_y)
print(lin_reg.coef_)
print(lin_reg.intercept_)
print()
print(lin_reg.predict(X_test_)[0:4])
def visualize_polynomial_regression(data_x, data_y, reg_lin, reg_poly):
plt.scatter(data_x, data_y, color='b')
_pred_reg = reg_poly.fit_transform(data_x)
plt.plot(data_x, reg_lin.predict( _pred_reg ), color='orange')
plt.show()
l = 5400
r = 6000
visualize_polynomial_regression(csv_X_r[l:r], csv_y[l:r], lin_reg, poly_reg)
l = 5500
r = l + 15
visualize_polynomial_regression(csv_X_r[l:r], csv_y[l:r], lin_reg, poly_reg)
def predict_and_print(a, b, lr, pr):
for _i in range(a, b):
_p = [[_i]]
_pred = lr.predict(pr.fit_transform( _p ))
print(_pred, csv_y[_i])
predict_and_print(l, r, lin_reg, poly_reg)
del X_train
del X_test
del X_test_
del y_train
del y_test
del X_
del l
del r
del poly_order
del lin_reg
del poly_reg
del poly_transform
###Output
_____no_output_____
###Markdown
linear_regression()
###Code
import pandas as pd
def linear_regression(x, y):
xt = x.T
_tmp = xt.dot(x)
_tmp = np.linalg.inv(_tmp)
_tmp = _tmp.dot(xt)
_theta = _tmp.dot(y)
return _theta
training_data = pd.DataFrame(
data=[ [1,1], [2,2], [4,4] ],
columns=['x1', 'y']
)
training_data.insert(0, 'x0', np.ones(3))
X_lr = training_data[['x0', 'x1']]
y_lr = training_data[['y']]
theta = linear_regression(X_lr, y_lr)
print(theta)
def build_df(x, y):
_df = []
for _i in range(0, len(x)):
_df.append( [x[_i], y[_i]] )
return pd.DataFrame(data=_df, columns=['x1', 'y'])
df = build_df(csv_X, csv_y)
df.insert(0, 'x0', np.ones(df.shape[0]))
X_lr = df[['x0', 'x1']]
y_lr = df[['y']]
theta = linear_regression(X_lr, y_lr)
print(theta)
theta = linear_regression(csv_X_r, csv_y)
print(theta)
poly_order = 19
poly_reg = skp.PolynomialFeatures(degree=poly_order)
X_ = poly_reg.fit_transform(csv_X_r)
theta = linear_regression(X_, csv_y)
print(theta)
def predict_linear_regression(ft, th):
return ft.dot(th.T)
for i in range(5500, 5515):
ft_1 = poly_reg.fit_transform([[i]])
pred_1 = predict_linear_regression(ft_1, theta)
print(pred_1 + 28_800, csv_y[i])
del df
del theta
del X_lr
del y_lr
del training_data
del X_
del ft_1
del poly_reg
del poly_order
del pred_1
del csv_X_r
del csv_X
del csv_y
###Output
_____no_output_____
###Markdown
Ćwiczenie 2
###Code
import csv
import numpy as np
import pandas as pd
def read_csv_file_data_2(csv_file):
lines = []
with open(csv_file, newline='') as file:
reader = csv.reader(file, delimiter=',')
header = next(reader)
for row in reader:
lines.append(row)
return pd.DataFrame(data=lines, columns=header)
CSV_FILE_NAME = './../../data/GoesGold/ElectionData.csv'
csv_ed = read_csv_file_data_2(CSV_FILE_NAME)
print(csv_ed.shape)
def reshape_election_data(ed):
_tmp = ed[ed['territoryName'] == 'Território Nacional']
_tmp = ed[['TimeElapsed', 'Party', 'Percentage', 'Votes', 'Mandates']]
_tmp.loc[:, 'TimeElapsed'] = pd.to_numeric(_tmp['TimeElapsed'])
_tmp.loc[:, 'Percentage'] = pd.to_numeric(_tmp['Percentage'])
_tmp.loc[:, 'Votes'] = pd.to_numeric(_tmp['Votes'])
return _tmp
ed_n = reshape_election_data(csv_ed)
print(ed_n.dtypes)
def filter_through_parties(_ed_n):
_parties = tuple(set(_ed_n['Party']))
_ed_p_set = []
for party in _parties:
_tmp = _ed_n[_ed_n['Party'] == party]
_tmp = _tmp[['TimeElapsed', 'Votes']]
_ed_p_set.append(_tmp)
return _ed_p_set, _parties
ed_p, parties = filter_through_parties(ed_n)
del CSV_FILE_NAME
del csv_ed
del ed_n
###Output
_____no_output_____
###Markdown
regresja liniowa
###Code
import sklearn.linear_model as skl
def build_data_by_fit_and_predict(_ed_p, _x_test):
_predictions = []
for _i in range(0, len(_ed_p)):
_dt = _ed_p[_i]
_dt_X_r = np.array(_dt['TimeElapsed']).reshape(-1, 1)
_dt_y = np.array(_dt['Votes'])
_lr = skl.LinearRegression()
_lr.fit(_dt_X_r, _dt_y)
_predict = _lr.predict(_x_test)
_predictions.append(_predict)
return _predictions
X_test = [[j] for j in range(0, 265)]
predictions = build_data_by_fit_and_predict(ed_p, X_test)
import matplotlib.pyplot as plt
def plot_predictions(_ed_p, _x_test, _predictions, _parties, fs=(10,6)):
for _i in range(0, len(_ed_p)):
plt.figure(figsize=fs)
plt.scatter(_ed_p[_i]['TimeElapsed'], _ed_p[_i]['Votes'], s=15)
plt.plot(_x_test, _predictions[_i], color='k')
plt.title(_parties[_i])
plt.show()
plot_predictions(ed_p, X_test, predictions, parties)
del X_test
###Output
_____no_output_____
###Markdown
?
###Code
# del ed_p
# del parties
# del predictions
###Output
_____no_output_____
###Markdown
Lab 3 - Séries temporais
###Code
#install.packages('tseries')
library(tseries)
#install.packages("FitAR")
library(FitAR)
#install.packages("forecast")
library(forecast)
###Output
Registered S3 methods overwritten by 'ggplot2':
method from
[.quosures rlang
c.quosures rlang
print.quosures rlang
Registered S3 methods overwritten by 'forecast':
method from
fitted.fracdiff fracdiff
residuals.fracdiff fracdiff
Attaching package: ‘forecast’
The following object is masked from ‘package:FitAR’:
BoxCox
###Markdown
Tarefa 7.1
###Code
library(data.table)
CBE <- fread('https://filebin.net/elh72va9571tc3hu/CBE.txt?t=ml8ogqxe', header = T)
#CBE <- read.table('https://ae4.tidia-ae.usp.br/access/content/group/d9eaaa2c-4085-4503-8e32-4bc0279da0d1/CBE.txt', header = T)
#edit(CBE)
Elec.ts <- ts(CBE[,3], start = 1958, freq = 12)
Beer.ts <- ts(CBE[,2], start = 1958, freq = 12)
Choc.ts <- ts(CBE[,1], start = 1958, freq = 12)
plot(cbind(Elec.ts, Beer.ts,Choc.ts))
Elec.decom <- decompose(Elec.ts, type="mult")
Elec.Trend <- Elec.decom$trend
Elec.Seasonal <- Elec.decom$seasonal
Elec.random <- Elec.decom$random
ZElec <- ts(Elec.random[7:390])
layout(1:3)
plot(ts(Elec.ts))
plot(diff(ts(Elec.ts)))
plot(ZElec)
layout(1:2)
acf(ZElec, lag.max = 30)
pacf(ZElec, lag.max = 30)
fit1 <- arima(ZElec, order = c(1, 0, 1))
fit2 <- arima(ZElec, order = c(1, 0, 0))
fit3 <- arima(ZElec, order = c(2, 0, 0))
BIC(fit1, fit2, fit3)
arima(ZElec, order = c(1, 0, 0))
arima(ZElec, order = c(1, 0, 1))
arima(ZElec, order = c(2, 0, 0))
layout(1:2)
acf(fit2$residuals, lag.max = 30)
pacf(fit2$residuals, lag.max = 30)
# For time-series prediction,
# predict.ar, predict.Arima, predict.arima0, # # predict.HoltWinters,
# predict.StructTS.
prev<-predict(fit2,6)
#par(mfrow=c(1,2))
ts.plot(window(ZElec, start=370),main='Previsão ZElec - Modelo AR(1)',
prev$pred,
prev$pred+1.96*prev$se,
prev$pred-1.96*prev$se,
col=c(1,2,2,2), lty=c(1,1,2,2))
prev
# Pacote de previsão alternativo
library(forecast)
fZElec=forecast(fit2, h=6)
fZElec
ts.plot(fZElec)
###Output
_____no_output_____
###Markdown
Análise de Séries Temporais com R
###Code
data(EuStockMarkets)
ftse=(EuStockMarkets[,4])
plot(ftse)
components.ts = decompose(ftse)
plot(components.ts)
x = ftse- components.ts$seasonal
ftse_stationary <- diff(x, differences=1)
plot(ftse_stationary)
layout(1:2)
acf(ftse_stationary,lag.max = 40)
pacf(ftse_stationary,lag.max = 40)
fitARIMA = arima(ftse, order=c(1,1,1),seasonal = list(order =
c(1,0,0), period = 12),method="ML")
fitARIMA
res=fitARIMA$residuals
plot(res)
layout(1:2)
acf(res,lag.max = 40)
pacf(res,lag.max = 40)
Box.test(res,type="Ljung-Box")
fit <- auto.arima(ZElec)
plot(forecast(fit,h=20))
###Output
_____no_output_____
###Markdown
Advanced Statistical Inference Gaussian Process Regression 1 Aims- To sample from a Gaussian process prior distribution.- To implement Gaussian process inference for regression.- To use the above to observe samples from a Gaussian process posterior distribution.- To evaluate how different hyperparameter settings impact model quality.
###Code
from pprint import pprint
import numpy as np
import numpy.linalg as linalg
import matplotlib
import matplotlib.pyplot as plt
import scipy.io as sio
from scipy import stats
import scipy
%matplotlib inline
x = np.random.uniform(-20,80,200)
t = np.sin(np.exp(0.03 * x))
plt.figure(figsize=(15,5))
ax = plt.gca()
ax.scatter(x,t)
ax.grid()
plt.show()
###Output
_____no_output_____
###Markdown
3. Sampling from GP Prior
###Code
def compute_kernel(x1,x2,lengthscale,variance):
return variance * np.exp(-(np.linalg.norm(x1 - x2)**2)/(2*lengthscale*lengthscale))
def compute_kernel_wrapper(x1,x2,lengthscale,variance,noise=0):
K = np.array([[compute_kernel(x,y,lengthscale,variance) for x in x1] for y in x2])
return K if noise == 0 else K + noise * np.identity(len(K))
K = compute_kernel_wrapper(x,x,10,2)
mu = np.zeros_like(x)
r = np.random.multivariate_normal(mu,K,size=4)
plt.figure(figsize=(15,5))
ax = plt.gca()
ax.scatter(x,t,s=20)
ax.scatter(x,r[0],s=10)
ax.scatter(x,r[1],s=10)
ax.scatter(x,r[2],s=10)
ax.scatter(x,r[3],s=10)
plt.grid()
plt.show()
###Output
_____no_output_____
###Markdown
4. GP Inference
###Code
def inv_prod(X,y):
L = np.linalg.cholesky(X)
B = scipy.linalg.solve_triangular(X,y,lower=True)
return scipy.linalg.solve_triangular(X.T,B,lower=False)
def gp_inference(obs_x, obs_t, new_x, lengthscale,variance,noise):
n = len(obs_x)
kern_obs = compute_kernel_wrapper(obs_x,obs_x,lengthscale,variance,noise=10**(-6))
#cholesky
L = np.linalg.cholesky(kern_obs)
B = scipy.linalg.solve_triangular(L,obs_t,lower=True)
alpha = scipy.linalg.solve_triangular(L.T,B,lower=False)
kern_obs_pred = compute_kernel_wrapper(obs_x,new_x,lengthscale,variance,noise)
kern_pred = compute_kernel_wrapper(new_x, new_x,lengthscale,variance,noise)
post_m = kern_obs_pred.dot(alpha)
v = np.dot(kern_obs_pred,np.linalg.inv(L))
post_v = kern_pred - np.dot(v,np.transpose(v))
return post_m,post_v
obs_x = np.random.choice(x,20,replace=False,)
obs_t = np.sin(np.exp(0.03 * obs_x))
mu,v = gp_inference(obs_x,obs_t,x,10,2,0)
r = np.random.multivariate_normal(mu,v,size=50)
###Output
/usr/local/lib/python3.6/site-packages/ipykernel/__main__.py:1: RuntimeWarning: covariance is not positive-semidefinite.
if __name__ == '__main__':
###Markdown
5. Sampling from GP Posterior
###Code
plt.figure(figsize=(15,10))
ax = plt.gca()
ax.scatter(x,t,s=20)
for _ in r:
ax.scatter(x,_,s=2)
plt.grid()
plt.show()
###Output
_____no_output_____
###Markdown
Cho số nguyên age chỉ tuổi của một con mèo được nhập vào từ bàn phím. Bạn hãy viết chương trình để kiểm tra xem con mèo của bạn là già hay còn trẻ. Nếu tuổi của con mèo dưới 5 (age <5), thì hiển thị ra màn hình dòng chữ Your cat is young, ngược lại nếu tuổi của con mèo lớn hơn hoặc bằng 5 tuổi thì hiển thị ra Your cat is old.
###Code
age = int(input())
if age < 5:
print("Your cat is young")
else :
print("Your cat is old")
###Output
_____no_output_____
###Markdown
Cho số nguyên temperature chỉ nhiệt độ được nhập từ bàn phím, bạn hãy viết chương trình in ra màn hình theo các yêu cầu như sau:
Nếu temperature >= 100, in ra dòng chữ Stay at home and enjoy a good movie trên màn hình.
Nếu temperature >= 92, in ra dòng chữ Stay at home trên màn hình.
Nếu temperature = 75, in ra dòng chữ Go outside and enjoy the weather trên màn hình.
Nếu temperature < 0, in ra dòng chữ It's cool outside trên màn hình.
Ngoài các ràng buộc như trên thì hiển thị Let's go to school.
###Code
temperature = int(input())
if temperature >= 100:
print("Stay at home and enjoy a good movie")
elif temperature >= 92:
print("Stay at home")
elif temperature == 75:
print("Go outside and enjoy the weather")
elif temperature <= 0:
print("It's cool outside")
else:
print("Let's go to school")
###Output
_____no_output_____
###Markdown
Cho trước 3 số nguyên x, y, z được từ bàn phím. Bạn hãy viết chương trình hiển thị ra màn hình theo yêu cầu sau:
Nếu x là số chẵn, kiểm tra xem y có lớn hơn hoặc bằng 20 hay không. Nếu y >= 20, in ra dòng chữ y is greater than or equal to 20; ngược lại, in ra dòng chữ y is less than 20.
Nếu x là số lẻ, kiểm tra xem z có lớn hơn hoặc bằng 30 hay không. Nếu z >= 30, in ra dòng chữ z is greater than or equal to 30; ngược lại, in ra dòng chữ z is less than 30.
###Code
x = int(input())
y = int(input())
z = int(input())
if x % 2 == 0:
if y >= 20:
print("y is greater than or equal to 20")
else:
print("y is less than 20")
else:
if z >= 30:
print("z is greater than or equal to 30")
else:
print("z is less than 30")
###Output
_____no_output_____
###Markdown
Viết chương trình Python tính giá trị trung bình (avg) của ba biến a, b, c nhập từ bàn phím (a, b, c là ba số tự nhiên) với điều kiện như sau:
Nếu avg > a và avg > b thì hiển thị The average value is greater than both a and b
Nếu avg > a và avg > c thì hiển thị The average value is greater than both a and c
Nếu avg > b và avg > c thì hiển thị The average value is greater than both b and c
Nếu avg chỉ lớn hơn a thì hiển thị The average value is greater than a
Nếu avg chỉ lớn hơn b thì hiển thị The average value is greater than b
Nếu avg chỉ lớn hơn c thì hiển thị The average value is greater than c
###Code
a = int(input())
b = int(input())
c = int(input())
avg = (a + b + c) / 3
if avg > a and avg > b:
print("The average value is greater than both a and b")
elif avg > a and avg > c:
print("The average value is greater than both a and c")
elif avg > b and avg > c:
print("The average value is greater than both b and c")
elif avg > a:
print("The average value is greater than a")
elif avg > b:
print("The average value is greater than b")
elif avg > c:
print("The average value is greater than c")
###Output
_____no_output_____
###Markdown
Cho số nguyên age chỉ tuổi của vật nuôi được nhập từ bàn phím, bạn hãy hiển thị ra màn hình theo yêu cầu sau:
Nếu age <= 0 thì hiển thị "This can hardly be true"
Nếu age == 1 thì hiển thị "About 1 human year"
Nếu age == 2 thì hiển thị "About 2 human years"
Nếu age > 2 thì hiển thị "Over 5 human years.
Ví dụ nếu bạn nhập age = 3 thì hiển thị "Over 5 human years"
Nếu bạn nhập age = 1 thì hiển thị "About 1 human year"
###Code
age = int(input())
if age <= 0:
print("This can hardly be true")
elif age == 1:
print("About 1 human year")
elif age == 2:
print("About 2 human years")
elif age > 2:
print("Over 5 human years")
###Output
_____no_output_____
###Markdown
create data frame
###Code
df= pd.DataFrame({'Stunden': [1, 1, 1.5, 2, 2.5, 2.5, 2.5, 3, 3.5 ,3.5 ,3.5 ,4 , 4.5], 'Punkte': [0.5, 1.5, 1, 1.5, 1.5, 2.5, 3, 2, 1.5, 2, 2.5, 2, 2.5]})
df.head()
###Output
_____no_output_____
###Markdown
Making a scatter plot
###Code
import matplotlib.pyplot as plt
plt.scatter(df.Stunden, df.Punkte)
plt.xlabel("Stunden ")
plt.ylabel("Punkte ")
plt.title("ML-Uebung")
plt.show()
import seaborn
import sklearn
###Output
_____no_output_____
###Markdown
Lab 3: Forecasting Competition - Predicting Gold Price Instructionsrubric={mechanics:5} You will receive marks for correctly submitting this assignment. To submit this assignment you should:1. Push your assignment to your GitHub repository. **Paste URL here**2. Upload the lab `.ipynb` file to Gradescope. 3. Double check if all the plots are rendered properly on Gradescope and the autograder returns your score.4. If your notebook is too heavy to be rendered on Gradescope, please attach a `.pdf` as well. ImportsYou might need to `conda install yfinance`
###Code
import yfinance as yf
import numpy as np
import pandas as pd
import warnings
warnings.filterwarnings('ignore')
import matplotlib.pyplot as plt
from statsmodels.tsa.api import ETSModel
from statsmodels.tsa.arima.model import ARIMA
from statsmodels.tsa.statespace.sarimax import SARIMAX
from statsmodels.tsa.ar_model import AutoReg
from statsmodels.tsa.stattools import adfuller
from sklearn.metrics import mean_absolute_error
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
from sklearn.metrics import mean_absolute_percentage_error
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import train_test_split
plt.style.use("ggplot")
plt.rcParams.update({"font.size": 14, "axes.labelweight": "bold", "lines.linewidth": 2})
###Output
_____no_output_____
###Markdown
Forecasting Competitionrubric={viz:10,reasoning:60,accuracy:30} It's Week 3 - so we have a lighter lab this week. In fact, you can spend as little or as much time as you want on this lab! We will be having a little forecasting competition! Background and Tasks In this week, we are going to have a live forecasting competition to predict the daily closing gold price from March 14th - March 18th. - You are provided with a real-time gold price dataset that refresh every day from Monday to Friday. - You are allowed to use as much or as little historical data as you want.- You are allowed to use any forecasting/ML/deep learning techniquesYour tasks in this lab are simple:1. Predict the daily closing gold price from March 14th - March 18th. Store it in a dataframe called `gold_predictions`2. Make a plot of the training data and your predictions using any plotting library you wish. 3. Your predictions will be evaluated 1 week after your lab's deadline.In addition, please explain:- Explain how far back did you use the historical data for training and why?- Explain how you pre-process the data and how you engineer your features- Explain which forecasting techniques did you use and why- How you choose your parameters- How did you deal with outliers?- How do you evaluate your model performance & model fit?- Reflect on the challenges that you encounter when working on this task DatasetThe dataset will refresh itself every weekday, so make sure to re-run the model on Saturday before submitting your results
###Code
gold_df = yf.download('GC=F',
start='2019-01-01', # YOU CAN CHANGE THIS
end='2022-03-12', # DO NOT CHANGE THIS
progress=False)
gold_df['Close'].plot(title="Gold daily closing price", figsize=(12,8),ylabel='$ USD')
gold_df
gold_df
gold_df = gold_df.reset_index()
train = gold_df[gold_df["Date"]<"2022-03-10"]
test = gold_df[gold_df["Date"]>="2022-03-10"]
###Output
_____no_output_____
###Markdown
PredictionsStore your predictions in this dataframe
###Code
# Test set
days = pd.date_range('2022-03-14', '2022-03-18', freq='D')
gold_predictions = pd.DataFrame({'Date': days,
'Close_predict': [np.NaN]*5})
gold_predictions= gold_predictions.set_index('Date')
gold_predictions
# Validation set
days_valid = pd.date_range('2022-03-10', '2022-03-13', freq='D')
gold_predictions = pd.DataFrame({'Date': days_valid,
'Close_predict': [np.NaN]*4})
gold_predictions= gold_predictions.set_index('Date')
gold_predictions
###Output
_____no_output_____
###Markdown
Evaluation Following in the footsteps of the [M4 time series competition](https://www.sciencedirect.com/science/article/pii/S0169207019301128), submissions will be evaluated based on the average of two metrics:1. Symmetric mean absolute percentage error (MAPE)$$\text{sMAPE}=\frac{2}{h}\sum_{t=n+1}^{n+h}\frac{|y_t-\hat{y_t}|}{|y_t|+|\hat{y_t}|}*100(\%)$$2. Mean absolute scaled error (MASE)$$\text{MASE}=\frac{1}{h}\frac{\sum_{t=n+1}^{n+h}|y_t-\hat{y_t}|}{\frac{1}{n-1}\sum_{t=2}^{n}|y_t-y_{t-1}|}$$Where $y_t$ is the value of the series at time $t$, $\hat{y_t}$ is the forecast at time $t$, $h$ is the forecast horizon, $n$ is the number of training samples. GradingAccuracy: 30%Reasoning: 60%Visualizations: 10%In addition, I will also build my own model and submit it by Saturday. I am not gonna be able to see the test set until March 19th so I have no control over how the results will look like. If your model can beat mine, you get 5% bonus points PrizesBased on accuracy - **1st**: 100% on Lab 1, Lab 2, and Lab 3.- **2nd**: 100% on Lab 1, Lab 2, and Lab 3.- **3rd**: 100% on Lab 3. Your Code Goes Here
###Code
def s_mape(y_pred, y):
cal = abs(y - y_pred) / (abs(y) - abs(y_pred))
return 2 * np.mean(cal) * 100
# def mase(y_pred, y, h):
# num = np.sum(abs(y - y_pred))
# den = np.sum(abs())
# return (1 / h) * ( num / den)
def _naive_forecasting(actual: np.ndarray, seasonality: int = 1):
return actual[:-seasonality]
def mase(actual: np.ndarray, predicted: np.ndarray, seasonality: int = 1):
return mean_absolute_error(actual, predicted) / mean_absolute_error(actual[seasonality:], _naive_forecasting(actual, seasonality))
average = pd.DataFrame({'Date': days_valid,
"Close_predict": train['Close'].iloc[-5:].mean()})
naive = pd.DataFrame({'Date': days_valid,
"Close_predict": train['Close'].iloc[-1]})
drift = pd.DataFrame({'Date': days_valid,
"Close_predict": train['Close'].iloc[-1]})
slope = (train["Close"].iloc[-1] - train["Close"].iloc[-4:])
drift["Close_predict"] += np.full_like(drift["Close_predict"], slope).cumsum()
average
naive
drift
###Output
_____no_output_____
###Markdown
ARIMA
###Code
train_df = train[["Date","Close"]]
train_df.info()
plot_acf(train_df["Close"]);
plot_pacf(train_df["Close"]);
adfuller(train_df["Close"])
train_df = train_df.diff().dropna()
adfuller(train_df["Close"])
plot_acf(train_df["Close"]);
plot_pacf(train_df["Close"]);
###Output
/Users/valliakella/opt/anaconda3/envs/mds574/lib/python3.9/site-packages/statsmodels/graphics/tsaplots.py:348: FutureWarning: The default method 'yw' can produce PACF values outside of the [-1,1] interval. After 0.13, the default will change tounadjusted Yule-Walker ('ywm'). You can use this method now by setting method='ywm'.
warnings.warn(
###Markdown
ARIMA p = 1, d = 1, q = 0
###Code
model = ARIMA(train["Close"], order=(1,0,0))
results = model.fit()
results.summary()
###Output
_____no_output_____
###Markdown
Machine Learning Feature Engineering
###Code
train
def feature_engineering(df):
df["rolling_mean"] = df["Close"].rolling(window=2).mean()
df["rolling_mean_2"] = df["Close"].rolling(window=3).mean()
df["lag_1"] = df["Close"].shift(1)
df["lag_2"] = df["Close"].shift(2)
df["High-Low"] = df["High"] - df["Low"]
df["Open-High"] = df["High"] - df["Low"]
df["Low-Open"] = df["Open"] - df["Low"]
return df
train = feature_engineering(train)
train = train.dropna()
X_train = train.drop(columns=['Close', 'Adj Close'])
y_train = train['Close']
#lags = 2
#last_observations = df.iloc[-1, :lag].to_numpy()
model = RandomForestRegressor()
model.fit(X_train, y_train)
# #test_ump["Unemployed_pred_RF"] = recursive_forecast(last_observations, model, n=len(test_ump.index)).ravel()
X_train.columns
test = feature_engineering(test)
test["rolling_mean"].iloc[0] = train["rolling_mean"].iloc[-1]
test["rolling_mean_2"].iloc[0] = train["rolling_mean_2"].iloc[-1]
test["lag_1"].iloc[0] = train["lag_1"].iloc[-1]
test["lag_2"].iloc[0] = train["lag_2"].iloc[-1]
X_test = test.drop(columns=["Close", "Adj Close"])
y_test = test["Close"]
X_test.columns
y_pred = model.predict(X_test)
y_pred
y = y_test.values
y
s_mape(y, y_pred)
mase(y, y_pred)
###Output
_____no_output_____
###Markdown
Zadanie 1Dany jest słownik student={'imie':'Jan', 'nazwisko':'kowalski','wiek':25, 'wzrost':188, 'waga':80, 'miasto':'Toruń'}* Wypisz jego elementy w postaci "klucz -> wartość "* Zmień 'wzrost' na 182 * Dodaj klucz 'wynik matury' z dowolną wartością* Usuń klucz (i wartość) 'miasto'
###Code
student={'imie':'Jan', 'nazwisko':'kowalski','wiek':25, 'wzrost':188, 'waga':80, 'miasto':'Toruń'}
for klucz in student.keys():
print(klucz+'->'+str(student[klucz]))
student['wzrost']=182
student
student['wynik matury']=20
del student['miasto']
student
###Output
_____no_output_____
###Markdown
Zadanie 2Dane są dwie listy równej długościklucze=['klucz1','klucz2','inny klucz', 'test']wartosci=[1,2,5,1]Utwórz w sposób zautomatyzowany (nie ręcznie) słownik, który kolejnym kluczom przypisze kolejne wartości.
###Code
klucze=['klucz1','klucz2','inny klucz', 'test']
wartosci=[1,2,5,1]
nowy=zip(klucze,wartosci)
list(lista)
dict(nowy)
###Output
_____no_output_____
###Markdown
Zadanie 3Napisz funkcję obliczającą $n$-ty wyraz ciągu zadanego rekurencyjnie1. $a_0=1$, $a_{k+1}=2a_k$ dla $k\geq 0$2. $b_0=0$, $b_1=1$, $b_{k+2}=b_{k+1}+b_k$ dla $k\geq 0$
###Code
def ciag(n):
if n==0:
return 1
else:
return 2*ciag(n-1)
ciag(5)
###Output
_____no_output_____
###Markdown
Sympy
###Code
from sympy import *
sin(30)
import math
math.sin(30)
x,y=symbols('x,y')
x
y
cos(x)**2+sin(x)**2
simplify(_)
solve(2*x-5)
wyr=x**2+5*x+3
wyr.subs(x,1)
sin(30).evalf()
wyr.diff(x)
f=symbols('f',cls=Function)
g=Function('g')
ODE=f(x).diff(x)-f(x)
dsolve(ODE)
integrate(wyr,(x,0,1))
plot(wyr,(x,0,5))
###Output
_____no_output_____
###Markdown
Zadanie 4Napisz funkcję $pochodna(funkcja,punkt)$, która oblicza z definicji pochodną danej funkcji w punkcie. Korzystając ze swojej funkcji oblicz* pochodną funkcji $e^{x^2}$ w punkcie $1$* pochodną funkcji $x*\ln(\sqrt(x))$ w punkcie $1$Porównaj wyniki do tych uzyskanych za pomocą metody diff
###Code
from sympy import *
def pochodna(f,x,a):
h=symbols('h')
return limit((f.subs(x,a+h)-f.subs(x,a))/h,h,0)
pochodna(y**2,y,1)
###Output
_____no_output_____
###Markdown
Zadanie domowea) Napisz funkcję obliczającą wartość wielomianu interpolacyjnego Lagrange'a w zadanym punkcie. Funkcja powinna przyjmować następujące argumenty:X - tablicę wartości xi ,Y - tablicę wartości yi ,x - punkt, w którym liczymy wartość wielomianu.b) Dodaj opcjonalny argument do powyższej funkcji, który pozwoli wyświetlić wzór interpolacyjny Lagrange'a w postaci symbolicznej.c) sporządź wykres otrzymanego wielomianu na podstawie symbolicznego wzoru z b)d) wybierz dwie funkcje: wielomian stopnia 5 i inną funkcję niebędącą wielomianem. Sporządź ich aproksymacje za pomocą 4 wybranych punktów. Porównaj wykresy oryginalnych funkcji i ich przybliżeń. Sformułuj wnioski.
###Code
###Output
_____no_output_____
###Markdown
Simple linear regression Import the data [pandas](https://pandas.pydata.org/) provides excellent data reading and querying module,[dataframe](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html), which allows you to import structured data and perform SQL-like queries. Here we imported some house price records from [Trulia](https://www.trulia.com/?cid=sem|google|tbw_br_nat_x_x_nat!53f9be4f|Trulia-Exact_352364665_22475209465_aud-278383240986:kwd-1967776155_260498918114_). For more about extracting data from Trulia, please check [my previous tutorial](https://www.youtube.com/watch?v=qB418v3k2vk).
###Code
import pandas
df = pandas.read_excel('house_price.xlsx')
df[:10]
###Output
_____no_output_____
###Markdown
Prepare the data We want to use the price as the dependent variable and the area as the independent variable, i.e., use the house areas to predict the house prices
###Code
X = df['area']
print (X[:10])
X_reshape = X.values.reshape(-1,1) # reshape the X to a 2D array
print (X_reshape[:10])
y = df['price']
###Output
0 1541
1 1810
2 1456
3 2903
4 2616
5 3850
6 1000
7 920
8 2705
9 1440
Name: area, dtype: int64
[[1541]
[1810]
[1456]
[2903]
[2616]
[3850]
[1000]
[ 920]
[2705]
[1440]]
###Markdown
[sklearn](http://scikit-learn.org/stable/) provides a [split](http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html) function that can split the data into training data and testing data.
###Code
import sklearn
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X_reshape,y, test_size = 0.3) # put 30% data as the testing data
print ('number of training data:',len(X_train),len(y_train))
print ('number of testing data:',len(X_test),len(y_test))
###Output
number of training data: 28 28
number of testing data: 13 13
###Markdown
Train the model Use the [Linear Regression](http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html) to estimate parameters from the training data.
###Code
from sklearn import linear_model
slr = linear_model.LinearRegression() #create an linear regression model objective
slr.fit(X_train,y_train) # estimate the patameters
print('beta',slr.coef_)
print('alpha',slr.intercept_)
###Output
beta [99.0653637]
alpha 103007.2821439009
###Markdown
Evaluate the model Let's calculate the [mean squared error](http://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_squared_error.htmlsklearn.metrics.mean_squared_error) and the [r square](http://scikit-learn.org/stable/modules/generated/sklearn.metrics.r2_score.htmlsklearn.metrics.r2_score) of the model based on the testing data.
###Code
from sklearn.metrics import mean_squared_error, r2_score
y_predict = slr.predict(X_test) # predict the Y based on the model
mean_squared_error = mean_squared_error(y_test,y_predict) # calculate mean square error
r2_score = r2_score(y_test,y_predict) #calculate r square
print ('mean square error:',mean_squared_error )
print ('r square:',r2_score )
###Output
mean square error: 68539924787.35116
r square: -0.043685817412512984
###Markdown
Visualize the model We use the [matplotlib](https://matplotlib.org/) to visualize our data.
###Code
import matplotlib.pyplot as plt
%matplotlib inline
plt.scatter(X_test, y_test, color='black') # create a scatterplot to visualize the test data
plt.plot(X_test, y_predict, color='blue', linewidth=3) # add a line chart to visualize the model
plt.xlabel('area')
plt.ylabel('price')
plt.show()
###Output
_____no_output_____
###Markdown
переделать!!!! надо написать все через tkinter
###Code
def create_window():
x = 1500 #int(input('Введите ширину картинки: '))
y = 1500 #int(input('Введите высоту картинки: '))
return gr.GraphWin('MyPic',x,y)
def draw_horizon(pic):
x,y = pic.getWidth(),pic.getHeight()
sky_color = gr.color_rgb(50,50,120)
ground_color = gr.color_rgb(80,120,80)
sky = gr.Rectangle(gr.Point(0,0),gr.Point(x,y//2))
sky.setFill(sky_color)
ground = gr.Rectangle(gr.Point(0,y//2),gr.Point(x,y))
ground.setFill(ground_color)
sky.draw(pic)
ground.draw(pic)
def draw_moon(pic):
x,y = pic.getWidth(),pic.getHeight()
moon_color = gr.color_rgb(255,255,204)
moon = gr.Circle(gr.Point(x//4*3,y//4),x//8)
moon.setFill(moon_color)
moon.draw(pic)
def draw_clouds(pic):
x,y = pic.getWidth(),pic.getHeight()
for i in range(8):
corner1_x = random.randrange(-x//3*2,x-x//6)
corner1_y = random.randrange(0,y//2-y//10)
corner1 = gr.Point(corner1_x, corner1_y)
corner2 = corner1.clone()
corner2.move(x//3*2,y//10)
cloud = gr.Oval(corner1,corner2)
random_grey = 32 * random.randrange(3,6)
cloud_color = gr.color_rgb(random_grey,random_grey,random_grey)
cloud.setFill(cloud_color)
cloud.draw(pic)
def draw_starship(pic):
x,y = pic.getWidth(),pic.getHeight()
lamps = 6
base_corner1 = gr.Point(x*0.05,y*0.25)
base_corner2 = base_corner1.clone()
base_corner2.move(x*0.5,y*0.15)
head_corner1 = base_corner1.clone()
head_corner1.move(x*0.1,-y*0.01)
head_corner2 = head_corner1.clone()
head_corner1.move(x*0.3,y*0.1)
starship_base = gr.Oval(base_corner1,base_corner2)
starship_base.setFill('grey')
starship_head = gr.Oval(head_corner1,head_corner2)
starship_head.setFill('lightgrey')
starship_base.draw(pic)
starship_head.draw(pic)
for i in range(lamps):
lamp_corner1 = base_corner1.clone()
lamp_corner1.move((base_corner2.x - base_corner1.x)//lamps*i,
(base_corner2.y - base_corner1.y + (base_corner2.y - base_corner1.y)//2)//lamps*i)
lamp_corner2 = lamp_corner1.clone()
lamp_corner2.move(x*0.06,y*0.02)
lamp = gr.Oval(lamp_corner1,lamp_corner2)
lamp.setFill('white')
lamp.draw(pic)
def draw_alien(win):
draw_horizon(win)
draw_moon(win)
draw_clouds(win)
draw_starship(win)
win = create_window()
draw_alien(win)
win.getMouse()
win.close()
###Output
_____no_output_____
###Markdown
Нарисуем гистограммы курсов купли/продажи
###Code
fig, axs = plt.subplots(2, 2, figsize=(13, 10))
j = 0
k = 0
for i in prices:
axs[j, k].hist(prices[i])
axs[j, k].set_xlabel(i)
axs[j, k].set_ylabel('Количество попаданий')
k += 1
if k % 2 == 0:
j = 1
k = 0
plt.show()
###Output
_____no_output_____
###Markdown
Вычисление симметрии
###Code
for i in prices:
N = len(prices[i])
xi = prices[i]
Ax = np.sum((xi - xi.mean())**3) / N
sigma = np.sqrt(np.sum((xi - xi.mean())**2) / N)
Ax = Ax / sigma**3
print("Коэфф симметрии {}: {}".format(i, Ax))
###Output
Коэфф симметрии доллар продажа: 1.0225870797172465
Коэфф симметрии доллар покупка: -0.43775407940276123
Коэфф симметрии евро продажа: 1.301880261180435
Коэфф симметрии евро покупка: -0.35375786912466567
###Markdown
Вычисление эксцесса
###Code
for i in prices:
N = len(prices[i])
xi = prices[i]
Ax = np.sum((xi - xi.mean())**4) / N
sigma = np.sqrt(np.sum((xi - xi.mean())**2) / N)
Ax = Ax / sigma**4 - 3
print("Коэфф эксцесса {}: {}".format(i, Ax))
###Output
Коэфф эксцесса доллар продажа: 1.6086092196026458
Коэфф эксцесса доллар покупка: -0.8191958658350758
Коэфф эксцесса евро продажа: 2.237514660393834
Коэфф эксцесса евро покупка: -0.9673113609499535
###Markdown
Часть 2Имеется выборочная совокупность из 400 реализаций СВ с треугольным распределением от 0 до 2. Определить параметры теоретического распределения (варианты: равномерное, нормальное), которое оптимальным образом приближает данную выборку.Использовать два метода:А. Метод наименьших квадратов Б. Систему уравнений для числовых характеристик выборки
###Code
distr = np.random.triangular(0, 1, 2, 400)
print(distr[0:5])
plt.hist(distr, bins=32)
plt.show()
###Output
[0.54586616 1.08763609 1.49709029 1.05681009 1.53573853]
###Markdown
Считаем характеристки распределения
###Code
mean = distr.mean()
D = np.var(distr)
avg = np.sqrt(D)
Ax = 1/np.sqrt(avg)**3 * np.sum((distr - mean)**3)/distr.size
Ex = 1/np.sqrt(avg)**4 * np.sum((distr - mean)**4)/distr.size - 3
import warnings
warnings.filterwarnings('ignore')
distr.sort()
x = np.arange(0, 2, 2 / distr.size)
x = np.vstack([x, np.ones(len(x))]).T
m, c = np.linalg.lstsq(x, distr)[0]
print(f'y = {m}x + {c}')
x_ = x[:,:1]
plt.plot(x_, distr, 'o', label='Original data', markersize=5)
plt.plot(x_, m*x_ + c, 'g', label='Fitted line')
plt.title('МНК, сделанный в городе Ессентуки')
plt.legend()
plt.show()
###Output
y = 0.7040846053331278x + 0.32897595013318087
###Markdown
Лабораторная работы №3 "Сезонные модели" Импортирование библиотек
###Code
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
from matplotlib.gridspec import GridSpec
from sklearn import metrics
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.model_selection import KFold
import statsmodels
from statsmodels.graphics.tsaplots import plot_pacf,plot_acf
from statsmodels.graphics.api import qqplot
from statsmodels.tsa.arima.model import ARIMA
from statsmodels.tsa.statespace.sarimax import SARIMAX
from statsmodels.tsa.stattools import adfuller
from scipy import stats
from tabulate import tabulate
from itertools import product
import warnings
warnings.filterwarnings("ignore")
###Output
_____no_output_____
###Markdown
Загрузка входных данных
###Code
dist = pd.read_csv('data/season.csv')
season = dist["liquor"].dropna()
season
###Output
_____no_output_____
###Markdown
График процесса, его АКФ и ЧАКФ
###Code
lagCount = 30
fig = plt.figure(figsize=(12, 8))
gs = GridSpec(2, 2, wspace=0.2, hspace=0.2)
ax1 = fig.add_subplot(gs[0, :])
ax1.set_title('Season model')
ax1.plot(season)
ax2 = fig.add_subplot(gs[1, :-1])
_ = plot_acf(season, ax = ax2, lags = lagCount)
ax3 = fig.add_subplot(gs[1:, -1])
_ = plot_pacf(season, ax = ax3, lags = lagCount)
plt.show()
###Output
_____no_output_____
###Markdown
Удаление тренда
###Code
diff = list()
for i in range(1, len(season)):
value = season[i] - season[i - 1]
diff.append(value)
plt.plot(season, label='season')
plt.plot(diff, label='not trend')
plt.show()
###Output
_____no_output_____
###Markdown
График процесса, его АКФ и ЧАКФ без тренда
###Code
lagCount = 30
fig = plt.figure(figsize=(12, 8))
gs = GridSpec(2, 2, wspace=0.2, hspace=0.2)
ax1 = fig.add_subplot(gs[0, :])
ax1.set_title('Diff model')
ax1.plot(diff)
ax2 = fig.add_subplot(gs[1, :-1])
_ = plot_acf(diff, ax = ax2, lags = lagCount)
ax3 = fig.add_subplot(gs[1:, -1])
_ = plot_pacf(diff, ax = ax3, lags = lagCount)
plt.show()
###Output
_____no_output_____
###Markdown
Проанализируем графики АКФ и ЧАКФ, для определения максимальных порядков модели Проведём обучение для всех моделей, порядок которых ниже максимального порядка модели.
###Code
pSeason = [0, 1, 2]
qSeason = [0, 1, 2]
pOrder = [0, 1, 2]
qOrder = [0, 1, 2]
models = {}
for i in pOrder:
for j in qOrder:
for k in pSeason:
for l in qSeason:
if ((i, j ,k, l) == (0, 0, 0, 0)):
continue
arimax = SARIMAX(np.array(diff), order=(i, 0, j), seasonal_order=(k, 0, l, 12), initialization='approximate_diffuse').fit()
pVal = arimax.pvalues
if all(i <= 0.05 for i in pVal):
models[i, j, k, l] = arimax
###Output
_____no_output_____
###Markdown
Количество моделей, имеющих значимые коэффициенты, то есть pVal < 0.05
###Code
print(f'Количество моделей: {len(models.keys())}')
###Output
Количество моделей: 45
###Markdown
Разделение данных на обучающую и тестовую выборки
###Code
split_diff = int(len(diff) * 0.7)
diff_train, diff_test = diff[:split_diff], diff[split_diff:]
diff_train = np.array(diff_train)
diff_test = np.array(diff_test)
###Output
_____no_output_____
###Markdown
Вычисление стандартной ошибки для моделей
###Code
def standard_error(y, y_1, order):
return np.sqrt(np.sum(np.square((y_1 - y))) / (len(y) - order))
def standard_error_model(train, test, model):
k = max(model.model_orders['ar'], model.model_orders['ma'])
standard_error_train = standard_error(train, model.predict(0, len(train) - 1), k)
standard_error_test = standard_error(test, model.forecast(len(test)), k)
return standard_error_train, standard_error_test
m = {}
dict_se_train = {}
dict_se_test = {}
dict_aic = {}
dict_bic = {}
for name, model in models.items():
tmp_dict = {}
se_train, se_test = standard_error_model(diff_train, diff_test, model)
dict_se_train[name] = se_train
dict_se_test[name] = se_test
dict_aic[name] = model.aic
dict_bic[name] = model.bic
tmp_dict['SE Train'] = se_train
tmp_dict['SE Test'] = se_test
tmp_dict['AIC'] = model.aic
tmp_dict['BIC'] = model.bic
m[name] = tmp_dict
data = {
'Model': list(m.keys()),
'SE Train': list(dict_se_train.values()),
'SE Test': list(dict_se_test.values()),
'AIC': list(dict_aic.values()),
'BIC': list(dict_bic.values())
}
df = pd.DataFrame.from_dict(data)
# df.set_index('Model')
dfAIC = df.sort_values("AIC")
###Output
_____no_output_____
###Markdown
Таблица результатов моделей, отсортированных по критерию Акаике
###Code
dfAIC.head(10)
###Output
_____no_output_____
###Markdown
Анализ остатков моделей Отсортировав все модели по критерию акаике, выберем первые 5 Построим их АКФ и ЧАКФ
###Code
lagCount = 30
top_model = 5
width = 2
height = 4
fig = plt.figure( figsize=( width * len(dfAIC.head(top_model)['Model']), height * len(dfAIC.head(top_model)['Model'] ) ) )
for idx, elem in enumerate(dfAIC.head(top_model)['Model']):
gs = GridSpec(len(dfAIC.head(top_model)['Model']), 2, wspace = 0.2, hspace = 0.3)
m = models[elem]
ax1 = fig.add_subplot(gs[idx, 0])
ax2 = fig.add_subplot(gs[idx, 1])
_ = plot_acf(m.resid, ax = ax1, lags = lagCount, title=f'АКФ {elem}')
_ = plot_pacf(m.resid, ax = ax2, lags = lagCount, title=f'ЧАКФ {elem}')
plt.show()
###Output
_____no_output_____
###Markdown
Logistic Regression Corinne Jones, TA DATA 558, Spring 2020 In this lab we'll see how to use scikit-learn's logistic regression function. After this lab, you should knowhow to fit a logistic regression model with scikit-learn. 1 Logistic Regression Recall that in logistic regression we have a binary response variable $y$ and use the model$$ P(y=1|X; \beta) = \frac{\exp{(\beta_0+\beta_1X_1 + \cdots + \beta_dX_d)}}{1+\exp{(\beta_0+\beta_1X_1 + \cdots + \beta_dX_d)}}.$$By transforming the linear combination of predictors, $\beta_0 + \beta_1X_1 + \cdots + \beta_dX_d$, in the above equation we ensure that $P(y=1|X;\beta)$ (the estimated probability that the response is equal to 1, conditional on the predictors $X=(X_1,\dots,X_d)$) is always between 0 and 1. We can also rearrange the above equation to get$$ \log\left(\frac{P(y=1|X; \beta)}{1-P(y=1|X; \beta)}\right) = \beta_0 + \beta_1X_1 + \cdots + \beta_dX_d.$$ During the lecture you saw that when the labels are in the set $\{-1, +1\}$ (as opposed to, e.g., $\{0, 1\}$), maximizing the log-likelihood entails solving the problem $$\min_{\beta_0\in\mathbb{R}, \beta \in \mathbb{R}^d} \: \frac{1}{n} \sum_{i=1}^n \log\left(1+ \exp(-y_i(\beta_0+x_i^T \beta))\right).$$where $\beta=[\beta_1,\dots, \beta_d]^T$. After fitting the model we typically label a new input $x$ with 1 if our estimated probability of it being 1, $P(y=1|x; \beta^\star)$, is larger than the estimated probability of it being -1, $P(y=-1|x;\beta^\star)$ (or 0, depending on the convention). **Exercise 1.** Denote by $\beta_0^\star$, $\beta^\star$ the $\beta_0,\beta$ that maximize the log-likelihood. Show that $P(y=1|x;\beta^\star)>P(y=-1|x;\beta^\star)$ if and only if $\beta_0^\star + (\beta^\star)^T x > 0$. 1.1 Log sum exp trickIn practice, $\exp(x_i^T\beta)$ could be very large or very close to zero, resulting in overflow or underflow. Suppose we want to compute $\log(1+\exp(1000))$:
###Code
import numpy as np
np.log(1+np.exp(1000))
###Output
_____no_output_____
###Markdown
It appears as though we get an overflow error! But it should be finite, since $1+\exp(1000)\approx \exp(1000)$ and hence $\log(1+\exp(1000)) \approx \log(\exp(1000)) = 1000$. To circumvent this problem, you can use a trick: the fact that$$ \log(1+\exp(x)) = a + \log(\exp(-a) + \exp(x-a))$$for any $a$. **Exercise 2.** Show that the above identity is true. **Exercise 3.** Use the above identity to compute $\log(1+\exp(1000))$.
###Code
a = 800
x = 1000
a + np.log(np.exp(-a)+np.exp(x-a))
###Output
_____no_output_____
###Markdown
You should get something close to 1000. 1.2 Loading the dataNext we'll use logistic regression to distinguish Hornbills and Toucans. The features that we'll use are derived from images. You can download the data from Canvas. **To do:** Change the directory below (if necessary) to load in the data for this lab.
###Code
import numpy as np
import os
data_dir = 'lab3_data'
x_train = np.load(os.path.join(data_dir, 'train_features.npy'))
y_train = np.load(os.path.join(data_dir, 'train_labels.npy'))
x_test = np.load(os.path.join(data_dir, 'test_features.npy'))
y_test = np.load(os.path.join(data_dir, 'test_labels.npy'))
###Output
_____no_output_____
###Markdown
"Hornbill" has label 0 and "Toucan" has label 1. There are 500 images in the training set and 100 images in the test set. There is one *row* corresponding to each image.
###Code
print('Number of images:', x_train.shape[0])
print('Dimension of features:', x_train.shape[1])
###Output
Number of images: 1000
Dimension of features: 4096
###Markdown
1.3 Classification using Scikit-LearnHere we're going to use logistic regression from Scikit-learn to classify the images. **Exercise 4.** Standardize the data. You may use Scikit-learn's `StandardScaler` for this. Use the same names for the normalized data (`x_train` and `x_test`). Reference: http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html
###Code
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
x_train = scaler.fit_transform(x_train)
###Output
_____no_output_____
###Markdown
As with linear regression, when using logistic regression it is beneficial to add a penalty term on the norm of the weights. With this penalty, we then optimize the expression$$\min_{\beta \in \mathbb{R}^d}\; \frac{1}{n} \sum_{i=1}^n \log\left(1+ \exp(-y_i(\beta_0+x_i^T \beta))\right) + \lambda \|\beta\|^2_2.$$(where the labels are $\pm 1$). We choose $\lambda$ via cross-validation. **Exercise 5.** Use `LogisticRegressionCV` to fit the model to the training data. For today use the default parameter values. Then compute the accuracy on the test set. Use `classifier` as the name of your instantiation of `LogisticRegressionCV`.Reference: http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LogisticRegressionCV.html We're able to get 88% accuracy! Let's get an idea of what images it classified correctly and incorrectly.
###Code
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import os
def display_ranked_image_list(names, image_dir, scores, num_images=10, cutoff=0.5, true_labels=None, display_mistakes=False):
"""
Display a (subset of a) ranked list of images. By default, this function displays
10 images from the list of image names ("names") sorted by decreasing scores ("scores").
:param names: List of image names
:param scores: Scores for each image (from some classifier)
:param num_images: Number of images to display
:param true_labels: The true labels of each image
:param display_mistakes: Whether to only display the top images on which the classifier made mistakes
"""
ncol = 6
idxs = np.argsort(scores)
if not display_mistakes:
idxs = idxs[-num_images:]
else:
mistakes = np.where(true_labels != 1)[0]
idxs = [i for i in idxs if (i in mistakes and scores[i] > cutoff)][-num_images:]
num_images = len(idxs)
nrow = int(num_images/6) + 1 if num_images % 6 != 0 else int(num_images/6)
fig = plt.figure()
fig.set_figwidth(15)
fig.set_figheight(5*nrow/2)
for i in range(1, num_images+1):
idx = idxs[i-1]
a = fig.add_subplot(nrow, 6, num_images-i+1)
img = mpimg.imread(os.path.join(image_dir, names[idx]))
imgplot = plt.imshow(img)
a.set_title(scores[idx])
plt.axis('off')
plt.show()
# Get names of files in validation set
image_names = sorted(os.listdir(os.path.join(data_dir, 'images', 'test')))
image_dir = os.path.join(data_dir, 'images', 'test')
# Generate estimated values for test observations using the logistic regression classifier
test_probs = classifier.predict_proba(x_test)
# See the images it was most confident were toucans that were in fact toucans
print('Images it was most confident were toucans that were in fact toucans:')
display_ranked_image_list(image_names, image_dir, test_probs[:, 1])
# See the images it was most confident about being toucans that were not toucans
print('Images it was most confident about being toucans that were not toucans:')
display_ranked_image_list(image_names, image_dir, test_probs[:, 1], true_labels=y_test, display_mistakes=True)
# See the images it was most confident were hornbills
print('Images it was most confident were hornbills that were in fact hornbills:')
display_ranked_image_list(image_names, image_dir, 1-test_probs[:, 1])
# See the images it was most confident about being hornbills that were not hornbills
print('Images it was most confident about being hornbills that were not hornbills:')
display_ranked_image_list(image_names, image_dir, 1-test_probs[:, 1], true_labels=(y_test-1)*-1, display_mistakes=True)
###Output
_____no_output_____
###Markdown
Lab 3In this lab, we will implement [Conway's Game of Life](https://en.wikipedia.org/wiki/Conway%27s_Game_of_Life) in a naïve way using the GPU in TensorFlow. Like we discussed in the lecture, there are more efficient algorithms that use the presence of reoccurring patterns within the Life board to speed up the processing.First, we will prepare our environment, then we'll get back to what the rules for the game are. We are using a small auxiliary script `lifereader.py` that you can inspect yourself.
###Code
%matplotlib inline
import matplotlib.pyplot as plt
import lifereader
import numpy as np
import tensorflow as tf
# The following two lines DISABLE GPU usage and logs all activities executed by TensorFlow.
##tf.config.set_visible_devices([], 'GPU')
##tf.debugging.set_log_device_placement(True)
###Output
_____no_output_____
###Markdown
We will download a zip file with lots of game of life patterns, and try at least one of them in our code. Specifically,you should download [lifep.zip](http://www.ibiblio.org/lifepatterns/lifep.zip) from [Alan Hensel's](http://www.ibiblio.org/lifepatterns/) page.On an UPPMAX machine, you can download and unzip this file with the following commands: wget http://www.ibiblio.org/lifepatterns/lifep.zip unzip lifep.zip Now we can try loading one file.
###Code
board = lifereader.readlife('BREEDER3.LIF', 2048)
###Output
_____no_output_____
###Markdown
Let's check what this looks like.
###Code
plt.figure(figsize=(20,20))
plt.imshow(board[768:1280,768:1280])
###Output
_____no_output_____
###Markdown
You can check qualitatively that this looks similar to the initial step in the Wikipedia [Breeder](https://en.wikipedia.org/wiki/Breeder_%28cellular_automaton%29) pageLet's zoom out a bit and check the full picture.
###Code
plt.figure(figsize=(20,20))
plt.imshow(board)
###Output
_____no_output_____
###Markdown
Since we will be using TensorFlow, we should convert this board to a tensor. We will even do it three times,in two different formats. Feel free to decide which one you use in your implementation.
###Code
boardtfbool = tf.cast(board, dtype=tf.bool)
boardtfuint8 = tf.cast(board, dtype=tf.uint8)
boardtfint32 = tf.cast(board, dtype=tf.int32)
boardtffloat16 = tf.cast(board, dtype=tf.half)
###Output
_____no_output_____
###Markdown
The standard rules of Game of Life are pretty simple:* Each cell has 8 neighbors, i.e. the 8 adjacent cells in each direction (including diagonals). All behavior is defined from the current state of a cell and it's neighbors.* A live cell is a cell containing `1` or `True`. The opposite is a dead cell.* In each iteration of the game, all cells are updated based on the state of that cell and its neighbors in the previous iteration. It doesn't matter which neighbors are turning dead/live during the same iteration.* Any live cell with tho or three neighbors survive * All other live cells die* Any dead cell with three live neighbors gets alive * All other dead cells stay dead You should implement the function `runlife` below. It accepts a Game of Life board tensor and the number of iterations. It should return a new tensor with the relevant updates. Try to use existing functions in the [TensorFlow API](https://www.tensorflow.org/versions/r2.1/api_docs/python/tf) rather than rolling your own. Note that inspecting the state of your neighbors and yourself might be possible to express as a convolution, but it might not be the fastest way. There might be a bug in some configurations with doing GPU convolutions for `int32` data.We tag this function as `@tf.function` in order to make TensorFlow optimize the full graph. You might want to remove that for making debugging easier (feel free to copy code out of Jupyter if you want to debug in another environment, as well).Note: You do not have to implement any specific behavior for cells right at the edge, as long as dead cells with only dead neighbors stay dead.
###Code
@tf.function
def runlife(board, iters):
# Init work
for _ in range(iters):
# Per iteration
pass
# Final work
return board
###Output
_____no_output_____
###Markdown
We will now run the code. In this version, it was adapted to the `float16` board.If you used another version instead, change the code.
###Code
%time boardresult = runlife(boardtffloat16, 1500)
boardresult = np.cast[np.int32](boardresult)
plt.figure(figsize=(20,20))
plt.imshow(boardresult)
###Output
_____no_output_____
###Markdown
IBM Quantum Challenge Africa: Quantum Chemistry for HIV Table of Contents| Walk-through ||:-||[Preface](preface)||[Introduction](intro)||[Step 1 : Defining the Molecular Geometry](step_1)||[Step 2 : Calculating the Qubit Hamiltonian](step_2)||[Step 2a: Constructing the Fermionic Hamiltonion](step_3)||[Step 2b: Getting Ready to Convert to a Qubit Hamiltonian](step_2b)||[Step 3 : Setting up the Variational Quantum Eigensolver (VQE)](step_3)||[Step 3a: The V in VQE (i.e. the Variational form, a Trial state)](step_3a)||[Step 3b: The Q in VQE: the Quantum environment](step_3b)||[Step 3c: Initializing VQE](step_3c)||[Step 4 : Solving for the Ground-state](step_4)||||[The HIV Challenge](challenge)||[1. Refining Step 1: Varying the Molecule](refine_step_1)||[2. Refining Step 2: Reducing the quantum workload](refine_step_2)||[3. Refining Step 4: Energy Surface](refine_step_4)||[4. Refining Step 3a](refine_step_3a)||Exercises||[Exercise 3a: Molecular Definition of Macromolecule with Blocking Approach](exercise_3a)||[Exercise 3b: Classical-Quantum Treatment Conceptual Questions (Multiple-Choice)](exercise_3b)||[Exercise 3c: Energy Landscape, To bind or not to bind?](exercise_3c)||[Exercise 3d: The effect of more repetitions](exercise_3d)||[Exercise 3e: Open-ended: Find the best hardware_inspired_trial to minimize the Energy Error for the Macromolecule](exercise_3e)||[Quantum Chemistry Resources](qresource)|Preface**HIV is a virus that has presented an immense challenge for public health, globally**. The ensuing disease dynamics touch on multiple societal dimensions including nutrition, access to health, education and research funding. To compound the difficulties, the virus mutates rapidly with different strains having different geographic footprints. In particular, the HIV-1-C and HIV-2 strains predominate mostly in Africa. Due to disparities in funding, research for treatments of the African strains lags behind other programmes. African researchers are striving to address this imbalance and should consider adding the latest technologies such as quantum computing to their toolkits.**Quantum computing promises spectacular improvements in drug-design**. In particular, in order to design new anti-retrovirals it is important to perform **chemical simulations** to confirm that the anti-retroviral binds with the virus protein. Such simulations are notoriously hard and sometimes ineffective on classical supercomputers. Quantum computers promise more accurate simulations allowing for a better drug-design workflow.In detail: anti-retrovirals are drugs that bind with and block a virus protein, called protease, that cleaves virus polyproteins into smaller proteins, ready for packaging. The protease can be thought of as a chemical scissor. The anti-retroviral can be thought of as a sticky obstacle that disrupts the ability of the scissor to cut. With the protease blocked, the virus cannot make more copies of itself.Mutations in the viral protease changes the binding propensity of a given anti-retroviral. Hence, when a mutation occurs and an anti-retroviral no longer binds well, the goal becomes to adjust the anti-retroviral molecule to again bind strongly.**The main goal of this challenge is to explore whether a toy anti-retroviral molecule binds with a toy virus protease.**Along the way, this challenge introduces **state-of-the-art hybrid classical-quantum embedded chemistry modelling** allowing the splitting of the work-load between classical approximations and more accurate quantum calculations.Finally, you need to tweak the setup of the quantum chemistry algorithm (without having to understand the nuts and bolts of quantum computing) to achieve the best performance for ideal quantum computing conditions. *A video explaining how HIV infects and how anti-retroviral treatment works*:
###Code
from IPython.display import display, YouTubeVideo
YouTubeVideo('cSNaBui2IM8')
###Output
_____no_output_____
###Markdown
Walk-through: Calculating the Ground-state Energy for the Simplest Molecule in the Universe *Import relevant packages*
###Code
from qiskit import Aer
from qiskit_nature.drivers import PySCFDriver, UnitsType, Molecule
from qiskit_nature.problems.second_quantization.electronic import ElectronicStructureProblem
from qiskit_nature.mappers.second_quantization import JordanWignerMapper, BravyiKitaevMapper
from qiskit_nature.converters.second_quantization import QubitConverter
from qiskit_nature.transformers import ActiveSpaceTransformer
from qiskit_nature.algorithms import GroundStateEigensolver, BOPESSampler
from qiskit.algorithms import NumPyMinimumEigensolver
from qiskit.utils import QuantumInstance
from qiskit_nature.circuit.library.ansatzes import UCCSD
from qiskit_nature.circuit.library.initial_states import HartreeFock
from qiskit.circuit.library import TwoLocal
from qiskit.algorithms import VQE
from qiskit.algorithms.optimizers import COBYLA
from functools import partial as apply_variation_to_atom_pair
import numpy as np
import matplotlib.pyplot as plt
###Output
/opt/conda/lib/python3.8/site-packages/pyscf/lib/misc.py:47: H5pyDeprecationWarning: Using default_file_mode other than 'r' is deprecated. Pass the mode to h5py.File() instead.
h5py.get_config().default_file_mode = 'a'
###Markdown
IntroductionIn the HIV Challenge, we are tasked with investigating whether the toy anti-retroviral molecule binds with and therefore, disrupts the toy protease molecule. Successful binding is determined by a lower total ground-state energy for the molecules when they are close together (forming a single macromolecule) compared to far apart.Total ground-state energy refers to the sum of the energies concerning the arrangement of the electrons and the nuclei. The nuclear energy is easy to calculate classically. It is the energy of the electron distribution (i.e. molecular spin-orbital occupation) that is extremely difficult and requires a quantum computer.We start with a walk-through tutorial, where we calculate the ground-state energy of a simple molecule and leave the more complicated set-up to the challenge section. The ground-state of a molecule in some configuration consists of the locations of the nuclei, together with some distribution of electrons around the nuclei. The nucleus-nucleus, nuclei-electron and electron-electron forces/energy of attraction and repulsion are captured in a matrix called the **Hamiltonian**. Since the nuclei are relatively massive compared to the electrons, they move at a slower time-scale than the electrons. This allows us to split the calculation into two parts: placing the nuclei and calculating the electron distribution, followed by moving the nuclei and recalculating the electron distribution until a minimum total energy distribution is reached: Algorithm: Find_total_ground_statePlace nuclei Repeat until grid completed or no change in total_energy: - calculate electronic ground-state - total_energy = (nuclei repulsion + electronic energy) - move nuclei (either in grid or following gradient)return total_energy In the walk-through, we simply fix the nuclei positions; however, later, in the challenge section, we allow for a varying one-dimensional intermolecular distance between the anti-retroviral and the protease molecules, which represents the anti-retroviral approaching the protease molecule in an attempt to bind. Step 1: Defining the Molecular Geometry For this walk-through, we work with the simplest non-trivial molecule possible: H$_2$, the hydrogen gas molecule.*The first thing to do is to fix the location of each nucleus. This is specified as a python list of nuclei, where each nucleus (as a list) contains a string corresponding to the atomic species and its 3D co-ordinates (as another list). We also specify the overall charge, which tells Qiskit to automatically calculate the number of needed electrons to produce that charge:*
###Code
hydrogen_molecule = Molecule(geometry=
[['H', [0., 0., 0.]],
['H', [0., 0., 0.735]]],
charge=0, multiplicity=1)
###Output
_____no_output_____
###Markdown
Step 2: Calculating the Qubit Hamiltonian Once nuclei positions are fixed (the nucleus-nucleus forces are temporarily irrelevant), the only part of the Hamiltonian that then needs to be calculated on the quantum computer is the detailed electron-electron interaction. The nuclei-electron and a rough mean field electron-electron interaction can be pre-computed as *allowed molecular orbitals* on a classical computer via the, so called, Hartree-Fock approximation. With these allowed molecular orbitals and their pre-calculated overlaps, Qiskit automatically produces an interacting electron-electron **fermionic molecular-orbital Hamiltonian** (called Second Quantization). The molecular orbital and overlap pre-calculation are provided by classical packages, e.g. PySCF, and connected to Qiskit via a so-called *driver*, in particular, we use the PySCFDriver. Step 2a: Constructing the Fermionic Hamiltonion *We specify the driver to the classical software package that is to be used to calculate the resulting orbitals of the provided molecule after taking into account the nuclei-electron and mean-field interactions. The `basis` option selects the basis set in which the molecular orbitals are to be expanded in. `sto3g` is the smallest available basis set:*
###Code
molecular_hydrogen_orbital_maker = PySCFDriver(molecule=hydrogen_molecule, unit=UnitsType.ANGSTROM, basis='sto3g')
###Output
_____no_output_____
###Markdown
*Qiskit provides a helpful Class named the ElectronicStructureProblem, which calls the driver in the right way to construct the molecular orbitals. We initialise ElectronicStructureProblem with the driver (which already has the molecular information stored in it from the previous step):*
###Code
hydrogen_fermionic_hamiltonian = ElectronicStructureProblem(molecular_hydrogen_orbital_maker)
###Output
_____no_output_____
###Markdown
*Here, we instruct the ElectronicStructureProblem object to go ahead and create the fermionic molecular-orbital Hamiltonian (which gets stored internally):*
###Code
hydrogen_fermionic_hamiltonian.second_q_ops()
print("Completed running classical package.\nFermionic molecular-orbital Hamiltonian calculated and stored internally.")
print("An example of HF info available: Orbital Energies", hydrogen_fermionic_hamiltonian._molecule_data_transformed.orbital_energies)
###Output
Completed running classical package.
Fermionic molecular-orbital Hamiltonian calculated and stored internally.
An example of HF info available: Orbital Energies [-0.58062892 0.67633625]
###Markdown
(If this step is not run explicitly, and its outputs are not used in an intermediary step, the final ground_state solving step would run it automatically.) Step 2b: Getting Ready to Convert to a Qubit Hamiltonian Above, *fermionic* is a term to describe the behaviour of electrons (having an anti-symmetric wave-function obeying the Pauli Exclusion principle). In order to use the quantum computer we need to map the electrons (which exhibit fermionic behavior) to the quantum computer's qubits (which have closely related spin behaviour: Pauli Exclusion but not necessarily anti-symmetric). This mapping is a generic process, independent of the driver above. There are multiple mapping methods available, each with pros and cons, and constitutes something to experiment with. *For now, we select the simplest qubit mapper/converter called the Jordan-Wigner Mapper:*
###Code
map_fermions_to_qubits = QubitConverter(JordanWignerMapper())
# e.g. alternative:
# map_fermions_to_qubits = QubitConverter(BravyiKitaevMapper())
###Output
_____no_output_____
###Markdown
(Note, we have just chosen the mapper above, it has not yet been applied to the fermionic Hamiltonian.) Step 3: Setting up the Variational Quantum Eigensolver (VQE)Now that we have defined the molecule and its mapping onto a quantum computer, we need to select an algorithm to solve for the ground state. There are two well-known approaches: Quantum Phase Estimation (QPE) and VQE. The first requires fault-tolerant quantum computers that have not yet been built. The second is suitable for current day, noisy **depth**-restricted quantum computers, because it is a hybrid quantum-classical method with short-depth quantum circuits. By *depth* of the circuit, it suffices to know that quantum computers can only be run for a short while, before noise completely scrambles the results.Therefore, for now, we only explore the VQE method. Furthermore, VQE offers many opportunities to tweak its configuration; thus, as an end-user you gain experience in quantum black-box tweaking. VQE is an algorithm for finding the ground-state of a molecule (or any Hamiltonian in general). It is a hybrid quantum-classical algorithm, which means that the algorithm consists of two interacting stages, a quantum stage and a classical stage. During the quantum stage, a trial molecular state is created on the quantum computer. The trial state is specified by a collection of **parameters** which are provided and adjusted by the classical stage. After the trial state is created, its energy is calculated on the quantum computer (by a few rounds of quantum-classical measurements). The result is finally available classically. At this stage, a classical optimization algorithm looks at the previous energy levels and the new energy level and decides how to adjust the trial state parameters. This process repeats until the energy essentially stops decreasing. The output of the whole algorithm is the final set of parameters that produced the winning approximation to the ground-state and its energy level. Step 3a: The V in VQE (i.e. the Variational form, a Trial state)VQE works by 'searching' for the electron orbital occupation distribution with the lowest energy, called the ground-state. The quantum computer is repeatedly used to calculate the energy of the search trial state.The trial state is specified by a collection of (randomly initialized) parameters that move the state around, in our search for the ground-state (we're minimizing the energy cost-function). The form of the 'movement' is something that can be tweaked (i.e., the definition of the structure of the *ansatz*/trial). There are two broad approaches we could follow. The first, let's call it *Chemistry-Inspired Trial-states*, is to use domain knowledge of what we expect the ground-state to look like from a chemistry point of view and build that into our trial state. The second, let's call it *Hardware-Inspired Trial-states*, is to simply try and create trial states that have as wide a reach as possible while taking into account the architecure of the available quantum computers. *Chemistry-Inspired Trial-states*Since chemistry gives us domain-specific prior information (e.g., the number of orbitals and electrons and the actual Hartree-Fock approximation), it makes sense to guide the trial state by baking this knowledge into the form of the trial. *From the HF approximation we get the number of orbitals and from that we can calculate the number of spin orbitals:*
###Code
hydrogen_molecule_info = hydrogen_fermionic_hamiltonian.molecule_data_transformed
num_hydrogen_molecular_orbitals = hydrogen_molecule_info.num_molecular_orbitals
num_hydrogen_spin_orbitals = 2 * num_hydrogen_molecular_orbitals
###Output
_____no_output_____
###Markdown
*Furthermore, we can also extract the number of electrons (spin up and spin down):*
###Code
num_hydrogen_electrons_spin_up_spin_down = (hydrogen_molecule_info.num_alpha, hydrogen_molecule_info.num_beta)
###Output
_____no_output_____
###Markdown
*With the number of spin orbitals, the number of electrons able to fill them and the mapping from fermions to qubits, we can construct an initial quantum computing state for our trial state:*
###Code
hydrogen_initial_state = HartreeFock(num_hydrogen_spin_orbitals,
num_hydrogen_electrons_spin_up_spin_down,
map_fermions_to_qubits)
###Output
_____no_output_____
###Markdown
*Finally, Qiskit provides a Class (Unitary Coupled Cluster Single and Double excitations, `UCCSD`) that takes the above information and creates a parameterised state inspired by the HF approximation, that can be iteratively adjusted in our attempt to find the ground-state:*
###Code
hydrogen_chemistry_inspired_trial = UCCSD(map_fermions_to_qubits,
num_hydrogen_electrons_spin_up_spin_down,
num_hydrogen_spin_orbitals,
initial_state=hydrogen_initial_state)
###Output
_____no_output_____
###Markdown
*Hardware-Inspired Trial-states*The problem with the above "chemistry-inspired" trial-states, is that they are quite deep, quickly using up the available depth of current-day quantum computers. A potential solution is to forgo this chemistry knowledge and try to represent arbitrary states with trial states that are easy to prepare and parametrically "move" around on current hardware. There are two quantum operations that can be used to try and reach arbitrary states: mixing (our term for *conditional sub-space rotation*) and rotating (*unconditional rotation*). Detailed knowledge of how these operations and their sub-options work are not really needed, especially because it is not immediately obvious which settings produce the best results. Mixing (also called Entanglement maps)There are a set of available mixing strategies, that you may experiment with. This is specified with two arguments, *`entanglement`* (choosing what to mix) and *`entanglement_blocks`* (choosing how to mix):Possible *`entanglement`* values: `'linear'`, `'full'`, `'circular'`, `'sca'`Possible *`entanglement_blocks`* values: `'cz'`, `'cx'`For our purposes, it is acceptable to simply choose the first option for each setting. RotationThere are a set of available *parameterized* rotation strategies. The rotation strategies are specified as a single argument, *`rotation_blocks`*, in the form of a list of any combination of the following possibilities:Possible *`rotation_blocks`*: `'ry'`, `'rx'`,`'rz'`,`'h'`, ...Typically, this is the only place that parameters are introduced in the trial state. One parameter is introduced for every rotation, corresponding to the angle of rotation around the associated axis. (Note, `'h'` does not have any parameters and so can not be selected alone.)Again, for our purposes, an acceptable choice is the first option alone in the list. *Qiskit provides a Class called `TwoLocal` for creating random trial states by local operations only. The number of **rounds** of the local operations is specified by the argument `reps`:*
###Code
hardware_inspired_trial = TwoLocal(rotation_blocks = ['ry'], entanglement_blocks = 'cz',
entanglement='linear', reps=2)
###Output
_____no_output_____
###Markdown
(Note, this trial state does not depend on the molecule.) *Just for convenience, let's choose between the two approaches by assiging the choice to a variable:*
###Code
hydrogen_trial_state = hydrogen_chemistry_inspired_trial
# OR
# hydrogen_trial_state = hardware_inspired_trial
###Output
_____no_output_____
###Markdown
Step 3b: The Q in VQE: the Quantum environment Since VQE runs on a quantum computer, it needs information about this stage. For testing purposes, this can even be a simulation, both in the form of noise-free or noisy simulations. Ultimately, we would want to run VQE an actual (albeit noisy) quantum hardware and hopefully, in the not-too-distant future, achieve results unattainable classically. For this challenge, let us pursue noise-free simulation only. Noise-Free Simulation*To set up a noise-free simulation:*
###Code
noise_free_quantum_environment = QuantumInstance(Aer.get_backend('statevector_simulator'))
###Output
_____no_output_____
###Markdown
Step 3c: Initializing VQE Qiskit Nature provides a class called VQE, that implements the VQE algorithm. *It is initialized in a generic way (without reference to the molecule or the Hamiltonian) and requires the two pieces of information from above: the trial state and the quantum environment:*
###Code
hydrogen_vqe_solver = VQE(ansatz=hydrogen_trial_state, quantum_instance=noise_free_quantum_environment)
###Output
_____no_output_____
###Markdown
(Note, the vqe solver is only tailored to hydrogen if the trial state is the hydrogen_chemistry_inspired_trial.) Step 4: Solving for the Ground-state **Qiskit Nature provides a class called GroundStateEigensolver to calculate the ground-state of a molecule.**This class first gets initialised with information that is independent of any molecule. It can then be applied to specific molecules using the same generic setup.To initialise a GroundStateEigensolver object, we need to provide the two generic algorithmic sub-components from above, the mapping method (Step 2b) and the solving method (Step 3). For testing purposes, an alternative to the VQE solver is a classical solver (see numpy_solver below).
###Code
hydrogen_ground_state = GroundStateEigensolver(map_fermions_to_qubits, hydrogen_vqe_solver)
###Output
_____no_output_____
###Markdown
We are finally ready to solve for the ground-state energy of our molecule.We apply the GroundStateEigensolver to the fermionic Hamiltonian (Step 2a) which has encoded in it the molecule (Step 1). The already specified mapper and VQE solver is then automatically applied for us to produce the ground-state (approximation).
###Code
hydrogen_ground_state_info = hydrogen_ground_state.solve(hydrogen_fermionic_hamiltonian)
print(hydrogen_ground_state_info)
###Output
=== GROUND STATE ENERGY ===
* Electronic ground state energy (Hartree): -1.857275030145
- computed part: -1.857275030145
~ Nuclear repulsion energy (Hartree): 0.719968994449
> Total ground state energy (Hartree): -1.137306035696
=== MEASURED OBSERVABLES ===
0: # Particles: 2.000 S: 0.000 S^2: 0.000 M: -0.000
=== DIPOLE MOMENTS ===
~ Nuclear dipole moment (a.u.): [0.0 0.0 1.3889487]
0:
* Electronic dipole moment (a.u.): [0.0 0.0 1.38894841]
- computed part: [0.0 0.0 1.38894841]
> Dipole moment (a.u.): [0.0 0.0 0.00000029] Total: 0.00000029
(debye): [0.0 0.0 0.00000074] Total: 0.00000074
###Markdown
As you can see, we have calculated the Ground-state energy of the electron distribution: -1.85 HartreeFrom the placement of the nuclei, we are also conveniently given the repulsion energy (a simple classical calculation).Finally, when it comes to the ground-state of the overall molecule it is the total ground state energy that we are trying to minimise.So the next step would be to move the nuclei and recalculate the **total ground state energy** in search of the stable nuclei positions. To end our discussion, let us compare the quantum-calculated energy to an accuracy-equivalent (but slower) classical calculation.
###Code
#Alternative Step 3b
numpy_solver = NumPyMinimumEigensolver()
#Alternative Step 4
ground_state_classical = GroundStateEigensolver(map_fermions_to_qubits, numpy_solver)
hydrogen_ground_state_info_classical = ground_state_classical.solve(hydrogen_fermionic_hamiltonian)
hydrogen_energy_classical = hydrogen_ground_state_info.computed_energies[0]
print("Ground-state electronic energy (via classical calculations): ", hydrogen_energy_classical, "Hartree")
###Output
Ground-state electronic energy (via classical calculations): -1.857275030145182 Hartree
###Markdown
The agreement to so many decimal places tells us that, for this particular Hamiltonian, the VQE process is accurately finding the lowest eigenvalue (and interestingly, the ansatz/trial does not fail to capture the ground-state, probably because it spans the entire Hilbert space). However, when comparing to nature or very accurate classical simulations of $H_2$, we find that the energy is only accurate to two decimal places, e.g. total energy VQE: -1.137 Hartree vs highly accurate classical simulation: -1.166 Hartree, which only agrees two decimal places. The reason for this is that in our above treatment there are sources of modelling error including: the placement of nuclei and a number of approximations that come with the Hartree-Fock expansion. For $H_2$ these can be addressed, but ultimately, in general, the more tricky of these sources can never be fully handled because finding the perfect ground-state is QMA-complete, i.e. the quantum version of NP-complete (i.e. 'unsolvable' for certain Hamiltonians). Then again, nature itself is not expected to be finding this perfect ground-state, so future experimention is needed to see how close a given quantum computing solution approximates nature's solution. Walk-through Finished *** The HIV ChallengeNow that we have completed the walk-through, we frame the challenge as the task to refine steps 1-4 while answering related questions. 1. Refining Step 1: Varying the MoleculeIn Step 1, we defined our molecule. For the challenge, we need to firstly define a new molecule, corresponding to our toy protease molecule (the *scissor*) with an approaching toy anti-retroviral (the *blocker*), forming a *macromolecule*. Secondly, we need to instruct Qiskit to vary the approach distance. Let's learn how to do the second step with the familiar hydrogen molecule. *Here is how to specify the type of molecular variation we are interested in (namely, changing the approach distance in absolute steps)*:
###Code
molecular_variation = Molecule.absolute_stretching
#Other types of molecular variation:
#molecular_variation = Molecule.relative_stretching
#molecular_variation = Molecule.absolute_bending
#molecular_variation = Molecule.relative_bending
###Output
_____no_output_____
###Markdown
*Here is how we specify which atoms the variation applies to. The numbers refer to the index of the atom in the geometric definition list. The first atom of the specified atom_pair, is moved closer to the left-alone second atom:*
###Code
specific_molecular_variation = apply_variation_to_atom_pair(molecular_variation, atom_pair=(1, 0))
###Output
_____no_output_____
###Markdown
*Finally, here is how we alter the original molecular definition that you have already seen in the walk-through:*
###Code
hydrogen_molecule_stretchable = Molecule(geometry=
[['H', [0., 0., 0.]],
['H', [0., 0., 0.735]]],
charge=0, multiplicity=1,
degrees_of_freedom=[specific_molecular_variation])
###Output
_____no_output_____
###Markdown
If we wanted to test that the variation is working, we could manually specify a given amount of variation (Qiskit calls it a *perturbation*) and then see what the new geometry is:
###Code
hydrogen_molecule_stretchable.perturbations = [0.1]
###Output
_____no_output_____
###Markdown
(If the above were not specified, a perturbation of zero would be assumed, defaulting to the original geometry.)
###Code
hydrogen_molecule_stretchable.geometry
###Output
_____no_output_____
###Markdown
Notice how only the second atom of our geometry list (index 1, specified first in the atom_pair) has moved closer to the other atom by the amount we specified. When it comes time to scanning across different approach distances this is very helpfully automated by Qiskit. Specifying the Protease+Anti-retroviral Macromolecule ProteaseA real protease molecule is made up of two polypeptide chains of around one hundred amino-acids in each chain (the two chains are folded together), with neighbouring pairs connected by the so-called *peptide-bond*.For our toy protease molecule, we have decided to take inspiration from this peptide bond since it is the basic building structure holding successive amino acids in proteins together. It is one of the most important factors in determining the chemistry of proteins, including protein folding in general and the HIV protease's cleaving ability, in particular.To simplify the calculations, let us choose to focus on the O=C-N part of molecule. We keep and also add enough hydrogen atoms to try and make the molecule as realistic as possible (indeed, HCONH$_2$, Formamide, is a stable molecule, which, incidentally, is an ionic solvent, so it does "cut" ionic bonds).Making O=C-N our toy protease molecule is an extreme simplification, but nevertheless biologically motivated.Here is our toy protease:```"O": (1.1280, 0.2091, 0.0000)"N": (-1.1878, 0.1791, 0.0000)"C": (0.0598, -0.3882, 0.0000)"H": (-1.3085, 1.1864, 0.0001)"H": (-2.0305, -0.3861, -0.0001)"H": (-0.0014, -1.4883, -0.0001)```Just for fun, you may imagine that this molecule is a pair of scissors, ready to cut the HIV master protein (Gag-Pol polyprotein), in the process of making copies of the HI virus: Anti-retroviralThe anti-retroviral is a molecule that binds with the protease to **inhibit/block the cleaving mechanism**. For this challenge, we select a single carbon atom to be our stand-in for the anti-retroviral molecule. MacromoleculeEven though the two molecules are separate in our minds, when they approach, they form a single macro-molecule, with the outer-electrons forming molecular orbitals around all the atoms.As explained in the walk-through, the quantum electronic distribution is calculated for fixed atom positions, thus we have to separately place the atoms. For the first and second task, let us fix the protease's co-ordinates and only vary the anti-retroviral's position along a straight line.We arbitrarily select a line of approach passing through a given point and approaching the nitrogen atom. This "blocking" approach tries to obstruct the scissor from cutting. If it "sticks", it's working and successfully disrupts the duplication efforts of the HIV. Exercise 3a: Molecular Definition of Macromolecule with Blocking ApproachConstruct the molecular definition and molecular variation to represent the anti-retroviral approaching the nitrogen atom, between the "blades": ``` "C": (-0.1805, 1.3955, 0.0000) ``` Write your answer code here: Create a your molecule in the cell below. Make sure to name the molecule `macromolecule`.
###Code
specific_molecular_variation = apply_variation_to_atom_pair(molecular_variation, atom_pair=(3, 2))
## Add your code here
macromolecule = Molecule(geometry=[['H', [-2.0305, -0.3861, -0.0001]],['H', [-1.3085, 1.1864, 0.0001]],
['N', [-1.1878, 0.1791, 0.0000]],['C', [-0.1805, 1.3955, 0.0000]],
['C', [0.0598, -0.3882, 0.0000]],['H', [-0.0014, -1.4883, -0.0001]],
['O', [1.1280, 0.2091, 0.0000]]],charge=0, multiplicity=1,
degrees_of_freedom=[specific_molecular_variation] )
##
###Output
_____no_output_____
###Markdown
To submit your molecule to the grader, run the cell below.
###Code
from qc_grader import grade_ex3a
grade_ex3a(molecule=macromolecule)
###Output
Submitting your answer for ex3/partA. Please wait...
Congratulations 🎉! Your answer is correct and has been submitted.
###Markdown
2. Refining Step 2: Reducing the quantum workload In Step 2, we constructed the qubit Hamiltonian. If we tried to apply Step 2 and beyond to our macromolecule above, the ground state calculation simulation would fail. The reason is because since we specified a zero charge, Qiskit knows that it must work with 30 (= 2\*6+7+8+3\*1) electrons. After second quantization, this translates into, say, 60 spin-orbitals which requires 60 qubits. 60 qubits is beyond our ability to simulate classically and while there are IBM Quantum systems with more than 60 qubits available, the noise levels are currently too high to produce accurate results when using that many qubits. Thus, for the purpose of this Challenge we need to reduce the number of qubits. Fortunately, this is well-motivated from a chemistry point of view as well: the classical Hartree-Fock approximation for core-electrons is sometimes sufficient to obtain accurate chemical results. Doubly fortunately, Qiskit has just recently been extended to seamlessly allow for users to specify that certain electrons should receive quantum-computing treatment while the remaining electrons should be classically approximated. Even as more qubits come on online, this facility may prove very useful in allowing near-term quantum computers to tackle very large molecules that would otherwise be out of reach. *Therefore, we next demonstrate how to instruct Qiskit to give a certain number of electrons quantum-computing treatment:*
###Code
macro_molecular_orbital_maker = PySCFDriver(molecule=macromolecule, unit=UnitsType.ANGSTROM, basis='sto3g')
split_into_classical_and_quantum = ActiveSpaceTransformer(num_electrons=2, num_molecular_orbitals=2)
macro_fermionic_hamiltonian = ElectronicStructureProblem(macro_molecular_orbital_maker, [split_into_classical_and_quantum])
###Output
_____no_output_____
###Markdown
Above, Qiskit provides a class called **ActiveSpaceTransformer** that takes in two arguments. The first is the number of electrons that should receive quantum-computing treatment (selected from the outermost electrons, counting inwards). The second is the number of orbitals to allow those electrons to roam over (around the so-called Fermi level). It is the second number that determines how many qubits are needed. Exercise 3b: Classical-Quantum Treatment Conceptual Questions (Multiple-Choice)Q1: Why does giving quantum treatment to outer electrons of the macromolecule first, make more heuristic sense?```A: Outer electrons have higher binding energies and therefore swing the ground state energy more, therefore requiring quantum treatment.B: Outer electrons exhibit more quantum interference because their orbitals are more spread out.C: Inner core-electrons typically occupy orbitals more straightforwardly, because they mostly orbit a single nucleus and therefore do not lower the energy much by interacting/entangling with outer electrons.```Q2: For a fixed number of quantum-treatment electrons, as you increase the number of orbitals that those electrons roam over (have access to), does the calculated ground-state energy approach the asymptotic energy from above or below?```A: The asymptotic energy is approached from above, because as you increase the possible orbitals that the electrons have access to, the lower the ground state could be.B: The asymptotic energy is approached from below, because as you increase the possible orbitals the more accurate is your simulation, adding energy that was left out before.C: The asymptotic energy is approached from below, because as you increase the possible orbitals that the electrons have access to, the lower the ground state could be.D: The asymptotic energy is approached from above, because as you increase the possible orbitals the more accurate is your simulation, adding energy that was left out before.``` **Uncomment your answers to these multiple choice questions in the code-cell below. Run the cell to submit your answers.**
###Code
from qc_grader import grade_ex3b
## Q1
# answer_for_ex3b_q1 = 'A'
# answer_for_ex3b_q1 = 'B'
# answer_for_ex3b_q1 = 'C'
##
answer_for_ex3b_q1 = 'C'
## Q2
# answer_for_ex3b_q2 = 'A'
# answer_for_ex3b_q2 = 'B'
# answer_for_ex3b_q2 = 'C'
# answer_for_ex3b_q2 = 'D'
##
answer_for_ex3b_q2 = 'A'
grade_ex3b(answer_for_ex3b_q1, answer_for_ex3b_q2)
###Output
Submitting your answer for ex3/partB. Please wait...
Congratulations 🎉! Your answer is correct and has been submitted.
###Markdown
3. Refining Step 4: Energy Surface In Step 4, we ran the ground_state solver on a given molecule once only and we haven't yet explained how to instruct Qiskit to vary the molecular geometry using the specification introduced above. As explained in the introduction, changing the nuclei positions and comparing the total energy levels, is a method for finding the nuclei arrangement with the lowest energy. If the lowest energy is **not** at "infinity", this corresponds to a "stable" bound state of the molecule at the energy minimum. The energy as a function of atomic separation is thus a crucial object of study. This function is called the **Born-Oppenheimer Potential Energy Surface (BOPES)**. Qiskit provides a helpful python Class that manages this process of varying the geometry and repeatedly calling the ground_state solver: **BOPESSampler**.Let's demonstrate BOPESSampler for the hydrogen molecule.*The only steps of the hydrogen molecule walk-through that need to be re-run are Steps 1 and 2a:*
###Code
hydrogen_stretchable_molecular_orbital_maker = PySCFDriver(molecule=hydrogen_molecule_stretchable, unit=UnitsType.ANGSTROM, basis='sto3g')
hydrogen_stretchable_fermionic_hamiltonian = ElectronicStructureProblem(hydrogen_stretchable_molecular_orbital_maker)
###Output
_____no_output_____
###Markdown
*Secondly, here is how to call the sampler:*
###Code
energy_surface = BOPESSampler(gss=hydrogen_ground_state, bootstrap=False) # same solver suffices, since the trial is the same
perturbation_steps = np.linspace(-0.5, 2, 25) # 25 equally spaced points from -0.5 to 2, inclusive.
energy_surface_result = energy_surface.sample(hydrogen_stretchable_fermionic_hamiltonian, perturbation_steps)
###Output
_____no_output_____
###Markdown
*Thirdly, here is how to produce the famous energy landscape plot:*
###Code
def plot_energy_landscape(energy_surface_result):
if len(energy_surface_result.points) > 1:
plt.plot(energy_surface_result.points, energy_surface_result.energies, label="VQE Energy")
plt.xlabel('Atomic distance Deviation(Angstrom)')
plt.ylabel('Energy (hartree)')
plt.legend()
plt.show()
else:
print("Total Energy is: ", energy_surface_result.energies[0], "hartree")
print("(No need to plot, only one configuration calculated.)")
plot_energy_landscape(energy_surface_result)
###Output
_____no_output_____
###Markdown
For extra intuition, you may think of the energy landscape as a mountain, next to a valley, next to a plateau that a ball rolls on (the x co-ordinate of the ball corresponds the separation between the two hydrogen atoms). If the ball is not rolling too fast down the plateau (right to left) it may settle in the valley. The ball slowly rolls down the plateau because the slope is positive (representing a force of attraction between the two hydrogen atoms). If the ball overshoots the minimum point of the valley, it meets the steep negative slope of the mountain and quickly rolls back (the hydrogen atoms repell each other).Notice the minimum is at zero. This is because we defined the hydrogen molecule's nuclei positions at the known ground state positions.By the way, if we had used the hardware_inspired_trial we would have produced a similiar plot, however it would have had bumps because the anzatz does not capture the electronic ground state equally well at different bond lengths. Exercise 3c: Energy Landscape, To bind or not to bind?The million-dollar question: Does our toy anti-retrovial bind and thus block the protease? - Search for the minimum from -0.5 to 5 for 30 points. - Give quantum-computing treatment to 2 electrons roaming over 2 orbitalsQ1. Submit the energy landscape for the anti-retroviral approaching the protease.Q2. Is there a clear minimum at a finite separation? Does binding occur?```A. Yes, there is a clear minimum at 0, so binding does occur.B. Yes, there is a clear minimum at infinity, so binding only happens at infinity.C. No, there is no clear minimum for any separation, so binding occurs because there is no seperation.D. No, there is no clear minimum for any separation, so there is no binding.```(Don't preempt the answer. Furthermore, the answer might change for other approaches and other settings, so please stick to the requested settings.) *Feel free to use the following function, which collects the entire walk-through and refinements to Step 2 and 4. It takes in a Molecule (of refinement Step 1 type), the inputs for the other refinements and boolean choice of whether to use VQE or the numpy solver:*
###Code
def construct_hamiltonian_solve_ground_state(
molecule,
num_electrons=2,
num_molecular_orbitals=2,
chemistry_inspired=True,
hardware_inspired_trial=None,
vqe=True,
perturbation_steps=np.linspace(-1, 1, 3),
):
"""Creates fermionic Hamiltonion and solves for the energy surface.
Args:
molecule (Union[qiskit_nature.drivers.molecule.Molecule, NoneType]): The molecule to simulate.
num_electrons (int, optional): Number of electrons for the `ActiveSpaceTransformer`. Defaults to 2.
num_molecular_orbitals (int, optional): Number of electron orbitals for the `ActiveSpaceTransformer`. Defaults to 2.
chemistry_inspired (bool, optional): Whether to create a chemistry inspired trial state. `hardware_inspired_trial` must be `None` when used. Defaults to True.
hardware_inspired_trial (QuantumCircuit, optional): The hardware inspired trial state to use. `chemistry_inspired` must be False when used. Defaults to None.
vqe (bool, optional): Whether to use VQE to calculate the energy surface. Uses `NumPyMinimumEigensolver if False. Defaults to True.
perturbation_steps (Union(list,numpy.ndarray), optional): The points along the degrees of freedom to evaluate, in this case a distance in angstroms. Defaults to np.linspace(-1, 1, 3).
Raises:
RuntimeError: `chemistry_inspired` and `hardware_inspired_trial` cannot be used together. Either `chemistry_inspired` is False or `hardware_inspired_trial` is `None`.
Returns:
qiskit_nature.results.BOPESSamplerResult: The surface energy as a BOPESSamplerResult object.
"""
# Verify that `chemistry_inspired` and `hardware_inspired_trial` do not conflict
if chemistry_inspired and hardware_inspired_trial is not None:
raise RuntimeError(
(
"chemistry_inspired and hardware_inspired_trial"
" cannot both be set. Either chemistry_inspired"
" must be False or hardware_inspired_trial must be none."
)
)
# Step 1 including refinement, passed in
# Step 2a
molecular_orbital_maker = PySCFDriver(
molecule=molecule, unit=UnitsType.ANGSTROM, basis="sto3g"
)
# Refinement to Step 2a
split_into_classical_and_quantum = ActiveSpaceTransformer(
num_electrons=num_electrons, num_molecular_orbitals=num_molecular_orbitals
)
fermionic_hamiltonian = ElectronicStructureProblem(
molecular_orbital_maker, [split_into_classical_and_quantum]
)
fermionic_hamiltonian.second_q_ops()
# Step 2b
map_fermions_to_qubits = QubitConverter(JordanWignerMapper())
# Step 3a
if chemistry_inspired:
molecule_info = fermionic_hamiltonian.molecule_data_transformed
num_molecular_orbitals = molecule_info.num_molecular_orbitals
num_spin_orbitals = 2 * num_molecular_orbitals
num_electrons_spin_up_spin_down = (
molecule_info.num_alpha,
molecule_info.num_beta,
)
initial_state = HartreeFock(
num_spin_orbitals, num_electrons_spin_up_spin_down, map_fermions_to_qubits
)
chemistry_inspired_trial = UCCSD(
map_fermions_to_qubits,
num_electrons_spin_up_spin_down,
num_spin_orbitals,
initial_state=initial_state,
)
trial_state = chemistry_inspired_trial
else:
if hardware_inspired_trial is None:
hardware_inspired_trial = TwoLocal(
rotation_blocks=["ry"],
entanglement_blocks="cz",
entanglement="linear",
reps=2,
)
trial_state = hardware_inspired_trial
# Step 3b and alternative
if vqe:
noise_free_quantum_environment = QuantumInstance(Aer.get_backend('statevector_simulator'))
solver = VQE(ansatz=trial_state, quantum_instance=noise_free_quantum_environment)
else:
solver = NumPyMinimumEigensolver()
# Step 4 and alternative
ground_state = GroundStateEigensolver(map_fermions_to_qubits, solver)
# Refinement to Step 4
energy_surface = BOPESSampler(gss=ground_state, bootstrap=False)
energy_surface_result = energy_surface.sample(
fermionic_hamiltonian, perturbation_steps
)
return energy_surface_result
###Output
_____no_output_____
###Markdown
Your answer
###Code
energy_surface_result =construct_hamiltonian_solve_ground_state(
macromolecule ,
num_electrons=2,
num_molecular_orbitals=2,
chemistry_inspired=True,
hardware_inspired_trial=None,
vqe=True,
perturbation_steps=np.linspace(-0.5,5, 30),)
plot_energy_landscape(energy_surface_result)
###Output
_____no_output_____
###Markdown
The following code cells give a skeleton to call `construct_hamiltonian_solve_ground_state` and plot the results. Once you are confident with your results, submit them in the code-cell that follows.**Note: `construct_hamiltonian_solve_ground_state` will take some time to run (approximately 2 minutes). Do not worry if it doesn't return a result immediately.**
###Code
# Q1
# Calculate the energies
#q1_energy_surface_result = construct_hamiltonian_solve_ground_state(
# molecule=None,
# num_electrons=None,
# num_molecular_orbitals=None,
# chemistry_inspired=None,
# vqe=None,
# perturbation_steps=None,
#)
,
# Plot the energies to visualize the results
# plot_energy_landscape(energy_surface_result)
## Q2
# answer_for_ex3c_q2 = 'A'
# answer_for_ex3c_q2 = 'B'
# answer_for_ex3c_q2 = 'C'
# answer_for_ex3c_q2 = 'D'
answer_for_ex3c_q2 = 'D'
###Output
_____no_output_____
###Markdown
Once you are happy with the results you have acquired, submit the energies and parameters for `construct_hamiltonian_solve_ground_state` in the following cell. Change the values for all parameters, except `energy_surface`, to have the same value that you used in your call of `construct_hamiltonian_solve_ground_state`
###Code
from qc_grader import grade_ex3c
grade_ex3c(
energy_surface=energy_surface_result.energies, #q1_energy_surface_result.energies,
molecule=macromolecule ,
num_electrons=2,
num_molecular_orbitals=2,
chemistry_inspired=True,
hardware_inspired_trial=None,
vqe=True,
perturbation_steps=np.linspace(-0.5,5, 30),
q2_multiple_choice=answer_for_ex3c_q2
)
###Output
Submitting your answer for ex3/partC. Please wait...
Congratulations 🎉! Your answer is correct and has been submitted.
###Markdown
4. Refining Step 3a The last refinement is a lesson in how black-box tweaking can improve results.In Step 3a, the hardware_inspired_trial is designed to run on actual current-day hardware. Recall this line from the walk-through:
###Code
hardware_inspired_trial = TwoLocal(rotation_blocks = ['ry'], entanglement_blocks = 'cz',
entanglement='linear', reps=2)
###Output
_____no_output_____
###Markdown
Let us get a feel for the `reps` (repetition) parameter. This parameter controls how many rounds of mix and rotate are applied in the trial state. In more detail: there is an initial round of rotations, before mix (often containing no parameters) and another round of rotations are repeated. Certain gates don't generate parameters (e.g. `h`, `cz`). Each round of rotations adds an extra set of parameters that the classical optimizer adjusts in the search for the ground state.Let's relook at the simple hydrogen molecule and compute the "ideal" lowest energy electronic energy using the chemistry trial, the numpy solver and a single zero perturbation (i.e., no perturbations):
###Code
true_total_energy = construct_hamiltonian_solve_ground_state(
molecule=hydrogen_molecule_stretchable, # Step 1
num_electrons=2, # Step 2a
num_molecular_orbitals=2, # Step 2a
chemistry_inspired=True, # Step 3a
vqe=False, # Step 3b
perturbation_steps = [0]) # Step 4
plot_energy_landscape(true_total_energy)
###Output
Total Energy is: -1.1373060357533986 hartree
(No need to plot, only one configuration calculated.)
###Markdown
We take this as the true value for the rest of our experiment.*Next, select `chemistry_inspired=False`, `vqe=True` and pass in a hardware trial with 1 round*:
###Code
hardware_inspired_trial = TwoLocal(rotation_blocks = ['ry'], entanglement_blocks = 'cz',
entanglement='linear', reps=1)
quantum_calc_total_energy = construct_hamiltonian_solve_ground_state(
molecule=hydrogen_molecule_stretchable, # Step 1
num_electrons=2, # Step 2a
num_molecular_orbitals=2, # Step 2a
chemistry_inspired=False, # Step 3a
hardware_inspired_trial=hardware_inspired_trial, # Step 3a
vqe=True, # Step 3b
perturbation_steps = [0]) # Step 4
plot_energy_landscape(quantum_calc_total_energy)
###Output
Total Energy is: -1.1169984885197866 hartree
(No need to plot, only one configuration calculated.)
###Markdown
*Notice the difference is small and positive:*
###Code
quantum_calc_total_energy.energies[0] - true_total_energy.energies[0]
###Output
_____no_output_____
###Markdown
*Let's see how many parameters are used to specify the trial state:*
###Code
total_number_of_parameters = len(hardware_inspired_trial._ordered_parameters)
print("Total number of adjustable parameters: ", total_number_of_parameters)
hardware_inspired_trial2 = TwoLocal(rotation_blocks = ['ry'], entanglement_blocks = 'cz',
entanglement='linear', reps=2)
quantum_calc_total_energy2 = construct_hamiltonian_solve_ground_state(
molecule=hydrogen_molecule_stretchable, # Step 1
num_electrons=2, # Step 2a
num_molecular_orbitals=2, # Step 2a
chemistry_inspired=False, # Step 3a
hardware_inspired_trial=hardware_inspired_trial2, # Step 3a
vqe=True, # Step 3b
perturbation_steps = [0]) # Step 4
plot_energy_landscape(quantum_calc_total_energy2)
quantum_calc_total_energy2.energies[0] - true_total_energy.energies[0]
total_number_of_parameters2 = len(hardware_inspired_trial2._ordered_parameters)
print("Total number of adjustable parameters: ", total_number_of_parameters2)
###Output
Total number of adjustable parameters: 12
###Markdown
Exercise 3d: The effect of more repetitions Q1: Try reps equal to 1 (done for you) and 2 and compare the errors. What happens to the error? Does it increase, decrease, or stay the same?Be aware that: - VQE is a statistical algorithm, so run it a few times before observing the pattern. - Going beyond 2 may not continue the pattern. - Note that `reps` is defined in `TwoLocal`Q2: Check the total number of parameters for reps equal 1 and 2. How many parameters are introduced per round of rotations? Write your answer here: **Enter your answer to the first multiple choice question in the code-cell below and add your answer for Q2. Run the cell to submit your answers.**
###Code
from qc_grader import grade_ex3d
## Q1
# answer_for_ex3d_q1 = 'decreases'
# answer_for_ex3d_q1 = 'increases'
# answer_for_ex3d_q1 = 'stays the same'
##
answer_for_ex3d_q1 = 'decreases'
## Q2
answer_for_ex3d_q2 = 4
##
grade_ex3d(answer_for_ex3d_q1, answer_for_ex3d_q2)
###Output
Submitting your answer for ex3/partD. Please wait...
Congratulations 🎉! Your answer is correct and has been submitted.
###Markdown
Exercise 3e: Open-ended: Find the best hardware_inspired_trial to minimize the Energy Error for the Macromolecule Turning to the macromolecule again. Using, `chemistry_inspired=False`, `vqe=True`, `perturbation_steps = [0]`, a maximum of 8 qubits, and your own hardware_inspired_trial with any combination of options from the walk-through; find the lowest energy. Your answer to this exercise includes all parameters passed to `construct_hamiltonian_solve_ground_state` and the result object it returns. This exercise is scored based on how close your computed energy $E_{computed}$ is to the "true" minimum energy of the macromolecule $E_{true}$. This score is calculated as shown below, rounded to the nearest integer. $$\text{score} = -10 \times \log_{10}{\left(\left\lvert{\frac{E_{true} - E_{computed}}{E_{true}}}\right\rvert\right)}$$ Achieving a smaller error in your computed energy will increase your score. For example, if the true energy is -42.141 and you compute -40.0, you would have a score of 13. Use the following code cell to trial different `hardware_inspired_trial`s.
###Code
# Modify the following variables
num_electrons = 4
num_molecular_orbitals = 4
hardware_inspired_trial = TwoLocal(rotation_blocks = ['ry'], entanglement_blocks = 'cz',
entanglement='linear', reps=8)
#
computed_macromolecule_energy_result = construct_hamiltonian_solve_ground_state(
molecule=macromolecule,
num_electrons=num_electrons,
num_molecular_orbitals=num_molecular_orbitals,
chemistry_inspired=False,
hardware_inspired_trial=hardware_inspired_trial,
vqe=True,
perturbation_steps=[0],
)
plot_energy_landscape(computed_macromolecule_energy_result)
true_total_energy1 = construct_hamiltonian_solve_ground_state(
molecule=macromolecule, # Step 1
num_electrons=num_electrons, # Step 2a
num_molecular_orbitals=num_electrons, # Step 2a
chemistry_inspired=True, # Step 3a
vqe=False, # Step 3b
perturbation_steps = [0]) # Step 4
plot_energy_landscape(true_total_energy1)
true_total_energy1.energies[0]-computed_macromolecule_energy_result.energies[0]
###Output
_____no_output_____
###Markdown
Once you are ready to submit your answer, run the following code cell to have your computed energy scored. You can submit multiple times.
###Code
from qc_grader import grade_ex3e
grade_ex3e(
energy_surface_result=computed_macromolecule_energy_result,
molecule=macromolecule,
num_electrons=num_electrons,
num_molecular_orbitals=num_molecular_orbitals,
chemistry_inspired=False,
hardware_inspired_trial=hardware_inspired_trial,
vqe=True,
perturbation_steps=[0],
)
###Output
Submitting your answer for ex3/partE. Please wait...
Congratulations 🎉! Your answer is correct and has been submitted.
Your score is 55.
###Markdown
---------------- Quantum Chemistry Resources*Videos*- *Quantum Chemistry I: Obtaining the Qubit Hamiltonian* - https://www.youtube.com/watch?v=2XEjrwWhr88- *Quantum Chemistry II: Finding the Ground States* - https://www.youtube.com/watch?v=_UW6puuGa5E - https://www.youtube.com/watch?v=o4BAOKbcd3o*Tutorials*- https://qiskit.org/documentation/nature/tutorials/01_electronic_structure.html - https://qiskit.org/documentation/nature/tutorials/03_ground_state_solvers.html - https://qiskit.org/documentation/nature/tutorials/05_Sampling_potential_energy_surfaces.html*Code References*- UCCSD : https://qiskit.org/documentation/stubs/qiskit.chemistry.components.variational_forms.UCCSD.html- ActiveSpaceTransformer: https://qiskit.org/documentation/nature/stubs/qiskit_nature.transformers.second_quantization.electronic.ActiveSpaceTransformer.html?highlight=activespacetransformerqiskit_nature.transformers.second_quantization.electronic.ActiveSpaceTransformer Licensing and notes:- All images used, with gratitude, are listed below with their respective licenses: - https://de.wikipedia.org/wiki/Datei:Teppichschere.jpg by CrazyD is licensed under CC BY-SA 3.0 - https://commons.wikimedia.org/wiki/File:The_structure_of_the_immature_HIV-1_capsid_in_intact_virus_particles.png by MarinaVladivostok is licensed under CC0 1.0 - https://commons.wikimedia.org/wiki/File:Peptidformationball.svg by YassineMrabet is licensed under the public domain - The remaining images are either IBM-owned, or hand-generated by the authors of this notebook.- HCONH2 (Formamide) co-ordinates kindly provided by the National Library of Medicine: - `National Center for Biotechnology Information (2021). PubChem Compound Summary for CID 713, Formamide. https://pubchem.ncbi.nlm.nih.gov/compound/Formamide.`- For further information about the Pauli exclusion principle:https://en.wikipedia.org/wiki/Pauli_exclusion_principle- We would like to thank collaborators, Prof Yasien and Prof Munro from Wits for extensive assistance.- We would like to thank all the testers and feedback providers for their valuable input.
###Code
import qiskit.tools.jupyter
%qiskit_version_table
%qiskit_copyright
###Output
/opt/conda/lib/python3.8/site-packages/qiskit/aqua/__init__.py:86: DeprecationWarning: The package qiskit.aqua is deprecated. It was moved/refactored to qiskit-terra For more information see <https://github.com/Qiskit/qiskit-aqua/blob/main/README.md#migration-guide>
warn_package('aqua', 'qiskit-terra')
###Markdown
Simulating Language, Lab 3, Regularisation This week we'll be working with a simple Bayesian model of frequency learning. This simulation allows you to explore the effects of the prior and the data on frequency learning, as discussed in the lecture as a model of the Hudson-Kam & Newport (2005) experiment; next week we'll use the same model to move beyond studying individuals and start looking at cultural evolution. The codeThe basic framework is the same as the word learning code: after some preliminaries we lay out a hypothesis space, specify the likelihood and the prior, then we have everything we need to calculate the posterior and do Bayesian inference. All the details are different from the word learning lab, because we are modelling a different aspect of language learning, but the code will hopefully already look somewhat familiar. Libraries etcFirst, we'll load the `random` library (for generating random numbers) and the `prod` function (for multiplying a list of numbers), plus one more library for doing stuff with beta distributions, which we are using for our prior. We also have to load the plotting library and set up inline plots.
###Code
import random
from numpy import prod
from scipy.stats import beta
%matplotlib inline
import matplotlib.pyplot as plt
from IPython.display import set_matplotlib_formats
set_matplotlib_formats('svg', 'pdf')
###Output
_____no_output_____
###Markdown
Some useful functions for dealing with probabilitiesThe code starts with two functions we need for doing stuff with probabilities. You saw `normalize_probs` last week, it will take a list of numbers and normalise them for us (i.e. scaling them so they sum to 1). `roulette_wheel` takes a list of probabilities and selects a random index from that list, with probability of any particular index being selected being given by its probability (i.e. if index 0 has twice the probability as index 1, it's twice as likely to be selected). These functions are used elsewhere in the code, but it is not particularly important that you understand exactly how they work.
###Code
def normalize_probs(probs):
total = sum(probs) #calculates the summed probabilities
normedprobs = []
for p in probs:
normedprobs.append(p / total) #normalise - divide by summed probs
return normedprobs
def roulette_wheel(normedprobs):
r=random.random() #generate a random number between 0 and 1
accumulator = normedprobs[0]
for i in range(len(normedprobs)):
if r < accumulator:
return i
accumulator = accumulator + normedprobs[i + 1]
###Output
_____no_output_____
###Markdown
The hypothesis spaceThe main part of the code starts by laying out our hypothesis space, the candidate hypotheses that our learner is going to consider. As discussed in class, we are going to turn the problem of inferring a potentially continuous value (the probability with which your teacher uses word 1) into the problem of inferring one of a limited set of possible values (either your teacher is using the word with probability 0.005, or 0.015, or 0.025, etc). In the code we will refer to a certain probability of using word 1 as `pW1`. We will call the set of possible values for `pW1` the grid - you can set the granularity of the grid as high as you like, but 100 works OK without being too slow.
###Code
grid_granularity = 100 #How many values of pW1 do you want to consider? Setting this to 100.
grid_increment = 1 / grid_granularity
# sets up the grid of possible values of pW1 to consider
possible_pW1 = []
for i in range(grid_granularity):
possible_pW1.append(grid_increment / 2 + (grid_increment * i))
###Output
_____no_output_____
###Markdown
Have a look at `possible_pW1`. Does it look like you expected? One thing you might notice (you might already have noticed it last week), and be a bit surprised about, is that there are rounding errors! Instead of the probabilities in the grid being exactly 0.05 apart, sometimes the values are over or under by a tiny amount. Working with probabilities on a computer can be a problem, because the computer cannot exactly represent real numbers (i.e. numbers we would write in decimal notation, e.g. numbers like 0.1, 3.147). Your computer has a very large memory where it can store and manipulate numbers, but the problem is that this memory is necessarily finite (it has to fit in your computer) and there are infinitely many real numbers. Think of recurring decimal you get by dividing 1 by 3, 0.3333..., where the threes go on forever - it would take an infinite amount of space to exactly represent this number in your computer, and distinguish it from a very similar number, e.g. 0.33333... where the threes go on for a few thousand repetitions only. More relevantly for the rounding errors above, imagine how much memory it would take to distinguish 0.5 from 0.50000000000...00001, where there could be arbitrarily many decimal places. Spoiler: it would take an infinite memory to do this perfectly. So there’s no way your computer can exactly represent every possible real number. What it does instead is store numbers as accurately as it can, which involves introducing small rounding errors, rounding a number it can't represent to a number it can (and sometimes the results there are slightly un-intuitive to us, like rounding 0.035 to 0.034999999999999996). In fact your computer does its best to conceal these errors from you, and often displays numbers in a format that hides exactly what numbers it is actually working with. But you can see those rounding errors here. Next week we are going to be forced to introduce a technique to deal with these rounding errors otherwise they start causing glitches in the code, but for this week we'll try to live with them. Next up come the various functions we need for Bayesian inference. I will step through these gradually. The priorFor this model our prior is more complicated than last week - we are modelling the prior using a *beta distribution*, which is a family of probability distributions that can capture a uniform prior (representing an unbiased learner), a prior favouring regularity, or a prior favouring variability. The `calculate_prior` function calculates the prior probability of each of our possible values of `pW1`. The beta distribution, which is what we are using for our prior, is a standard probability distribution, so we can just use a function from a library (`beta.pdf`) to get the probability density for each value of `pW1`, then normalise those to convert them to probabilities. The `alpha` parameter determines the shape of our prior, and therefore the bias of our learners when it comes to inferring `pW1`.
###Code
def calculate_prior(alpha):
prior = []
for pW1 in possible_pW1:
prior.append(beta.pdf(pW1, alpha, alpha)) #look up the value using beta.pdf and add to our growing prior
return normalize_probs(prior) #normalize the final list so they are all probabilities
###Output
_____no_output_____
###Markdown
Plot some different prior probability distributions. To get a line graph, try typing e.g. ```pythonplt.plot(possible_pW1, calculate_prior(0.1))``` to see the prior probability distribution over various values of pW1 for the alpha=0.1 prior. Or, if you prefer a barplot (one bar per value of pW1) do ```pythonplt.bar(possible_pW1,calculate_prior(0.1),align='center',width=1./grid_granularity)``` (`align='center'` and `width=1./grid_granularity` makes sure your x-axis looks right and the bars line up where they should). Play around with the code, trying different values for the alpha parameter, to answer these three questions: - What values of alpha lead to a prior bias for regularity (i.e. higher prior probability for pW1 closer to 0 or 1)? - What values of alpha lead to a prior bias for variability (i.e. higher prior probability for pW1 closer to 0.5)? - What values of alpha lead to a completely unbiased learner (i.e. all values of pW1 are a priori equally likely)? Likelihood and productionIn order to do Bayesian inference, we need a likelihood function that tells us how probable some data is given a certain hypothesis (a value of `pW1`) - that's our `likelihood` function. Next week we are also going to need a way of modelling production - taking an individual, with a value of `pW1` in their head, and having them produce data that someone else can learn from. We'll specify that now too, it's called `produce`. We are going to model data - a sequence of utterances - as a simple list of 0s and 1s: the 0s correspond to occurrences of word 0, the 1s correspond to occurrences of word 1. For example, this is how we will represent a data set consisting of one occurence of word 0 and one occurence of word 1:```pythonsmall_data = [0,1]```How would you represent a dataset consisting of two occurences of word 0 and two occurences of word 1?Both the `likelihood` function and the `produce` function take as an argument the probability of word 1 being produced, `pW1`, and use that to calculate the probability of word 0 being produced (which is `1 - pW1`: in this model there are only two words, every time you produce an utterance you produce one or the other). The `likelihood` function calculates the likelihood of `data`, a list of utterances, given a particular value of `pW1`. The `produce` function generates some data for a speaker with a specific value of `pW1` in their head - you tell it how many productions you want (`n_productions`) and it spits out a list of data for you.
###Code
def likelihood(data, pW1):
pW0 = 1 - pW1 #probability of w0 is 1-prob of w1
probs = [pW0, pW1]
likelihoods = []
for d in data:
likelihood_this_item = probs[d] #d will be either 0 or 1, so we can use as an index
likelihoods.append(likelihood_this_item)
return prod(likelihoods) #multiply the probabilities of the individual data items
def produce(pW1, n_productions):
pW0 = 1- pW1
probs = [pW0, pW1]
data = []
for p in range(n_productions):
data.append(roulette_wheel(probs))
return data
###Output
_____no_output_____
###Markdown
- Test out the `produce` function - decide on a probability for w1 and then specify how many utterances you would like to produce. What kind of data will be produced if the probability of w1 is low? Or if it is high? Hint: `produce(0.1,10)` will produce 10 utterances with the probability of producing word 1 on each utterance being 0.1. - Next, check out the likelihood function - how does the likelihood of a set of data depend on the data and the probability of word 1? Hint: `likelihood([0,0,1,1],0.5)` will tell you the likelihood of producing word 0 twice then word 1 twice when the probability of producing word 1 each time is 0.5. Try plugging in different sequences of data and different values for `pW1`. Learning Now we have all the bits we need to calculate the posterior probability distribution - that's what the `posterior` function does, and it works in exactly the same way as the `posterior` function from lab 2. We are also going to make a function, with we will call `learn`, which picks a hypothesis (a value of pW1) based on its posterior probability - again, we'll be needing this next week, but you can play with it now.
###Code
def posterior(data, prior):
posterior_probs = [] #this list will hold the posterior for each possible value of pW1
for i in range(len(possible_pW1)): #work through the list of pW1 values, by index
pW1 = possible_pW1[i] #look up that value of pW1
p_h = prior[i] #look up the prior probability of this pW1
p_d = likelihood(data, pW1) #calculate the likelihood of data given this pW1
p_h_given_d = p_h * p_d #multiply prior x likelihood
posterior_probs.append(p_h_given_d)
return normalize_probs(posterior_probs) #normalise
def learn(data,prior):
posterior_probs = posterior(data, prior) #calculate the posterior
selected_index = roulette_wheel(posterior_probs) #select a random index from the posterior
return possible_pW1[selected_index] #look up the corresponding value of pW1
###Output
_____no_output_____
###Markdown
Домашнее задание Свойства матричных вычислений
###Code
import numpy as np
l = [[26, 18, 10, 18], [10, 13, 14, 12], [5, 13, 6, 11], [18, 16, 44, 10]]
A = np.array(l)
A
k = [[12, 18, 19, 14], [2, 4, 3, 12], [4, 5, 7, 74], [20, 21, 15, 42]]
B = np.array(k)
B
k = [[28, 14 , 17, 31], [4, 22, 11, 3], [17, 21, 15, 20], [17, 18, 0, 10]]
C = np.array(k)
C
###Output
_____no_output_____
###Markdown
Транспонирование матрицы:
###Code
A.transpose()
A.T
###Output
_____no_output_____
###Markdown
Дважды транспонированная матрица равна исходной матрице:
###Code
(A.T).T
###Output
_____no_output_____
###Markdown
Транспонирование суммы матриц равно сумме транспонированных матриц:
###Code
(A+B).T
A.T+B.T
###Output
_____no_output_____
###Markdown
Транспонирование произведения матриц равно произведению транспонированныхматриц расставленных в обратном порядке:
###Code
(A.dot(B)).T
(B.T).dot(A.T)
###Output
_____no_output_____
###Markdown
Транспонирование произведения матрицы на число равно произведению этогочисла на транспонированную матрицу:
###Code
t = 3
(t * A).T
t * (A.T)
###Output
_____no_output_____
###Markdown
Определители исходной и транспонированной матрицы совпадают:
###Code
format(np.linalg.det(A), '.9g')
format(np.linalg.det(A.T), '.9g')
###Output
_____no_output_____
###Markdown
Умножение матрицы на число
###Code
2 * A
###Output
_____no_output_____
###Markdown
Произведение единицы и любой заданной матрицы равно заданной матрице:
###Code
1 * A
###Output
_____no_output_____
###Markdown
Произведение нуля и любой матрицы равно нулевой матрице, размерность которойравна исходной матрицы:
###Code
0 * A
###Output
_____no_output_____
###Markdown
Произведение матрицы на сумму чисел равно сумме произведений матрицы накаждое из этих чисел:
###Code
(2 + 3) * A
2 * A + 3 * A
###Output
_____no_output_____
###Markdown
Произведение матрицы на произведение двух чисел равно произведению второгочисла и заданной матрицы, умноженному на первое число:
###Code
(2 * 3) * A
2 * (3 * A)
###Output
_____no_output_____
###Markdown
Произведение суммы матриц на число равно сумме произведений этих матриц назаданное число:
###Code
2 * (A + B)
2 * A + 2 * B
###Output
_____no_output_____
###Markdown
Сложение матриц
###Code
A + B
B + A
A + (B + C)
(A + B) + C
A + (-1)*A
###Output
_____no_output_____
###Markdown
Диаграмма матричного умножения
###Code
A.dot(B)
###Output
_____no_output_____
###Markdown
Ассоциативность умножения. Результат умножения матриц не зависит от порядка, вкотором будет выполняться эта операция:
###Code
A.dot(B.dot(C))
(A.dot(B)).dot(C)
###Output
_____no_output_____
###Markdown
Дистрибутивность умножения. Произведение матрицы на сумму матриц равносумме произведений матриц:
###Code
A.dot(B+C)
A.dot(B)+A.dot(C)
###Output
_____no_output_____
###Markdown
Умножение матриц в общем виде не коммутативно. Это означает, что для матриц невыполняется правило независимости произведения от перестановки множителей:
###Code
A.dot(B)
B.dot(A)
###Output
_____no_output_____
###Markdown
Произведение заданной матрицы на единичную равно исходной матрице:
###Code
E = np.matrix('1 0 0 0; 0 1 0 0; 0 0 1 0; 0 0 0 1')
E.dot(A)
A.dot(E)
###Output
_____no_output_____
###Markdown
Произведение заданной матрицы на нулевую матрицу равно нулевой матрице:
###Code
Z = np.matrix('0 0 0 0; 0 0 0 0; 0 0 0 0; 0 0 0 0')
Z.dot(A)
A.dot(Z)
###Output
_____no_output_____
###Markdown
Определитель матрицы
###Code
np.linalg.det(A)
###Output
_____no_output_____
###Markdown
Определитель матрицы остается неизменным при ее транспонировании:
###Code
round(np.linalg.det(A), 3)
round(np.linalg.det(A.T), 3)
###Output
_____no_output_____
###Markdown
Если у матрицы есть строка или столбец, состоящие из нулей, то определительтакой матрицы равен нулю:
###Code
N = np.matrix('3 2 3; 0 0 0; 12 4 5')
np.linalg.det(N)
###Output
_____no_output_____
###Markdown
При перестановке строк матрицы знак ее определителя меняется напротивоположный:
###Code
N = np.matrix('3 2 3; 5 6 9; 12 4 5')
round(np.linalg.det(N), 3)
N = np.matrix('5 6 9; 3 2 3; 12 4 5')
round(np.linalg.det(N), 3)
###Output
_____no_output_____
###Markdown
Если у матрицы есть две одинаковые строки, то ее определитель равен нулю:
###Code
N = np.matrix('3 2 3; 3 2 3; 12 4 5')
np.linalg.det(N)
###Output
_____no_output_____
###Markdown
Если все элементы строки или столбца матрицы умножить на какое-то число, то иопределитель будет умножен на это число:
###Code
N = np.matrix('3 5 3; 3 2 3; 12 4 5')
k = 2
M = N.copy()
M[2, :] = k * M[2, :]
print(M)
det_N = round(np.linalg.det(N), 3)
det_M = round(np.linalg.det(M), 3)
det_N * k
det_M
###Output
_____no_output_____
###Markdown
Если все элементы строки или столбца можно представить как сумму двухслагаемых, то определитель такой матрицы равен сумме определителей двух соответствующихматриц:
###Code
C = A.copy()
C[1, :] += B[1, :]
print(C)
A
B
round(np.linalg.det(C), 3)
round(np.linalg.det(A), 3) + round(np.linalg.det(B), 3)
###Output
_____no_output_____
###Markdown
Если к элементам одной строки прибавить элементы другой строки, умноженные наодно и тоже число, то определитель матрицы не изменится:
###Code
C = A.copy()
C[1, :] = C[1, :] + 2 * C[0, :]
A
C
round(np.linalg.det(A), 3)
round(np.linalg.det(C), 3)
###Output
_____no_output_____
###Markdown
Если строка или столбец матрицы является линейной комбинацией других строк(столбцов), то определитель такой матрицы равен нулю:
###Code
A[1, :] = A[0, :] + 2 * A[2, :]
round(np.linalg.det(A), 3)
###Output
_____no_output_____
###Markdown
Если матрица содержит пропорциональные строки, то ее определитель равен нулю:
###Code
A[1, :] = 2 * A[0, :]
A
round(np.linalg.det(A), 3)
###Output
_____no_output_____
###Markdown
Обратная матрица Обратная матрица обратной матрицы есть исходная матрица:
###Code
N = np.matrix('6 2; -7 12')
np.linalg.inv(N)
###Output
_____no_output_____
###Markdown
Обратная матрица транспонированной матрицы равна транспонированной матрицеот обратной матрицы:
###Code
np.linalg.inv(N.T)
(np.linalg.inv(N)).T
###Output
_____no_output_____
###Markdown
Обратная матрица произведения матриц равна произведению обратных матриц:
###Code
M = np.matrix('7. 2.; 6. 12.')
N = np.matrix('-1. 9.; 7. -8.')
np.linalg.inv(M.dot(N))
np.linalg.inv(N).dot(np.linalg.inv(M))
###Output
_____no_output_____
###Markdown
Матричный метод Рассмотрим систему линейных уравнений:* x-2y+3z-t=6* 2x+3y-4z+4t=-7* 3x+y-2z-2t=9* x-3y+7z+6t=-7 Создадим матрицу
###Code
K = np.array([[1., -2., 3., -1.], [2., 3., -4., 4.], [3., 1., -2., -2.], [1., -3., 7., 6.]])
K
###Output
_____no_output_____
###Markdown
Создадим вектор (правую часть системы)
###Code
L = np.array([6.,-7., 9., -7.])
L = L[:, np.newaxis]
L
N = np.linalg.inv(K)
print(N)
###Output
[[ 2.85714286e-01 1.42857143e-01 1.42857143e-01 7.40148683e-17]
[-5.02857143e+00 -2.31428571e+00 2.68571429e+00 1.60000000e+00]
[-2.85714286e+00 -1.42857143e+00 1.57142857e+00 1.00000000e+00]
[ 7.71428571e-01 4.85714286e-01 -5.14285714e-01 -2.00000000e-01]]
###Markdown
Для решения системы воспользуемся функцией numpy.linalg.solve
###Code
A = np.linalg.solve(K, L)
print(A)
B = (N.dot(L))
B
###Output
_____no_output_____
###Markdown
Метод Крамера Найти решение СЛАУ при помощи метода Крамера.* x-2y+3z-t=6* 2x+3y-4z+4t=-7* 3x+y-2z-2t=9* x-3y+7z+6t=-7 Вычисляем определитель матрицы системы:
###Code
K = np.array([[1., -2., 3., -1.], [2., 3., -4., 4.], [3., 1., -2., -2.], [1., -3., 7., 6.]])
L = np.array([[6.], [-7.], [9.], [-7.]])
D = round(np.linalg.det(K), 3)
D
J = np.copy(K)
J[:, 0] = L[:, 0]
J
D_1 = np.linalg.det(J)
D_1
J = np.copy(K)
J[:, 1] = L[:, 0]
D_2 = np.linalg.det(J)
D_2
J = np.copy(K)
J[:, 2] = L[:, 0]
D_3 = np.linalg.det(J)
D_3
J = np.copy(K)
J[:, 3] = L[:, 0]
D_4 = np.linalg.det(J)
D_4
print(
f" x = {D_1/D}"
f" y = {D_2/D}"
f" z = {D_3/D}"
f" t = {D_4/D}"
)
###Output
x = 1.999999999999999 y = -1.0000000000000002 z = 5.0753052554292856e-15 t = -2.000000000000002
###Markdown
Simple linear regression Import the data [pandas](https://pandas.pydata.org/) provides excellent data reading and querying module,[dataframe](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.html), which allows you to import structured data and perform SQL-like queries. Here we imported some house price records from [Trulia](https://www.trulia.com/?cid=sem|google|tbw_br_nat_x_x_nat!53f9be4f|Trulia-Exact_352364665_22475209465_aud-278383240986:kwd-1967776155_260498918114_). For more about extracting data from Trulia, please check [my previous tutorial](https://www.youtube.com/watch?v=qB418v3k2vk).
###Code
import pandas
df = pandas.read_excel('house_price.xlsx')
df[:10]
###Output
_____no_output_____
###Markdown
Prepare the data We want to use the price as the dependent variable and the area as the independent variable, i.e., use the house areas to predict the house prices
###Code
X = df['area']
print (X[:10])
X_reshape = X.values.reshape(-1,1) # reshape the X to a 2D array
print (X_reshape[:10])
y = df['price']
###Output
0 1541
1 1810
2 1456
3 2903
4 2616
5 3850
6 1000
7 920
8 2705
9 1440
Name: area, dtype: int64
[[1541]
[1810]
[1456]
[2903]
[2616]
[3850]
[1000]
[ 920]
[2705]
[1440]]
###Markdown
[sklearn](http://scikit-learn.org/stable/) provides a [split](http://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html) function that can split the data into training data and testing data.
###Code
import sklearn
from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X_reshape,y, test_size = 0.3) # put 30% data as the testing data
print ('number of training data:',len(X_train),len(y_train))
print ('number of testing data:',len(X_test),len(y_test))
###Output
number of training data: 28 28
number of testing data: 13 13
###Markdown
Train the model Use the [Linear Regression](http://scikit-learn.org/stable/modules/generated/sklearn.linear_model.LinearRegression.html) to estimate parameters from the training data.
###Code
from sklearn import linear_model
slr = linear_model.LinearRegression() #create an linear regression model objective
slr.fit(X_train,y_train) # estimate the patameters
print('beta',slr.coef_)
print('alpha',slr.intercept_)
###Output
beta [69.17060713]
alpha 195930.9472414695
###Markdown
Evaluate the model Let's calculate the [mean squared error](http://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_squared_error.htmlsklearn.metrics.mean_squared_error) and the [r square](http://scikit-learn.org/stable/modules/generated/sklearn.metrics.r2_score.htmlsklearn.metrics.r2_score) of the model based on the testing data.
###Code
from sklearn.metrics import mean_squared_error, r2_score
y_predict = slr.predict(X_test) # predict the Y based on the model
mean_squared_error = mean_squared_error(y_test,y_predict) # calculate mean square error
r2_score = r2_score(y_test,y_predict) #calculate r square
print ('mean square error:',mean_squared_error )
print ('r square:',r2_score )
###Output
mean square error: 7079477409.2479
r square: 0.6039126323520008
###Markdown
Visualize the model We use the [matplotlib](https://matplotlib.org/) to visualize our data.
###Code
import matplotlib.pyplot as plt
%matplotlib inline
plt.scatter(X_test, y_test, color='black') # create a scatterplot to visualize the test data
plt.plot(X_test, y_predict, color='blue', linewidth=3) # add a line chart to visualize the model
plt.xlabel('area')
plt.ylabel('price')
plt.show()
###Output
_____no_output_____
###Markdown
Домашнее задание Свойства матричных вычислений
###Code
import numpy as np
l = [[26, 18, 10, 18], [10, 13, 14, 12], [5, 13, 6, 11], [18, 16, 44, 10]]
A = np.array(l)
A
k = [[12, 18, 19, 14], [2, 4, 3, 12], [4, 5, 7, 74], [20, 21, 15, 42]]
B = np.array(k)
B
k = [[28, 14 , 17, 31], [4, 22, 11, 3], [17, 21, 15, 20], [17, 18, 0, 10]]
C = np.array(k)
C
###Output
_____no_output_____
###Markdown
Транспонирование матрицы:
###Code
A.transpose()
A.T
###Output
_____no_output_____
###Markdown
Дважды транспонированная матрица равна исходной матрице:
###Code
(A.T).T
###Output
_____no_output_____
###Markdown
Транспонирование суммы матриц равно сумме транспонированных матриц:
###Code
(A+B).T
A.T+B.T
###Output
_____no_output_____
###Markdown
Транспонирование произведения матриц равно произведению транспонированныхматриц расставленных в обратном порядке:
###Code
(A.dot(B)).T
(B.T).dot(A.T)
###Output
_____no_output_____
###Markdown
Транспонирование произведения матрицы на число равно произведению этогочисла на транспонированную матрицу:
###Code
t = 3
(t * A).T
t * (A.T)
###Output
_____no_output_____
###Markdown
Определители исходной и транспонированной матрицы совпадают:
###Code
format(np.linalg.det(A), '.9g')
format(np.linalg.det(A.T), '.9g')
###Output
_____no_output_____
###Markdown
Умножение матрицы на число
###Code
2 * A
###Output
_____no_output_____
###Markdown
Произведение единицы и любой заданной матрицы равно заданной матрице:
###Code
1 * A
###Output
_____no_output_____
###Markdown
Произведение нуля и любой матрицы равно нулевой матрице, размерность которойравна исходной матрицы:
###Code
0 * A
###Output
_____no_output_____
###Markdown
Произведение матрицы на сумму чисел равно сумме произведений матрицы накаждое из этих чисел:
###Code
(2 + 3) * A
2 * A + 3 * A
###Output
_____no_output_____
###Markdown
Произведение матрицы на произведение двух чисел равно произведению второгочисла и заданной матрицы, умноженному на первое число:
###Code
(2 * 3) * A
2 * (3 * A)
###Output
_____no_output_____
###Markdown
Произведение суммы матриц на число равно сумме произведений этих матриц назаданное число:
###Code
2 * (A + B)
2 * A + 2 * B
###Output
_____no_output_____
###Markdown
Сложение матриц
###Code
A + B
B + A
A + (B + C)
(A + B) + C
A + (-1)*A
###Output
_____no_output_____
###Markdown
Диаграмма матричного умножения
###Code
A.dot(B)
###Output
_____no_output_____
###Markdown
Ассоциативность умножения. Результат умножения матриц не зависит от порядка, вкотором будет выполняться эта операция:
###Code
A.dot(B.dot(C))
(A.dot(B)).dot(C)
###Output
_____no_output_____
###Markdown
Дистрибутивность умножения. Произведение матрицы на сумму матриц равносумме произведений матриц:
###Code
A.dot(B+C)
A.dot(B)+A.dot(C)
###Output
_____no_output_____
###Markdown
Умножение матриц в общем виде не коммутативно. Это означает, что для матриц невыполняется правило независимости произведения от перестановки множителей:
###Code
A.dot(B)
B.dot(A)
###Output
_____no_output_____
###Markdown
Произведение заданной матрицы на единичную равно исходной матрице:
###Code
E = np.matrix('1 0 0 0; 0 1 0 0; 0 0 1 0; 0 0 0 1')
E.dot(A)
A.dot(E)
###Output
_____no_output_____
###Markdown
Произведение заданной матрицы на нулевую матрицу равно нулевой матрице:
###Code
Z = np.matrix('0 0 0 0; 0 0 0 0; 0 0 0 0; 0 0 0 0')
Z.dot(A)
A.dot(Z)
###Output
_____no_output_____
###Markdown
Определитель матрицы
###Code
np.linalg.det(A)
###Output
_____no_output_____
###Markdown
Определитель матрицы остается неизменным при ее транспонировании:
###Code
round(np.linalg.det(A), 3)
round(np.linalg.det(A.T), 3)
###Output
_____no_output_____
###Markdown
Если у матрицы есть строка или столбец, состоящие из нулей, то определительтакой матрицы равен нулю:
###Code
N = np.matrix('3 2 3; 0 0 0; 12 4 5')
np.linalg.det(N)
###Output
_____no_output_____
###Markdown
При перестановке строк матрицы знак ее определителя меняется напротивоположный:
###Code
N = np.matrix('3 2 3; 5 6 9; 12 4 5')
round(np.linalg.det(N), 3)
N = np.matrix('5 6 9; 3 2 3; 12 4 5')
round(np.linalg.det(N), 3)
###Output
_____no_output_____
###Markdown
Если у матрицы есть две одинаковые строки, то ее определитель равен нулю:
###Code
N = np.matrix('3 2 3; 3 2 3; 12 4 5')
np.linalg.det(N)
###Output
_____no_output_____
###Markdown
Если все элементы строки или столбца матрицы умножить на какое-то число, то иопределитель будет умножен на это число:
###Code
N = np.matrix('3 5 3; 3 2 3; 12 4 5')
k = 2
M = N.copy()
M[2, :] = k * M[2, :]
print(M)
det_N = round(np.linalg.det(N), 3)
det_M = round(np.linalg.det(M), 3)
det_N * k
det_M
###Output
_____no_output_____
###Markdown
Если все элементы строки или столбца можно представить как сумму двухслагаемых, то определитель такой матрицы равен сумме определителей двух соответствующихматриц:
###Code
C = A.copy()
C[1, :] += B[1, :]
print(C)
A
B
round(np.linalg.det(C), 3)
round(np.linalg.det(A), 3) + round(np.linalg.det(B), 3)
###Output
_____no_output_____
###Markdown
Если к элементам одной строки прибавить элементы другой строки, умноженные наодно и тоже число, то определитель матрицы не изменится:
###Code
C = A.copy()
C[1, :] = C[1, :] + 2 * C[0, :]
A
C
round(np.linalg.det(A), 3)
round(np.linalg.det(C), 3)
###Output
_____no_output_____
###Markdown
Если строка или столбец матрицы является линейной комбинацией других строк(столбцов), то определитель такой матрицы равен нулю:
###Code
A[1, :] = A[0, :] + 2 * A[2, :]
round(np.linalg.det(A), 3)
###Output
_____no_output_____
###Markdown
Если матрица содержит пропорциональные строки, то ее определитель равен нулю:
###Code
A[1, :] = 2 * A[0, :]
A
round(np.linalg.det(A), 3)
###Output
_____no_output_____
###Markdown
Обратная матрица Обратная матрица обратной матрицы есть исходная матрица:
###Code
N = np.matrix('6 2; -7 12')
np.linalg.inv(N)
###Output
_____no_output_____
###Markdown
Обратная матрица транспонированной матрицы равна транспонированной матрицеот обратной матрицы:
###Code
np.linalg.inv(N.T)
(np.linalg.inv(N)).T
###Output
_____no_output_____
###Markdown
Обратная матрица произведения матриц равна произведению обратных матриц:
###Code
M = np.matrix('7. 2.; 6. 12.')
N = np.matrix('-1. 9.; 7. -8.')
np.linalg.inv(M.dot(N))
np.linalg.inv(N).dot(np.linalg.inv(M))
###Output
_____no_output_____
###Markdown
Матричный метод Рассмотрим систему линейных уравнений:* x-2y+3z-t=6* 2x+3y-4z+4t=-7* 3x+y-2z-2t=9* x-3y+7z+6t=-7 Создадим матрицу
###Code
K = np.array([[1., -2., 3., -1.], [2., 3., -4., 4.], [3., 1., -2., -2.], [1., -3., 7., 6.]])
K
###Output
_____no_output_____
###Markdown
Создадим вектор (правую часть системы)
###Code
L = np.array([[6.], [-7.], [9.], [-7.]])
L
K_inv = np.linalg.inv(K)
roK_inv @ L
###Output
_____no_output_____
###Markdown
Для решения системы воспользуемся функцией numpy.linalg.solve
###Code
np.linalg.solve(K, L)
###Output
_____no_output_____
###Markdown
Метод Крамера Найти решение СЛАУ при помощи метода Крамера.* x-2y+3z-t=6* 2x+3y-4z+4t=-7* 3x+y-2z-2t=9* x-3y+7z+6t=-7 Вычисляем определитель матрицы системы:
###Code
K = np.array([[1., -2., 3., -1.], [2., 3., -4., 4.], [3., 1., -2., -2.], [1., -3., 7., 6.]])
L = np.array([[6.], [-7.], [9.], [-7.]])
D = round(np.linalg.det(K), 3)
D
J = np.copy(K)
J[:, 0] = L[:, 0]
J
D_1 = np.linalg.det(J)
D_1
J = np.copy(K)
J[:, 1] = L[:, 0]
D_2 = np.linalg.det(J)
D_2
J = np.copy(K)
J[:, 2] = L[:, 0]
D_3 = np.linalg.det(J)
D_3
J = np.copy(K)
J[:, 3] = L[:, 0]
D_4 = np.linalg.det(J)
D_4
print(
f" x = {D_1/D}"
f" y = {D_2/D}"
f" z = {D_3/D}"
f" t = {D_4/D}"
)
###Output
x = 1.999999999999999 y = -0.9999999999999998 z = 0.0 t = -2.000000000000002
|
100-pandas-puzzles-with-solutions-cn.ipynb | ###Markdown
100 pandas puzzles 中文版受 [numpy-100](https://github.com/rougier/numpy-100) 的启发,本仓库将提供 100 个(仍在更新)小问题用于测试你对 Pandas 的掌握。Pandas 是一个具有非常多专业特性和功能的大型库,由于时间和能力所限,本仓库并不能全面涉及。本仓库设计的练习主要集中在利用 DataFrame 和 Series 对象操作数据的基础上(索引、分组、聚合、清洗)。许多问题的解决方案只需要几行代码,因此选择正确的方法和遵循最佳实践是基本目标。练习题将根据难度等级来划分,当然,这些等级是主观的,但也这些等级也可以作为难度的大致参考,让你对题目难度大致有个数。如果你刚刚接触 Pandas,那么以下是一些不错的学习资源方便你快速上手:- [10 minutes to pandas](http://pandas.pydata.org/pandas-docs/version/0.17.0/10min.html)- [pandas basics](http://pandas.pydata.org/pandas-docs/version/0.17.0/basics.html)- [tutorials](http://pandas.pydata.org/pandas-docs/stable/tutorials.html)- [cookbook and idioms](http://pandas.pydata.org/pandas-docs/version/0.17.0/cookbook.htmlcookbook)- [Guilherme Samora's pandas exercises](https://github.com/guipsamora/pandas_exercises)祝你玩的愉快!*关于 Pandas 的 100 题目目前还没有完成!如果你有想反馈或是改进的建议,欢迎提 PR 或是 issue。* 导入 Pandas 准备好使用 Pandas 吧!难度: *简单* **1.** 以 `pd` 别名导入 pandas 库
###Code
import pandas as pd
###Output
_____no_output_____
###Markdown
**2.** 打印出导入 pandas 库的版本信息
###Code
pd.__version__
###Output
_____no_output_____
###Markdown
**3.** 打印 pandas 依赖包及其 *版本* 信息
###Code
pd.show_versions()
###Output
_____no_output_____
###Markdown
DataFrame:基础知识 使用 DataFrame 进行选择、排序、添加以及聚合数据。难度: *简单*提示: 记得使用如下命令导入 numpy:```pythonimport numpy as np```有如下字典 `data` 以及列表 `labels`:``` pythondata = {'animal': ['cat', 'cat', 'snake', 'dog', 'dog', 'cat', 'snake', 'cat', 'dog', 'dog'], 'age': [2.5, 3, 0.5, np.nan, 5, 2, 4.5, np.nan, 7, 3], 'visits': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1], 'priority': ['yes', 'yes', 'no', 'yes', 'no', 'no', 'no', 'yes', 'no', 'no']}labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']```(这只是以动物和看兽医为主题编造的一些无意义的数据)**4.** 使用数据 `data` 和行索引 `labels` 创建一个 DataFrame `df`
###Code
import numpy as np
data = {'animal': ['cat', 'cat', 'snake', 'dog', 'dog', 'cat', 'snake', 'cat', 'dog', 'dog'],
'age': [2.5, 3, 0.5, np.nan, 5, 2, 4.5, np.nan, 7, 3],
'visits': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'priority': ['yes', 'yes', 'no', 'yes', 'no', 'no', 'no', 'yes', 'no', 'no']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
df = pd.DataFrame(data, index=labels)
###Output
_____no_output_____
###Markdown
**5.** 显示该 DataFrame 及其数据相关的基本信息(*提示:DataFrame 直接调用的方法*)
###Code
df.info()
# 或者
df.describe()
###Output
_____no_output_____
###Markdown
**6.** 返回 DataFrame `df` 的前三行数据
###Code
df.iloc[:3]
# 等价于
df.head(3)
###Output
_____no_output_____
###Markdown
**7.** 从 DataFrame `df` 选择标签为 `animal` 和 `age` 的列
###Code
df.loc[:, ['animal', 'age']]
# 或者
df[['animal', 'age']]
###Output
_____no_output_____
###Markdown
**8.** 在 `[3, 4, 8]` 行中 *且* 列为 `['animal', 'age']` 的数据
###Code
df.loc[df.index[[3, 4, 8]], ['animal', 'age']]
###Output
_____no_output_____
###Markdown
**9.** 选择 `visits` 大于 3 的行
###Code
df[df['visits'] > 3]
###Output
_____no_output_____
###Markdown
**10.** 选择 `age` 为缺失值的行,如 `NaN`
###Code
df[df['age'].isnull()]
###Output
_____no_output_____
###Markdown
**11.** 选择 `animal` 是 cat *且* `age` 小于 3 的行
###Code
df[(df['animal'] == 'cat') & (df['age'] < 3)]
###Output
_____no_output_____
###Markdown
**12.** 选择 `age` 在 2 到 4 之间的数据(包含边界值)
###Code
df[df['age'].between(2, 4)]
###Output
_____no_output_____
###Markdown
**13.** 将 'f' 行的 `age` 改为 1.5
###Code
df.loc['f', 'age'] = 1.5
###Output
_____no_output_____
###Markdown
**14.** 计算 `visits` 列的数据总和
###Code
df['visits'].sum()
###Output
_____no_output_____
###Markdown
**15.** 计算每种 `animal` `age` 的平均值
###Code
df.groupby('animal')['age'].mean()
###Output
_____no_output_____
###Markdown
**16.** 追加一行 k,列的数据自定义,然后再删除新追加的 k 行
###Code
df.loc['k'] = [5.5, 'dog', 'no', 2]
# 接着删除新添加的 k 行
df = df.drop('k')
###Output
_____no_output_____
###Markdown
**17.** 计算每种 `animal` 的总数
###Code
df['animal'].value_counts()
###Output
_____no_output_____
###Markdown
**18.** 先根据 `age` 降序排列,再根据 `visits` 升序排列(结果 `i` 列在前面,`d` 列在最后面)
###Code
df.sort_values(by=['age', 'visits'], ascending=[False, True])
###Output
_____no_output_____
###Markdown
**19.** 将 `priority` 列的 `yes` 和 `no` 用 `True` 和 `False` 替换
###Code
df['priority'] = df['priority'].map({'yes': True, 'no': False})
###Output
_____no_output_____
###Markdown
**20.** 将 `animal` 列的 `snake` 用 `python` 替换
###Code
df['animal'] = df['animal'].replace('snake', 'python')
###Output
_____no_output_____
###Markdown
**21.** 对于每种 `animal` 和 `visit`,求出平均年龄。换句话说,每一行都是动物,每一列都是访问次数,其值是平均年龄(提示:使用数据透视表)
###Code
df.pivot_table(index='animal', columns='visits', values='age', aggfunc='mean')
###Output
_____no_output_____
###Markdown
DataFrame:更上一层楼 有点困难了!你可能需要结合两种或以上的方法才能得到正确的解答。难度: *中等*上一章节是一些简单但是相当实用的 DataFrame 操作。本章节将介绍如何切割数据,但是并没有开箱即用的方法。 **22.** 假设现在有一个一列整数 `A` 的 DataFrame `df`,比如:```pythondf = pd.DataFrame({'A': [1, 2, 2, 3, 4, 5, 5, 5, 6, 7, 7]})```你怎么样把重复的数据去除?剩下的数据应该像下面一样:```python1, 2, 3, 4, 5, 6, 7```
###Code
df = pd.DataFrame({'A': [1, 2, 2, 3, 4, 5, 5, 5, 6, 7, 7]})
df.loc[df['A'].shift() != df['A']]
# Alternatively, we could use drop_duplicates() here. Note
# that this removes *all* duplicates though, so it won't
# work as desired if A is [1, 1, 2, 2, 1, 1] for example.
df.drop_duplicates(subset='A')
###Output
_____no_output_____
###Markdown
**23.** 给定一组随机数据```pythondf = pd.DataFrame(np.random.random(size=(5, 3))) a 5x3 frame of float values```如何使每个元素减去所在行的平均值?
###Code
df = pd.DataFrame(np.random.random(size=(5, 3)))
df.sub(df.mean(axis=1), axis=0)
###Output
_____no_output_____
###Markdown
**24.** 假设你有 10 列实数:```pythondf = pd.DataFrame(np.random.random(size=(5, 10)), columns=list('abcdefghij'))```返回数字总和最小那列的标签
###Code
df = pd.DataFrame(np.random.random(size=(5, 10)), columns=list('abcdefghij'))
df.sum().idxmin()
###Output
_____no_output_____
###Markdown
**25.** 如何计算一个 DataFrame 有多少唯一的行(即忽略所有重复的行)?```pythondf = pd.DataFrame(np.random.randint(0, 2, size=(10, 3)))```
###Code
df = pd.DataFrame(np.random.randint(0, 2, size=(10, 3)))
len(df) - df.duplicated(keep=False).sum()
# or perhaps more simply...
len(df.drop_duplicates(keep=False))
###Output
_____no_output_____
###Markdown
后面三题会更加难!做好准备了吗?**26.** 给定一个十列的 DataFrame `df`,每行恰好有 5 个 `NaN` 值,从中找出第三个是 `NaN` 值的列标签。返回结果如: `e, c, d, h, d`
###Code
nan = np.nan
data = [[0.04, nan, nan, 0.25, nan, 0.43, 0.71, 0.51, nan, nan],
[ nan, nan, nan, 0.04, 0.76, nan, nan, 0.67, 0.76, 0.16],
[ nan, nan, 0.5 , nan, 0.31, 0.4 , nan, nan, 0.24, 0.01],
[0.49, nan, nan, 0.62, 0.73, 0.26, 0.85, nan, nan, nan],
[ nan, nan, 0.41, nan, 0.05, nan, 0.61, nan, 0.48, 0.68]]
columns = list('abcdefghij')
df = pd.DataFrame(data, columns=columns)
(df.isnull().cumsum(axis=1) == 3).idxmax(axis=1)
###Output
_____no_output_____
###Markdown
**27.** DataFrame 如下 ```pythondf = pd.DataFrame({'grps': list('aaabbcaabcccbbc'), 'vals': [12,345,3,1,45,14,4,52,54,23,235,21,57,3,87]})```对于每组(即a,b,c 三组),找到三个数相加的最大和```grpsa 409b 156c 345```
###Code
df = pd.DataFrame({'grps': list('aaabbcaabcccbbc'),
'vals': [12,345,3,1,45,14,4,52,54,23,235,21,57,3,87]})
df.groupby('grps')['vals'].nlargest(3).sum(level=0)
###Output
_____no_output_____
###Markdown
**28.** `DataFrame` 数据如下,`A` 和 `B` 都是 0-100 之间(包括边界值)的数值,对 `A` 进行分段分组(i.e. `(0, 10]`, `(10, 20]`, ...),求每组内 `B` 的和。输出应该和下述一致:```A(0, 10] 635(10, 20] 360(20, 30] 315(30, 40] 306(40, 50] 750(50, 60] 284(60, 70] 424(70, 80] 526(80, 90] 835(90, 100] 852```
###Code
df = pd.DataFrame(np.random.RandomState(8765).randint(1, 101, size=(100, 2)), columns = ["A", "B"])
df.groupby(pd.cut(df['A'], np.arange(0, 101, 10)))['B'].sum()
###Output
_____no_output_____
###Markdown
DataFrame:向你发出挑战 这里可能需要一点突破常规的思维……但所有这些都可以使用通常的 pandas/NumPy 方法来解决(因此避免使用的`for` 循环来解决)。难度: *困难* **29.** 假设存在一列整数 `X````pythondf = pd.DataFrame({'X': [7, 2, 0, 3, 4, 2, 5, 0, 3, 4]})```对于每一个元素,计算其与上一个 `0` 或者列的开头之间的距离(哪一个更小就取哪个,若自身为 0 则值为 0),结果应该如下:```[1, 2, 0, 1, 2, 3, 4, 0, 1, 2]```生成新列 `Y`
###Code
df = pd.DataFrame({'X': [7, 2, 0, 3, 4, 2, 5, 0, 3, 4]})
izero = np.r_[-1, (df == 0).values.nonzero()[0]] # 零值的索引
idx = np.arange(len(df))
y = df['X'] != 0
df['Y'] = idx - izero[np.searchsorted(izero - 1, idx) - 1]
# http://stackoverflow.com/questions/30730981/how-to-count-distance-to-the-previous-zero-in-pandas-series/
# credit: Behzad Nouri
###Output
_____no_output_____
###Markdown
基于 [cookbook recipe](http://pandas.pydata.org/pandas-docs/stable/cookbook.htmlgrouping) 的另一种方法:
###Code
df = pd.DataFrame({'X': [7, 2, 0, 3, 4, 2, 5, 0, 3, 4]})
x = (df['X'] != 0).cumsum()
y = x != x.shift()
df['Y'] = y.groupby((y != y.shift()).cumsum()).cumsum()
###Output
_____no_output_____
###Markdown
使用 groupby 的方法也可以:
###Code
df = pd.DataFrame({'X': [7, 2, 0, 3, 4, 2, 5, 0, 3, 4]})
df['Y'] = df.groupby((df['X'] == 0).cumsum()).cumcount()
# 找到第一组的结束位置,对这个位置之前的所有值都 +1
first_zero_idx = (df['X'] == 0).idxmax()
df['Y'].iloc[0:first_zero_idx] += 1
###Output
_____no_output_____
###Markdown
**30.** 求出最大的三个值的索引位置,结果应该如下:```[(5, 7), (6, 4), (2, 5)]```
###Code
df = pd.DataFrame(np.random.RandomState(30).randint(1, 101, size=(8, 8)))
df.unstack().sort_values()[-3:].index.tolist()
# http://stackoverflow.com/questions/14941261/index-and-column-for-the-max-value-in-pandas-dataframe/
# credit: DSM
###Output
_____no_output_____
###Markdown
**31.** 给定如下数据```pythondf = pd.DataFrame({"vals": np.random.RandomState(31).randint(-30, 30, size=15), "grps": np.random.RandomState(31).choice(["A", "B"], 15)})```创建一个新列 `patched_values`,当 `vals`为正数时,`patched_value` 的值为`vals` 本身;当 `vals` 为负时,`patched_value` 的值等于所在组的正数的平均值``` vals grps patched_vals0 -12 A 13.61 -7 B 28.02 -14 A 13.63 4 A 4.04 -7 A 13.65 28 B 28.06 -2 A 13.67 -1 A 13.68 8 A 8.09 -2 B 28.010 28 A 28.011 12 A 12.012 16 A 16.013 -24 A 13.614 -12 A 13.6```
###Code
df = pd.DataFrame({"vals": np.random.RandomState(31).randint(-30, 30, size=15),
"grps": np.random.RandomState(31).choice(["A", "B"], 15)})
def replace(group):
mask = group<0
group[mask] = group[~mask].mean()
return group
df.groupby(['grps'])['vals'].transform(replace)
# http://stackoverflow.com/questions/14760757/replacing-values-with-groupby-means/
# credit: unutbu
###Output
_____no_output_____
###Markdown
**32.** 对窗口大小为 3 的组实施滚动均值,忽略 NaN 值,给定数据如下```python>>> df = pd.DataFrame({'group': list('aabbabbbabab'), 'value': [1, 2, 3, np.nan, 2, 3, np.nan, 1, 7, 3, np.nan, 8]})>>> df group value0 a 1.01 a 2.02 b 3.03 b NaN4 a 2.05 b 3.06 b NaN7 b 1.08 a 7.09 b 3.010 a NaN11 b 8.0```目标是计算该 Series```0 1.0000001 1.5000002 3.0000003 3.0000004 1.6666675 3.0000006 3.0000007 2.0000008 3.6666679 2.00000010 4.50000011 4.000000```例如,第一个大小为 3 的窗口 `b` 组的值为 3.0、NaN 和 3.0。在第三行索引的新列中的值应该是 3.0,而不是 NaN(用两个非 NaN 值来计算平均值(3+3)/2)。
###Code
df = pd.DataFrame({'group': list('aabbabbbabab'),
'value': [1, 2, 3, np.nan, 2, 3, np.nan, 1, 7, 3, np.nan, 8]})
g1 = df.groupby(['group'])['value'] # 进行分组
g2 = df.fillna(0).groupby(['group'])['value'] # 填充缺失值为 0
s = g2.rolling(3, min_periods=1).sum() / g1.rolling(3, min_periods=1).count() # 计算平均值
s.reset_index(level=0, drop=True).sort_index() # 重置索引
# http://stackoverflow.com/questions/36988123/pandas-groupby-and-rolling-apply-ignoring-nans/
###Output
_____no_output_____
###Markdown
Series 和 DatetimeIndex 使用时间数据创建和操作 Series 对象。难度: *简单/中等*pandas 在处理日期与时间方面非常出色,这部分将探索 pandas 这方面的功能。 **33.** 创建一个 Series `s`,其索引为 2015 年的工作日,值可以随机取
###Code
dti = pd.date_range(start='2015-01-01', end='2015-12-31', freq='B')
s = pd.Series(np.random.rand(len(dti)), index=dti)
s
###Output
_____no_output_____
###Markdown
**34.** 计算日期是周三(Wednesday)的值的总和
###Code
s[s.index.weekday == 2].sum()
###Output
_____no_output_____
###Markdown
**35.** 计算每个月的平均值
###Code
s.resample('M').mean()
###Output
_____no_output_____
###Markdown
**36.** 寻找每个季度内最大值所对应的日期
###Code
s.groupby(pd.Grouper(freq='4M')).idxmax()
###Output
_____no_output_____
###Markdown
**37.** 创建一个 DataTimeIndex,包含 2015 年至 2016 年每个月的第三个星期四
###Code
pd.date_range('2015-01-01', '2016-12-31', freq='WOM-3THU')
###Output
_____no_output_____
###Markdown
清理数据 让 DataFrame 更好协作。难度: *简单/中等*这种情况经常发生:有人给你包含畸形字符串、Python、列表和缺失数据的数据。你如何把它整理好,以便能继续分析?使用下面这些 ”怪兽“ 开始这一章的学习吧:```pythondf = pd.DataFrame({'From_To': ['LoNDon_paris', 'MAdrid_miLAN', 'londON_StockhOlm', 'Budapest_PaRis', 'Brussels_londOn'], 'FlightNumber': [10045, np.nan, 10065, np.nan, 10085], 'RecentDelays': [[23, 47], [], [24, 43, 87], [13], [67, 32]], 'Airline': ['KLM(!)', ' (12)', '(British Airways. )', '12. Air France', '"Swiss Air"']})```格式化后,是这样的:``` From_To FlightNumber RecentDelays Airline0 LoNDon_paris 10045.0 [23, 47] KLM(!)1 MAdrid_miLAN NaN [] (12)2 londON_StockhOlm 10065.0 [24, 43, 87] (British Airways. )3 Budapest_PaRis NaN [13] 12. Air France4 Brussels_londOn 10085.0 [67, 32] "Swiss Air"```(这是瞎编的一些飞行数据,没有任何实际意义。) **38.** Some values in the the **FlightNumber** column are missing (they are `NaN`). These numbers are meant to increase by 10 with each row so 10055 and 10075 need to be put in place. Modify `df` to fill in these missing numbers and make the column an integer column (instead of a float column).
###Code
df = pd.DataFrame({'From_To': ['LoNDon_paris', 'MAdrid_miLAN', 'londON_StockhOlm',
'Budapest_PaRis', 'Brussels_londOn'],
'FlightNumber': [10045, np.nan, 10065, np.nan, 10085],
'RecentDelays': [[23, 47], [], [24, 43, 87], [13], [67, 32]],
'Airline': ['KLM(!)', '<Air France> (12)', '(British Airways. )',
'12. Air France', '"Swiss Air"']})
df['FlightNumber'] = df['FlightNumber'].interpolate().astype(int)
df
###Output
_____no_output_____
###Markdown
**39.** The **From\_To** column would be better as two separate columns! Split each string on the underscore delimiter `_` to give a new temporary DataFrame called 'temp' with the correct values. Assign the correct column names 'From' and 'To' to this temporary DataFrame.
###Code
temp = df.From_To.str.split('_', expand=True)
temp.columns = ['From', 'To']
temp
###Output
_____no_output_____
###Markdown
**40.** Notice how the capitalisation of the city names is all mixed up in this temporary DataFrame 'temp'. Standardise the strings so that only the first letter is uppercase (e.g. "londON" should become "London".)
###Code
temp['From'] = temp['From'].str.capitalize()
temp['To'] = temp['To'].str.capitalize()
temp
###Output
_____no_output_____
###Markdown
**41.** Delete the From_To column from **41.** Delete the **From_To** column from `df` and attach the temporary DataFrame 'temp' from the previous questions.`df` and attach the temporary DataFrame from the previous questions.
###Code
df = df.drop('From_To', axis=1)
df = df.join(temp)
df
###Output
_____no_output_____
###Markdown
**42**. In the **Airline** column, you can see some extra puctuation and symbols have appeared around the airline names. Pull out just the airline name. E.g. `'(British Airways. )'` should become `'British Airways'`.
###Code
df['Airline'] = df['Airline'].str.extract('([a-zA-Z\s]+)', expand=False).str.strip()
# note: using .strip() gets rid of any leading/trailing spaces
df
###Output
_____no_output_____
###Markdown
**43**. In the **RecentDelays** column, the values have been entered into the DataFrame as a list. We would like each first value in its own column, each second value in its own column, and so on. If there isn't an Nth value, the value should be NaN.Expand the Series of lists into a new DataFrame named 'delays', rename the columns 'delay_1', 'delay_2', etc. and replace the unwanted RecentDelays column in `df` with 'delays'.
###Code
# there are several ways to do this, but the following approach is possibly the simplest
delays = df['RecentDelays'].apply(pd.Series)
delays.columns = ['delay_{}'.format(n) for n in range(1, len(delays.columns)+1)]
df = df.drop('RecentDelays', axis=1).join(delays)
df
###Output
_____no_output_____
###Markdown
The DataFrame should look much better now:``` FlightNumber Airline From To delay_1 delay_2 delay_30 10045 KLM London Paris 23.0 47.0 NaN1 10055 Air France Madrid Milan NaN NaN NaN2 10065 British Airways London Stockholm 24.0 43.0 87.03 10075 Air France Budapest Paris 13.0 NaN NaN4 10085 Swiss Air Brussels London 67.0 32.0 NaN``` Pandas 多层索引 为 Pandas 添加多层索引!难度: *中等*Previous exercises have seen us analysing data from DataFrames equipped with a single index level. However, pandas also gives you the possibilty of indexing your data using *multiple* levels. This is very much like adding new dimensions to a Series or a DataFrame. For example, a Series is 1D, but by using a MultiIndex with 2 levels we gain of much the same functionality as a 2D DataFrame.The set of puzzles below explores how you might use multiple index levels to enhance data analysis.To warm up, we'll look make a Series with two index levels. **44**. Given the lists `letters = ['A', 'B', 'C']` and `numbers = list(range(10))`, construct a MultiIndex object from the product of the two lists. Use it to index a Series of random numbers. Call this Series `s`.
###Code
letters = ['A', 'B', 'C']
numbers = list(range(10))
mi = pd.MultiIndex.from_product([letters, numbers])
s = pd.Series(np.random.rand(30), index=mi)
s
###Output
_____no_output_____
###Markdown
**45.** Check the index of `s` is lexicographically sorted (this is a necessary proprty for indexing to work correctly with a MultiIndex).
###Code
s.index.is_lexsorted()
# or more verbosely...
s.index.lexsort_depth == s.index.nlevels
###Output
_____no_output_____
###Markdown
**46**. Select the labels `1`, `3` and `6` from the second level of the MultiIndexed Series.
###Code
s.loc[:, [1, 3, 6]]
###Output
_____no_output_____
###Markdown
**47**. Slice the Series `s`; slice up to label 'B' for the first level and from label 5 onwards for the second level.
###Code
s.loc[pd.IndexSlice[:'B', 5:]]
# or equivalently without IndexSlice...
s.loc[slice(None, 'B'), slice(5, None)]
###Output
_____no_output_____
###Markdown
**48**. Sum the values in `s` for each label in the first level (you should have Series giving you a total for labels A, B and C).
###Code
s.sum(level=0)
###Output
_____no_output_____
###Markdown
**49**. Suppose that `sum()` (and other methods) did not accept a `level` keyword argument. How else could you perform the equivalent of `s.sum(level=1)`?
###Code
# One way is to use .unstack()...
# This method should convince you that s is essentially just a regular DataFrame in disguise!
s.unstack().sum(axis=0)
###Output
_____no_output_____
###Markdown
**50**. Exchange the levels of the MultiIndex so we have an index of the form (letters, numbers). Is this new Series properly lexsorted? If not, sort it.
###Code
new_s = s.swaplevel(0, 1)
if not new_s.index.is_lexsorted():
new_s = new_s.sort_index()
new_s
###Output
_____no_output_____
###Markdown
扫雷 玩过扫雷吗?用 Pandas 生成数据。难度: *中等* 至 *困难*If you've ever used an older version of Windows, there's a good chance you've played with Minesweeper:- https://en.wikipedia.org/wiki/Minesweeper_(video_game)If you're not familiar with the game, imagine a grid of squares: some of these squares conceal a mine. If you click on a mine, you lose instantly. If you click on a safe square, you reveal a number telling you how many mines are found in the squares that are immediately adjacent. The aim of the game is to uncover all squares in the grid that do not contain a mine.In this section, we'll make a DataFrame that contains the necessary data for a game of Minesweeper: coordinates of the squares, whether the square contains a mine and the number of mines found on adjacent squares. **51**. Let's suppose we're playing Minesweeper on a 5 by 4 grid, i.e.```X = 5Y = 4```To begin, generate a DataFrame `df` with two columns, `'x'` and `'y'` containing every coordinate for this grid. That is, the DataFrame should start:``` x y0 0 01 0 12 0 2...```
###Code
X = 5
Y = 4
p = pd.core.reshape.util.cartesian_product([np.arange(X), np.arange(Y)])
df = pd.DataFrame(np.asarray(p).T, columns=['x', 'y'])
df
###Output
_____no_output_____
###Markdown
**52**. For this DataFrame `df`, create a new column of zeros (safe) and ones (mine). The probability of a mine occuring at each location should be 0.4.
###Code
# One way is to draw samples from a binomial distribution.
df['mine'] = np.random.binomial(1, 0.4, X*Y)
df
###Output
_____no_output_____
###Markdown
**53**. Now create a new column for this DataFrame called `'adjacent'`. This column should contain the number of mines found on adjacent squares in the grid. (E.g. for the first row, which is the entry for the coordinate `(0, 0)`, count how many mines are found on the coordinates `(0, 1)`, `(1, 0)` and `(1, 1)`.)
###Code
# Here is one way to solve using merges.
# It's not necessary the optimal way, just
# the solution I thought of first...
df['adjacent'] = \
df.merge(df + [ 1, 1, 0], on=['x', 'y'], how='left')\
.merge(df + [ 1, -1, 0], on=['x', 'y'], how='left')\
.merge(df + [-1, 1, 0], on=['x', 'y'], how='left')\
.merge(df + [-1, -1, 0], on=['x', 'y'], how='left')\
.merge(df + [ 1, 0, 0], on=['x', 'y'], how='left')\
.merge(df + [-1, 0, 0], on=['x', 'y'], how='left')\
.merge(df + [ 0, 1, 0], on=['x', 'y'], how='left')\
.merge(df + [ 0, -1, 0], on=['x', 'y'], how='left')\
.iloc[:, 3:]\
.sum(axis=1)
# An alternative solution is to pivot the DataFrame
# to form the "actual" grid of mines and use convolution.
# See https://github.com/jakevdp/matplotlib_pydata2013/blob/master/examples/minesweeper.py
from scipy.signal import convolve2d
mine_grid = df.pivot_table(columns='x', index='y', values='mine')
counts = convolve2d(mine_grid.astype(complex), np.ones((3, 3)), mode='same').real.astype(int)
df['adjacent'] = (counts - mine_grid).ravel('F')
###Output
_____no_output_____
###Markdown
**54**. For rows of the DataFrame that contain a mine, set the value in the `'adjacent'` column to NaN.
###Code
df.loc[df['mine'] == 1, 'adjacent'] = np.nan
###Output
_____no_output_____
###Markdown
**55**. Finally, convert the DataFrame to grid of the adjacent mine counts: columns are the `x` coordinate, rows are the `y` coordinate.
###Code
df.drop('mine', axis=1).set_index(['y', 'x']).unstack()
###Output
_____no_output_____
###Markdown
绘图 探索 Pandas 的部分绘图功能,了解数据的趋势。难度: *中等*To really get a good understanding of the data contained in your DataFrame, it is often essential to create plots: if you're lucky, trends and anomalies will jump right out at you. This functionality is baked into pandas and the puzzles below explore some of what's possible with the library.**56.** Pandas is highly integrated with the plotting library matplotlib, and makes plotting DataFrames very user-friendly! Plotting in a notebook environment usually makes use of the following boilerplate:```pythonimport matplotlib.pyplot as plt%matplotlib inlineplt.style.use('ggplot')```matplotlib is the plotting library which pandas' plotting functionality is built upon, and it is usually aliased to ```plt```.```%matplotlib inline``` tells the notebook to show plots inline, instead of creating them in a separate window. ```plt.style.use('ggplot')``` is a style theme that most people find agreeable, based upon the styling of R's ggplot package.For starters, make a scatter plot of this random data, but use black X's instead of the default markers. ```df = pd.DataFrame({"xs":[1,5,2,8,1], "ys":[4,2,1,9,6]})```Consult the [documentation](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.html) if you get stuck!
###Code
import matplotlib.pyplot as plt
%matplotlib inline
plt.style.use('ggplot')
df = pd.DataFrame({"xs":[1,5,2,8,1], "ys":[4,2,1,9,6]})
df.plot.scatter("xs", "ys", color = "black", marker = "x")
###Output
_____no_output_____
###Markdown
**57.** Columns in your DataFrame can also be used to modify colors and sizes. Bill has been keeping track of his performance at work over time, as well as how good he was feeling that day, and whether he had a cup of coffee in the morning. Make a plot which incorporates all four features of this DataFrame.(Hint: If you're having trouble seeing the plot, try multiplying the Series which you choose to represent size by 10 or more)*The chart doesn't have to be pretty: this isn't a course in data viz!*```df = pd.DataFrame({"productivity":[5,2,3,1,4,5,6,7,8,3,4,8,9], "hours_in" :[1,9,6,5,3,9,2,9,1,7,4,2,2], "happiness" :[2,1,3,2,3,1,2,3,1,2,2,1,3], "caffienated" :[0,0,1,1,0,0,0,0,1,1,0,1,0]})```
###Code
df = pd.DataFrame({"productivity":[5,2,3,1,4,5,6,7,8,3,4,8,9],
"hours_in" :[1,9,6,5,3,9,2,9,1,7,4,2,2],
"happiness" :[2,1,3,2,3,1,2,3,1,2,2,1,3],
"caffienated" :[0,0,1,1,0,0,0,0,1,1,0,1,0]})
df.plot.scatter("hours_in", "productivity", s = df.happiness * 30, c = df.caffienated)
###Output
_____no_output_____
###Markdown
**58.** What if we want to plot multiple things? Pandas allows you to pass in a matplotlib *Axis* object for plots, and plots will also return an Axis object.Make a bar plot of monthly revenue with a line plot of monthly advertising spending (numbers in millions)```df = pd.DataFrame({"revenue":[57,68,63,71,72,90,80,62,59,51,47,52], "advertising":[2.1,1.9,2.7,3.0,3.6,3.2,2.7,2.4,1.8,1.6,1.3,1.9], "month":range(12) })```
###Code
df = pd.DataFrame({"revenue":[57,68,63,71,72,90,80,62,59,51,47,52],
"advertising":[2.1,1.9,2.7,3.0,3.6,3.2,2.7,2.4,1.8,1.6,1.3,1.9],
"month":range(12)
})
ax = df.plot.bar("month", "revenue", color = "green")
df.plot.line("month", "advertising", secondary_y = True, ax = ax)
ax.set_xlim((-1,12))
###Output
_____no_output_____
###Markdown
Now we're finally ready to create a candlestick chart, which is a very common tool used to analyze stock price data. A candlestick chart shows the opening, closing, highest, and lowest price for a stock during a time window. The color of the "candle" (the thick part of the bar) is green if the stock closed above its opening price, or red if below.This was initially designed to be a pandas plotting challenge, but it just so happens that this type of plot is just not feasible using pandas' methods. If you are unfamiliar with matplotlib, we have provided a function that will plot the chart for you so long as you can use pandas to get the data into the correct format.Your first step should be to get the data in the correct format using pandas' time-series grouping function. We would like each candle to represent an hour's worth of data. You can write your own aggregation function which returns the open/high/low/close, but pandas has a built-in which also does this. The below cell contains helper functions. Call ```day_stock_data()``` to generate a DataFrame containing the prices a hypothetical stock sold for, and the time the sale occurred. Call ```plot_candlestick(df)``` on your properly aggregated and formatted stock data to print the candlestick chart.
###Code
#This function is designed to create semi-interesting random stock price data
import numpy as np
def float_to_time(x):
return str(int(x)) + ":" + str(int(x%1 * 60)).zfill(2) + ":" + str(int(x*60 % 1 * 60)).zfill(2)
def day_stock_data():
#NYSE is open from 9:30 to 4:00
time = 9.5
price = 100
results = [(float_to_time(time), price)]
while time < 16:
elapsed = np.random.exponential(.001)
time += elapsed
if time > 16:
break
price_diff = np.random.uniform(.999, 1.001)
price *= price_diff
results.append((float_to_time(time), price))
df = pd.DataFrame(results, columns = ['time','price'])
df.time = pd.to_datetime(df.time)
return df
def plot_candlestick(agg):
fig, ax = plt.subplots()
for time in agg.index:
ax.plot([time.hour] * 2, agg.loc[time, ["high","low"]].values, color = "black")
ax.plot([time.hour] * 2, agg.loc[time, ["open","close"]].values, color = agg.loc[time, "color"], linewidth = 10)
ax.set_xlim((8,16))
ax.set_ylabel("Price")
ax.set_xlabel("Hour")
ax.set_title("OHLC of Stock Value During Trading Day")
plt.show()
###Output
_____no_output_____
###Markdown
**59.** Generate a day's worth of random stock data, and aggregate / reformat it so that it has hourly summaries of the opening, highest, lowest, and closing prices
###Code
df = day_stock_data()
df.head()
df.set_index("time", inplace = True)
agg = df.resample("H").ohlc()
agg.columns = agg.columns.droplevel()
agg["color"] = (agg.close > agg.open).map({True:"green",False:"red"})
agg.head()
###Output
_____no_output_____
###Markdown
**60.** Now that you have your properly-formatted data, try to plot it yourself as a candlestick chart. Use the ```plot_candlestick(df)``` function above, or matplotlib's [```plot``` documentation](https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.plot.html) if you get stuck.
###Code
plot_candlestick(agg)
###Output
_____no_output_____ |
polygen/sample-pretrained.ipynb | ###Markdown
Copyright 2020 DeepMind Technologies LimitedLicensed under the Apache License, Version 2.0 (the "License");you may not use this file except in compliance with the License.You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, softwaredistributed 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 andlimitations under the License. Clone repo and import dependencies
###Code
!pip install tensorflow==1.15 dm-sonnet==1.36 tensor2tensor==1.14
import time
import numpy as np
import tensorflow.compat.v1 as tf
tf.logging.set_verbosity(tf.logging.ERROR) # Hide TF deprecation messages
import matplotlib.pyplot as plt
%cd /tmp
%rm -rf /tmp/deepmind_research
!git clone https://github.com/deepmind/deepmind-research.git \
/tmp/deepmind_research
%cd /tmp/deepmind_research/polygen
import modules
import data_utils
###Output
_____no_output_____
###Markdown
Download pre-trained model weights from Google Cloud Storage
###Code
!mkdir /tmp/vertex_model
!mkdir /tmp/face_model
!gsutil cp gs://deepmind-research-polygen/vertex_model.tar.gz /tmp/vertex_model/
!gsutil cp gs://deepmind-research-polygen/face_model.tar.gz /tmp/face_model/
!tar xvfz /tmp/vertex_model/vertex_model.tar.gz -C /tmp/vertex_model/
!tar xvfz /tmp/face_model/face_model.tar.gz -C /tmp/face_model/
###Output
_____no_output_____
###Markdown
Pre-trained model config
###Code
vertex_module_config=dict(
decoder_config=dict(
hidden_size=512,
fc_size=2048,
num_heads=8,
layer_norm=True,
num_layers=24,
dropout_rate=0.4,
re_zero=True,
memory_efficient=True
),
quantization_bits=8,
class_conditional=True,
max_num_input_verts=5000,
use_discrete_embeddings=True,
)
face_module_config=dict(
encoder_config=dict(
hidden_size=512,
fc_size=2048,
num_heads=8,
layer_norm=True,
num_layers=10,
dropout_rate=0.2,
re_zero=True,
memory_efficient=True,
),
decoder_config=dict(
hidden_size=512,
fc_size=2048,
num_heads=8,
layer_norm=True,
num_layers=14,
dropout_rate=0.2,
re_zero=True,
memory_efficient=True,
),
class_conditional=False,
decoder_cross_attention=True,
use_discrete_vertex_embeddings=True,
max_seq_length=8000,
)
###Output
_____no_output_____
###Markdown
Generate class-conditional samplesTry varying the `class_id` parameter to generate meshes from different object categories. Good classes to try are tables (49), lamps (30), and cabinets (32). We can also specify the maximum number of vertices / face indices we want to see in the generated meshes using `max_num_vertices` and `max_num_face_indices`. The code will keep generating batches of samples until there are at least `num_samples_min` complete samples with the required number of vertices / faces.`top_p_vertex_model` and `top_p_face_model` control how varied the outputs are, with `1.` being the most varied, and `0.` the least varied. `0.9` is a good value for both the vertex and face models.Sampling should take around 2-5 minutes with a colab GPU using the default settings depending on the object class.
###Code
class_id = '49) table' #@param ['0) airplane,aeroplane,plane','1) ashcan,trash can,garbage can,wastebin,ash bin,ash-bin,ashbin,dustbin,trash barrel,trash bin','2) bag,traveling bag,travelling bag,grip,suitcase','3) basket,handbasket','4) bathtub,bathing tub,bath,tub','5) bed','6) bench','7) birdhouse','8) bookshelf','9) bottle','10) bowl','11) bus,autobus,coach,charabanc,double-decker,jitney,motorbus,motorcoach,omnibus,passenger vehi','12) cabinet','13) camera,photographic camera','14) can,tin,tin can','15) cap','16) car,auto,automobile,machine,motorcar','17) cellular telephone,cellular phone,cellphone,cell,mobile phone','18) chair','19) clock','20) computer keyboard,keypad','21) dishwasher,dish washer,dishwashing machine','22) display,video display','23) earphone,earpiece,headphone,phone','24) faucet,spigot','25) file,file cabinet,filing cabinet','26) guitar','27) helmet','28) jar','29) knife','30) lamp','31) laptop,laptop computer','32) loudspeaker,speaker,speaker unit,loudspeaker system,speaker system','33) mailbox,letter box','34) microphone,mike','35) microwave,microwave oven','36) motorcycle,bike','37) mug','38) piano,pianoforte,forte-piano','39) pillow','40) pistol,handgun,side arm,shooting iron','41) pot,flowerpot','42) printer,printing machine','43) remote control,remote','44) rifle','45) rocket,projectile','46) skateboard','47) sofa,couch,lounge','48) stove','49) table','50) telephone,phone,telephone set','51) tower','52) train,railroad train','53) vessel,watercraft','54) washer,automatic washer,washing machine']
num_samples_min = 1 #@param
num_samples_batch = 8 #@param
max_num_vertices = 400 #@param
max_num_face_indices = 2000 #@param
top_p_vertex_model = 0.9 #@param
top_p_face_model = 0.9 #@param
tf.reset_default_graph()
# Build models
vertex_model = modules.VertexModel(**vertex_module_config)
face_model = modules.FaceModel(**face_module_config)
# Tile out class label to every element in batch
class_id = int(class_id.split(')')[0])
vertex_model_context = {'class_label': tf.fill([num_samples_batch,], class_id)}
vertex_samples = vertex_model.sample(
num_samples_batch, context=vertex_model_context,
max_sample_length=max_num_vertices, top_p=top_p_vertex_model,
recenter_verts=True, only_return_complete=True)
vertex_model_saver = tf.train.Saver(var_list=vertex_model.variables)
# The face model generates samples conditioned on a context, which here is
# the vertex model samples
face_samples = face_model.sample(
vertex_samples, max_sample_length=max_num_face_indices,
top_p=top_p_face_model, only_return_complete=True)
face_model_saver = tf.train.Saver(var_list=face_model.variables)
# Start sampling
start = time.time()
print('Generating samples...')
with tf.Session() as sess:
vertex_model_saver.restore(sess, '/tmp/vertex_model/model')
face_model_saver.restore(sess, '/tmp/face_model/model')
mesh_list = []
num_samples_complete = 0
while num_samples_complete < num_samples_min:
v_samples_np = sess.run(vertex_samples)
if v_samples_np['completed'].size == 0:
print('No vertex samples completed in this batch. Try increasing ' +
'max_num_vertices.')
continue
f_samples_np = sess.run(
face_samples,
{vertex_samples[k]: v_samples_np[k] for k in vertex_samples.keys()})
v_samples_np = f_samples_np['context']
num_samples_complete_batch = f_samples_np['completed'].sum()
num_samples_complete += num_samples_complete_batch
print('Num. samples complete: {}'.format(num_samples_complete))
for k in range(num_samples_complete_batch):
verts = v_samples_np['vertices'][k][:v_samples_np['num_vertices'][k]]
faces = data_utils.unflatten_faces(
f_samples_np['faces'][k][:f_samples_np['num_face_indices'][k]])
mesh_list.append({'vertices': verts, 'faces': faces})
end = time.time()
print('sampling time: {}'.format(end - start))
data_utils.plot_meshes(mesh_list, ax_lims=0.4)
###Output
_____no_output_____
###Markdown
Export meshes as `.obj` filesPick a `mesh_id` (starting at 0) corresponding to the samples generated above. Refresh the colab file browser to find an `.obj` file with the mesh data.
###Code
mesh_id = 4 #@param
data_utils.write_obj(
mesh_list[mesh_id]['vertices'], mesh_list[mesh_id]['faces'],
'mesh-{}.obj'.format(mesh_id))
###Output
_____no_output_____
###Markdown
Copyright 2020 DeepMind Technologies LimitedLicensed under the Apache License, Version 2.0 (the "License");you may not use this file except in compliance with the License.You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0Unless required by applicable law or agreed to in writing, softwaredistributed 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 andlimitations under the License. Clone repo and import dependencies
###Code
!pip install tensorflow==1.15
!pip install dm-sonnet==1.36
!pip install tensor2tensor==1.14
import time
import numpy as np
import tensorflow.compat.v1 as tf
tf.logging.set_verbosity(tf.logging.ERROR) # Hide TF deprecation messages
import matplotlib.pyplot as plt
!git clone https://github.com/deepmind/deepmind-research.git deepmind_research
%cd deepmind_research/polygen
import modules
import data_utils
###Output
_____no_output_____
###Markdown
Download pre-trained model weights from Google Cloud Storage
###Code
!mkdir /tmp/vertex_model
!mkdir /tmp/face_model
!gsutil cp gs://deepmind-research-polygen/vertex_model.tar.gz /tmp/vertex_model/
!gsutil cp gs://deepmind-research-polygen/face_model.tar.gz /tmp/face_model/
!tar xvfz /tmp/vertex_model/vertex_model.tar.gz -C /tmp/vertex_model/
!tar xvfz /tmp/face_model/face_model.tar.gz -C /tmp/face_model/
###Output
_____no_output_____
###Markdown
Pre-trained model config
###Code
vertex_module_config=dict(
decoder_config=dict(
hidden_size=512,
fc_size=2048,
num_heads=8,
layer_norm=True,
num_layers=24,
dropout_rate=0.4,
re_zero=True,
memory_efficient=True
),
quantization_bits=8,
class_conditional=True,
max_num_input_verts=5000,
use_discrete_embeddings=True,
)
face_module_config=dict(
encoder_config=dict(
hidden_size=512,
fc_size=2048,
num_heads=8,
layer_norm=True,
num_layers=10,
dropout_rate=0.2,
re_zero=True,
memory_efficient=True,
),
decoder_config=dict(
hidden_size=512,
fc_size=2048,
num_heads=8,
layer_norm=True,
num_layers=14,
dropout_rate=0.2,
re_zero=True,
memory_efficient=True,
),
class_conditional=False,
decoder_cross_attention=True,
use_discrete_vertex_embeddings=True,
max_seq_length=8000,
)
###Output
_____no_output_____
###Markdown
Generate class-conditional samplesTry varying the `class_id` parameter to generate meshes from different object categories. Good classes to try are tables (49), lamps (30), and cabinets (32). We can also specify the maximum number of vertices / face indices we want to see in the generated meshes using `max_num_vertices` and `max_num_face_indices`. The code will keep generating batches of samples until there are at least `num_samples_min` complete samples with the required number of vertices / faces.`top_p_vertex_model` and `top_p_face_model` control how varied the outputs are, with `1.` being the most varied, and `0.` the least varied. `0.9` is a good value for both the vertex and face models.Sampling should take around 2-5 minutes with a colab GPU using the default settings depending on the object class.
###Code
class_id = '49) table' #@param ['0) airplane,aeroplane,plane','1) ashcan,trash can,garbage can,wastebin,ash bin,ash-bin,ashbin,dustbin,trash barrel,trash bin','2) bag,traveling bag,travelling bag,grip,suitcase','3) basket,handbasket','4) bathtub,bathing tub,bath,tub','5) bed','6) bench','7) birdhouse','8) bookshelf','9) bottle','10) bowl','11) bus,autobus,coach,charabanc,double-decker,jitney,motorbus,motorcoach,omnibus,passenger vehi','12) cabinet','13) camera,photographic camera','14) can,tin,tin can','15) cap','16) car,auto,automobile,machine,motorcar','17) cellular telephone,cellular phone,cellphone,cell,mobile phone','18) chair','19) clock','20) computer keyboard,keypad','21) dishwasher,dish washer,dishwashing machine','22) display,video display','23) earphone,earpiece,headphone,phone','24) faucet,spigot','25) file,file cabinet,filing cabinet','26) guitar','27) helmet','28) jar','29) knife','30) lamp','31) laptop,laptop computer','32) loudspeaker,speaker,speaker unit,loudspeaker system,speaker system','33) mailbox,letter box','34) microphone,mike','35) microwave,microwave oven','36) motorcycle,bike','37) mug','38) piano,pianoforte,forte-piano','39) pillow','40) pistol,handgun,side arm,shooting iron','41) pot,flowerpot','42) printer,printing machine','43) remote control,remote','44) rifle','45) rocket,projectile','46) skateboard','47) sofa,couch,lounge','48) stove','49) table','50) telephone,phone,telephone set','51) tower','52) train,railroad train','53) vessel,watercraft','54) washer,automatic washer,washing machine']
num_samples_min = 1 #@param
num_samples_batch = 8 #@param
max_num_vertices = 400 #@param
max_num_face_indices = 2000 #@param
top_p_vertex_model = 0.9 #@param
top_p_face_model = 0.9 #@param
tf.reset_default_graph()
# Build models
vertex_model = modules.VertexModel(**vertex_module_config)
face_model = modules.FaceModel(**face_module_config)
# Tile out class label to every element in batch
class_id = int(class_id.split(')')[0])
vertex_model_context = {'class_label': tf.fill([num_samples_batch,], class_id)}
vertex_samples = vertex_model.sample(
num_samples_batch, context=vertex_model_context,
max_sample_length=max_num_vertices, top_p=top_p_vertex_model,
recenter_verts=True, only_return_complete=True)
vertex_model_saver = tf.train.Saver(var_list=vertex_model.variables)
# The face model generates samples conditioned on a context, which here is
# the vertex model samples
face_samples = face_model.sample(
vertex_samples, max_sample_length=max_num_face_indices,
top_p=top_p_face_model, only_return_complete=True)
face_model_saver = tf.train.Saver(var_list=face_model.variables)
# Start sampling
start = time.time()
print('Generating samples...')
with tf.Session() as sess:
vertex_model_saver.restore(sess, '/tmp/vertex_model/model')
face_model_saver.restore(sess, '/tmp/face_model/model')
mesh_list = []
num_samples_complete = 0
while num_samples_complete < num_samples_min:
v_samples_np = sess.run(vertex_samples)
if v_samples_np['completed'].size == 0:
print('No vertex samples completed in this batch. Try increasing ' +
'max_num_vertices.')
continue
f_samples_np = sess.run(
face_samples,
{vertex_samples[k]: v_samples_np[k] for k in vertex_samples.keys()})
v_samples_np = f_samples_np['context']
num_samples_complete_batch = f_samples_np['completed'].sum()
num_samples_complete += num_samples_complete_batch
print('Num. samples complete: {}'.format(num_samples_complete))
for k in range(num_samples_complete_batch):
verts = v_samples_np['vertices'][k][:v_samples_np['num_vertices'][k]]
faces = data_utils.unflatten_faces(
f_samples_np['faces'][k][:f_samples_np['num_face_indices'][k]])
mesh_list.append({'vertices': verts, 'faces': faces})
end = time.time()
print('sampling time: {}'.format(end - start))
data_utils.plot_meshes(mesh_list, ax_lims=0.4)
###Output
_____no_output_____
###Markdown
Export meshes as `.obj` filesPick a `mesh_id` (starting at 0) corresponding to the samples generated above. Refresh the colab file browser to find an `.obj` file with the mesh data.
###Code
mesh_id = 4 #@param
data_utils.write_obj(
mesh_list[mesh_id]['vertices'], mesh_list[mesh_id]['faces'],
'mesh-{}.obj'.format(mesh_id))
###Output
_____no_output_____ |
examples/bias-removal-optim_preproc_adult.ipynb | ###Markdown
###Code
!pip install git+https://[email protected]/adnanmasood/AIF360.git
###Output
Collecting git+https://****@github.com/bhomass/AIF360.git
Cloning https://****@github.com/bhomass/AIF360.git to /tmp/pip-req-build-igt74688
Running command git clone -q 'https://****@github.com/bhomass/AIF360.git' /tmp/pip-req-build-igt74688
Requirement already satisfied: numpy>=1.16 in /usr/local/lib/python3.6/dist-packages (from aif360==0.3.0) (1.18.5)
Requirement already satisfied: scipy>=1.2.0 in /usr/local/lib/python3.6/dist-packages (from aif360==0.3.0) (1.4.1)
Requirement already satisfied: pandas>=0.24.0 in /usr/local/lib/python3.6/dist-packages (from aif360==0.3.0) (1.0.5)
Requirement already satisfied: scikit-learn>=0.21 in /usr/local/lib/python3.6/dist-packages (from aif360==0.3.0) (0.22.2.post1)
Requirement already satisfied: matplotlib in /usr/local/lib/python3.6/dist-packages (from aif360==0.3.0) (3.2.2)
Requirement already satisfied: python-dateutil>=2.6.1 in /usr/local/lib/python3.6/dist-packages (from pandas>=0.24.0->aif360==0.3.0) (2.8.1)
Requirement already satisfied: pytz>=2017.2 in /usr/local/lib/python3.6/dist-packages (from pandas>=0.24.0->aif360==0.3.0) (2018.9)
Requirement already satisfied: joblib>=0.11 in /usr/local/lib/python3.6/dist-packages (from scikit-learn>=0.21->aif360==0.3.0) (0.15.1)
Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.6/dist-packages (from matplotlib->aif360==0.3.0) (0.10.0)
Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib->aif360==0.3.0) (1.2.0)
Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.6/dist-packages (from matplotlib->aif360==0.3.0) (2.4.7)
Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.6/dist-packages (from python-dateutil>=2.6.1->pandas>=0.24.0->aif360==0.3.0) (1.12.0)
Building wheels for collected packages: aif360
Building wheel for aif360 (setup.py) ... [?25l[?25hdone
Created wheel for aif360: filename=aif360-0.3.0-cp36-none-any.whl size=1226976 sha256=f7187afcfb557d8511fb8ddc5d9ebdac8864f1817f09783b9100c61f9beb1468
Stored in directory: /tmp/pip-ephem-wheel-cache-utd7e75k/wheels/b0/cb/cf/e61262f367d6e3f0d65ae1e5cb7809b5d9952f1c0e64eaae42
Successfully built aif360
Installing collected packages: aif360
Successfully installed aif360-0.3.0
###Markdown
Detecting and mitigating racial bias in income estimation it needs to know the attribute or attributes, called _protected attributes_, that are of interest: race is one example of a _protected attribute_ and age is a second.First, the process starts with a _training dataset_, which contains a sequence of instances, where each instance has two components: the features and the correct prediction for those features. Next, a machine learning algorithm is trained on this training dataset to produce a machine learning model. This generated model can be used to make a prediction when given a new instance. A second dataset with features and correct predictions, called a _test dataset_, is used to assess the accuracy of the model.Since this test dataset is the same format as the training dataset, a set of instances of features and prediction pairs, often these two datasets derive from the same initial dataset. A random partitioning algorithm is used to split the initial dataset into training and test datasets..
###Code
import sys
sys.path.append("../")
import numpy as np
import pandas as pd
from aif360.metrics import BinaryLabelDatasetMetric
from aif360.algorithms.preprocessing.optim_preproc import OptimPreproc
from aif360.algorithms.preprocessing.optim_preproc_helpers.data_preproc_functions\
import load_preproc_data_adult
from aif360.algorithms.preprocessing.optim_preproc_helpers.distortion_functions\
import get_distortion_adult
from aif360.algorithms.preprocessing.optim_preproc_helpers.opt_tools import OptTools
from IPython.display import Markdown, display
np.random.seed(1)
###Output
_____no_output_____
###Markdown
Step 2 Load dataset, specifying protected attribute, and split dataset into train and testIn Step 2 we load the initial dataset, setting the protected attribute to be race. We then splits the original dataset into training and testing datasets. A normal workflow would also use a test dataset for assessing the efficacy (accuracy, fairness, etc.) during the development of a machine learning model. Finally, we set two variables (to be used in Step 3) for the privileged (1) and unprivileged (0) values for the race attribute. These are key inputs for detecting and mitigating bias, which will be Step 3 and Step 4.
###Code
dataset_orig = load_preproc_data_adult(['race'])
dataset_orig_train, dataset_orig_test = dataset_orig.split([0.7], shuffle=True)
privileged_groups = [{'race': 1}] # White
unprivileged_groups = [{'race': 0}] # Not white
###Output
_____no_output_____
###Markdown
Step 3 Compute fairness metric on original training datasetNow that we've identified the protected attribute 'race' and defined privileged and unprivileged values, we can detect bias in the dataset. One simple test is to compare the percentage of favorable results for the privileged and unprivileged groups, subtracting the former percentage from the latter. A negative value indicates less favorable outcomes for the unprivileged groups. This is implemented in the method called mean_difference on the BinaryLabelDatasetMetric class. The code below performs this check and displays the output:
###Code
metric_orig_train = BinaryLabelDatasetMetric(dataset_orig_train,
unprivileged_groups=unprivileged_groups,
privileged_groups=privileged_groups)
display(Markdown("#### Original training dataset"))
print("Difference in mean outcomes between unprivileged and privileged groups = %f" % metric_orig_train.mean_difference())
###Output
_____no_output_____
###Markdown
Step 4 Mitigate bias by transforming the original datasetThe previous step showed that the privileged group was getting 10.5% more positive outcomes in the training dataset. Since this is not desirable, we are going to try to mitigate this bias in the training dataset. Optimized preprocessing algorithm will transform the dataset to have more equity in positive outcomes on the protected attribute for the privileged and unprivileged groups.The algorithm requires some tuning parameters, which are set in the optim_options variable and passed as an argument along with some other parameters, including the 2 variables containg the unprivileged and privileged groups defined in Step 3.We then call the fit and transform methods to perform the transformation, producing a newly transformed training dataset (dataset_transf_train). Finally, we ensure alignment of features between the transformed and the original dataset to enable comparisons.[1] Optimized Pre-Processing for Discrimination Prevention, NIPS 2017, Flavio Calmon, Dennis Wei, Bhanukiran Vinzamuri, Karthikeyan Natesan Ramamurthy, and Kush R. Varshney
###Code
optim_options = {
"distortion_fun": get_distortion_adult,
"epsilon": 0.05,
"clist": [0.99, 1.99, 2.99],
"dlist": [.1, 0.05, 0]
}
OP = OptimPreproc(OptTools, optim_options)
OP = OP.fit(dataset_orig_train)
dataset_transf_train = OP.transform(dataset_orig_train, transform_Y=True)
dataset_transf_train = dataset_orig_train.align_datasets(dataset_transf_train)
print(dataset_transf_train)
# To export the dataset
#pd.set_option('display.max_rows', 50)
#from google.colab import drive
# Mount your Drive to the Colab VM.
#drive.mount('/gdrive')
#data = pd.DataFrame()
#data, _ = dataset_transf_train.convert_to_dataframe()
# Write the DataFrame to CSV file.
#with open('/gdrive/My Drive/output/dataset.csv', 'w') as f:
# data.to_csv(f)
#print ("completed")
###Output
_____no_output_____
###Markdown
Step 5 Compute fairness metric on transformed datasetNow that we have a transformed dataset, we can check how effective it was in removing bias by using the same metric we used for the original training dataset in Step 3. Once again, we use the function mean_difference in the BinaryLabelDatasetMetric class:
###Code
metric_transf_train = BinaryLabelDatasetMetric(dataset_transf_train,
unprivileged_groups=unprivileged_groups,
privileged_groups=privileged_groups)
display(Markdown("#### Transformed training dataset"))
print("Difference in mean outcomes between unprivileged and privileged groups = %f" % metric_transf_train.mean_difference())
###Output
_____no_output_____ |
avocado_linear_regression/avocados.ipynb | ###Markdown
Avocado DatasetLinear regression for Avocados price predition without the implementation of any high level Python library.Create a linear regression model estimating the function f that represents the price of Avocados based on historical data. This should be done using only numpy and basic python - i.e not using higher-level packages. Basic machine learning consideration when preprocessing and handling data need to be taken in consideration. Lines of code should be commented thoroughly to show understanding.Dataset:https://drive.google.com/file/d/1rhRzA2s44I8ASm_bMHnCpmAz_mNJQ7M3/view?usp=s haring
###Code
#ignore warnings
import warnings
warnings.filterwarnings("ignore")
#import plotting libraries, pandas and numpy
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
###Output
_____no_output_____
###Markdown
read CVS file with pandas and extract infoFetch some relevant columns from the data
###Code
avocados = pd.read_csv('avocado.csv')
avocados.head()
avocados.info()
avocados.describe()
avocados.columns
###Output
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 18249 entries, 0 to 18248
Data columns (total 14 columns):
Unnamed: 0 18249 non-null int64
Date 18249 non-null object
AveragePrice 18249 non-null float64
Total Volume 18249 non-null float64
4046 18249 non-null float64
4225 18249 non-null float64
4770 18249 non-null float64
Total Bags 18249 non-null float64
Small Bags 18249 non-null float64
Large Bags 18249 non-null float64
XLarge Bags 18249 non-null float64
type 18249 non-null object
year 18249 non-null int64
region 18249 non-null object
dtypes: float64(9), int64(2), object(3)
memory usage: 1.9+ MB
###Markdown
Date - The date of the observation AveragePrice - the average price of a single avocado type - conventional or organic year - the year Region - the city or region of the observation Total Volume - Total number of avocados sold 4046 - Total number of avocados with PLU 4046 sold 4225 - Total number of avocados with PLU 4225 sold 4770 - Total number of avocados with PLU 4770 sold
###Code
### the col 4-5-6 refer to price lookup codes as explained by the Kaggle dataset page: https://www.kaggle.com/neuromusic/avocado-prices
avocados.head()
### Group by provenience
provenience = avocados.groupby('region').sum()
provenience.head()
###Output
_____no_output_____
###Markdown
A bit of data Cleaning!
###Code
### check for null values
null = avocados.isnull().sum()
print(null)
# Data augmentation
avocados = avocados.apply(lambda n : n /2 if n.dtype=='float' else n, axis='columns')
#create Custom column for individual avocado price
avocados.assign(price=(avocados.AveragePrice/avocados['Total Volume'])).head()
###Output
_____no_output_____
###Markdown
Data Vizualisation plotting inspired by the blog: https://www.kaggle.com/rishpande/avocado-prices-data-visualization-beginner
###Code
#let's have a look at the dataset just for the Average price
avocados.AveragePrice.head(10).plot.bar()
# Split Date into 3 different columns
avocados['Year'], avocados['Month'], avocados['Day'] = avocados['Date'].str.split('-').str
###Output
_____no_output_____
###Markdown
Trends for the Average Price by Month for the Conventional / Organic type of Avocados
###Code
plt.figure(figsize=(18,10))
sns.lineplot(x="Month", y="AveragePrice", hue='type', data=avocados)
plt.show()
###Output
_____no_output_____
###Markdown
Trends for the Average Price by year across the months
###Code
plt.figure(figsize=(18,10))
sns.lineplot(x="Month", y="AveragePrice", hue='year', data=avocados)
plt.show()
###Output
_____no_output_____
###Markdown
Trends for the Total Volume with the AveragePrice
###Code
Year = avocados[['Total Volume' ,'AveragePrice']].groupby(avocados.year).sum()
Year.plot(kind='line', fontsize = 14,figsize=(14,8))
plt.show()
## Convert categorical data to numeric
def mapping(data,feature):
featureMap=dict()
count=0
for i in sorted(data[feature].unique(),reverse=True):
featureMap[i]=count
count=count+1
data[feature]=data[feature].map(featureMap)
return data
data=mapping(avocados,"type")
data=mapping(avocados,"region")
#drop useless cols
data=data.drop(["Unnamed: 0", "Date", "Year"],axis=1)
data.sample(5)
###Output
_____no_output_____
###Markdown
Plot distribution of the Prices (this case the values are left skewed)
###Code
sns.distplot(data['AveragePrice'])
## By plotting the correlation between data points from the columns it's possible to identify the linear correlation between features.
def plotFeatures(col_list,title):
plt.figure(figsize=(15, 18))
i = 0
print(len(col_list))
for col in col_list:
i+=1
plt.subplot(10,2,i)
plt.plot(data[col],data["AveragePrice"],marker='.',linestyle='none')
plt.title(title % (col))
plt.tight_layout()
colnames = ['Total Volume', '4046', '4225', '4770', 'Total Bags', 'Small Bags', 'Large Bags', 'XLarge Bags', 'Day','Month','year']
plotFeatures(colnames,"Relationship between %s and Average pricing")
###Output
11
###Markdown
plotting Linear Regression using Seaborn
###Code
# Plot a linear regression between Total Volume and avrg. price
sns.lmplot(x='AveragePrice', y='Total Volume', data=data)
plt.show()
#Plotting residuals of a regression
#Residual plot of the regression between 'AveragePrice' and 'totalVolume'
sns.residplot(x='AveragePrice', y='Total Volume', data=data, color='green')
plt.show()
###Output
_____no_output_____
###Markdown
Normalising the dataset is an important part of handling imbalanced data. This time mean normalisation is utilised. Datetime has been omitted from normalisation.
###Code
#get only the columns to be normalised
cols_to_norm = [ 'Total Volume', '4046', '4225', '4770', 'Total Bags', 'Small Bags', 'Large Bags', 'XLarge Bags','type', 'region', 'AveragePrice']
data[cols_to_norm] = data[cols_to_norm].apply(lambda x: (x - x.min()) / (x.max() - x.min()))
#display dataframe where the normalisation has been applied to most columns apart from the datetime ones
data.head()
###Output
_____no_output_____
###Markdown
Example of Univariate Linear Regression by Volume Indentify a linear correlation between the dependable variable Price and the independent variable Total Volume. Least Square Methodidentify the best-fitted squareing distance between the data point and the regression line. Function: y = mean(Volume)+cmean = mean of x and YVolume= Volumecovariance = y-Intercept
###Code
# define X and Y
X = data['Total Volume'].values
Y = data['AveragePrice'].values
# calculate the Mean for X and Y
mean_x = np.mean(X)
mean_y = np.mean(Y)
number_values = len(X)
# Using the formula to calculate mean and c
numer = 0
denom = 0
for i in range(number_values):
numer += (X[i] - mean_x) * (Y[i] - mean_y)
denom += (X[i] - mean_x) ** 2
mean = numer / denom
c = mean_y - (m * mean_x)
# Print coefficients
print(mean, c)
# Plotting Values and Regression Line
max_x = np.max(X)
min_x = np.min(X)
# Calculating line values x and y
x = np.linspace(min_x, max_x, 1000)
y = c + mean * x
# Ploting Line
plt.plot(x, y, color='#008080', label='Regression Line')
# Ploting Scatter Points
plt.scatter(X, Y, c='#008080', label='Data points')
plt.xlabel('Volume')
plt.ylabel('Price')
plt.legend()
plt.show()
###Output
_____no_output_____ |
Chapter-05/5.3 Summarizing and Computing Descriptive Statistics(总结和描述性统计).ipynb | ###Markdown
5.3 Summarizing and Computing Descriptive Statistics(汇总和描述性统计)pandas有很多数学和统计方法。大部分可以归类为降维或汇总统计,这些方法是用来从series中提取单个值(比如sum或mean)。还有一些方法来处理缺失值:
###Code
import pandas as pd
import numpy as np
df = pd.DataFrame([[1.4, np.nan], [7.1, -4.5],
[np.nan, np.nan], [0.75, -1.3]],
index=['a', 'b', 'c', 'd'],
columns=['one', 'two'])
df
###Output
_____no_output_____
###Markdown
使用sum的话,会返回一个series:
###Code
df.sum()
###Output
_____no_output_____
###Markdown
使用`axis='columns'` or `axis=1`,计算列之间的和:
###Code
df.sum(axis='columns')
###Output
_____no_output_____
###Markdown
计算的时候,NA(即缺失值)会被除外,除非整个切片全是NA。我们可以用skipna来跳过计算NA:
###Code
df.mean(axis='columns', skipna=False)
###Output
_____no_output_____
###Markdown
一些reduction方法:一些方法,比如idxmin和idxmax,能返回间接的统计值,比如index value:
###Code
df
df.idxmax()
###Output
_____no_output_____
###Markdown
还能计算累加值:
###Code
df.cumsum()
###Output
_____no_output_____
###Markdown
另一种类型既不是降维,也不是累加。describe能一下子产生多维汇总数据:
###Code
df.describe()
###Output
/Users/xu/anaconda/envs/py35/lib/python3.5/site-packages/numpy/lib/function_base.py:4116: RuntimeWarning: Invalid value encountered in percentile
interpolation=interpolation)
###Markdown
对于非数值性的数据,describe能产生另一种汇总统计:
###Code
obj = pd.Series(['a', 'a', 'b', 'c'] * 4)
obj
obj.describe()
###Output
_____no_output_____
###Markdown
下表是一些描述和汇总统计数据: 1 Correlation and Covariance (相关性和协方差)假设DataFrame时股价和股票数量。这些数据取自yahoo finace,用padas-datareader包能加载。如果没有的话,用conda或pip来下载这个包:
###Code
conda install pandas-datareader
import pandas_datareader.data as web
all_data = {ticker: web.get_data_yahoo(ticker)
for ticker in ['AAPL', 'IBM', 'MSFT', 'GOOG']}
price = pd.DataFrame({ticker: data['Adj Close']
for ticker, data in all_data.items()})
volumn = pd.DataFrame({ticker: data['Volumn']
for ticker, data in all_data.items()})
###Output
_____no_output_____
###Markdown
上面的代码无法直接从yahoo上爬取数据,因为yahoo被verizon收购后,好像是不能用了。于是这里我们直接从下好的数据包里加载。
###Code
ls ../examples/
price = pd.read_pickle('../examples/yahoo_price.pkl')
volume = pd.read_pickle('../examples/yahoo_volume.pkl')
price.head()
volume.head()
###Output
_____no_output_____
###Markdown
> pct_change(): 这个函数用来计算同colnums两个相邻的数字之间的变化率现在我们计算一下价格百分比的变化:
###Code
returns = price.pct_change()
returns.tail()
###Output
_____no_output_____
###Markdown
series的corr方法计算两个,重合的,非NA的,通过index排列好的series。cov计算方差:
###Code
returns['MSFT'].corr(returns['IBM'])
returns['MSFT'].cov(returns['IBM'])
###Output
_____no_output_____
###Markdown
因为MSFT是一个有效的python属性,我们可以通过更简洁的方式来选中columns:
###Code
returns.MSFT.corr(returns.IBM)
###Output
_____no_output_____
###Markdown
dataframe的corr和cov方法,能返回一个完整的相似性或方差矩阵:
###Code
returns.corr()
returns.cov()
###Output
_____no_output_____
###Markdown
用Dataframe的corrwith方法,我们可以计算dataframe中不同columns之间,或row之间的相似性。传递一个series:
###Code
returns.corrwith(returns.IBM)
###Output
_____no_output_____
###Markdown
传入一个dataframe能计算匹配的column names质监局的相似性。这里我计算vooumn中百分比变化的相似性:
###Code
returns.corrwith(volume)
###Output
_____no_output_____
###Markdown
传入axis='columns'能做到row-by-row计算。在correlation被计算之前,所有的数据会根据label先对齐。 2 Unique Values, Value Counts, and Membership(唯一值,值计数,会员)这里介绍另一种从一维series中提取信息的方法:
###Code
obj = pd.Series(['c', 'a', 'd', 'a', 'a', 'b', 'b', 'c', 'c'])
###Output
_____no_output_____
###Markdown
第一个函数时unique,能告诉我们series里unique values有哪些:
###Code
uniques = obj.unique()
uniques
###Output
_____no_output_____
###Markdown
返回的unique values不是有序的,但我们可以排序,uniques.sort()。相对的,value_counts能计算series中值出现的频率:
###Code
obj.value_counts()
###Output
_____no_output_____
###Markdown
返回的结果是按降序处理的。vaule_counts也是pandas中的方法,能用在任何array或sequence上:
###Code
pd.value_counts(obj.values, sort=False)
###Output
_____no_output_____
###Markdown
isin 能实现一个向量化的集合成员关系检查,能用于过滤数据集,检查一个子集,是否在series的values中,或在dataframe的column中:
###Code
obj
mask = obj.isin(['b', 'c'])
mask
obj[mask]
###Output
_____no_output_____
###Markdown
与isin相对的另一个方法是Index.get_indexer,能返回一个index array,告诉我们有重复值的values(to_match),在非重复的values(unique_vals)中对应的索引值:
###Code
to_match = pd.Series(['c', 'a', 'b', 'b', 'c', 'a'])
unique_vals = pd.Series(['c', 'b', 'a'])
pd.Index(unique_vals).get_indexer(to_match)
###Output
_____no_output_____
###Markdown
Unique, value counts, and set membership methods:在某些情况下,你可能想要计算一下dataframe中多个column的柱状图:
###Code
data = pd.DataFrame({'Qu1': [1, 3, 4, 3, 4],
'Qu2': [2, 3, 1, 2, 3],
'Qu3': [1, 5, 2, 4, 4]})
data
###Output
_____no_output_____
###Markdown
把padas.value_counts传递给dataframe的apply函数:
###Code
result = data.apply(pd.value_counts)
result
###Output
_____no_output_____ |
Clase 6 a 7 - Suma Vectores/Suma_Vectores.ipynb | ###Markdown
2. Adición entre vectores. La información de vectores de la **misma dimensión** se puede *juntar* sumando elemento a elemento sus entradas. A esta operación entre vectores se le conoce como suma y es denotada por el operador $+$. Así pues, sean $a,b,c$ $n$-vectores de $\mathbb{R}^{n}$ donde $c=a+b$, la operación se ilustra como:$$c = a+b = \begin{bmatrix}a_{0}\\ a_{1}\\\vdots \\ a_{n-1}\end{bmatrix} + \begin{bmatrix}b_{0}\\ b_{1}\\\vdots \\ b_{n-1}\end{bmatrix} = \begin{bmatrix}a_{0} + b_{0}\\ a_{1}+b_{1}\\\vdots \\ a_{n-1}+b_{n-1}\end{bmatrix} $$ Por ejemplo:$$\begin{bmatrix} 0\\ 1\\ 2\end{bmatrix} + \begin{bmatrix}2\\ 3\\ -1\end{bmatrix} = \begin{bmatrix}0+2\\ 1+3 \\ 2-1\end{bmatrix} = \begin{bmatrix}2\\ 4 \\ 1\end{bmatrix} $$Y también:$$ \left( 1 , 2 , 3 \right) + \left( -1 ,-2 , -3 \right) = \left( 1-1 , 2-2 , 3-3 \right) = \left( 0 , 0 , 0 \right) = \mathbf{0}$$ 2.1 Propiedades de la adición La suma entre vectores es llamada una *operación algebraíca* y esta cumple ciertas propiedades. Consideremos $\displaystyle\vec{a},\displaystyle\vec{b},\displaystyle\vec{c}$ vectores de $\mathbb{R}^n$ entonces:* La suma de vectores es *conmutativa*: $\vec{a}+\vec{b} = \vec{b}+\vec{a}$* La suma de vectores es *asociativa*: $(\vec{a}+\vec{b})+\vec{c} = \vec{a}+(\vec{b}+\vec{c})$. Por esto último podemos escribir libremente $\vec{a}+\vec{b}+\vec{c}$ ya que el resultado no cambiará según qué pareja de vectores sumemos primero. * La suma entre vectores, cuando uno es el vector cero, no surte algún efecto sobre el otro vector: $\vec{a}+\vec{0}=\vec{0}+\vec{a}=\vec{a}$* Suma un vector con su inverso o lo que es lo mismo restar dos vectores iguales nos deja con el vector cero: $\vec{a}-\vec{a}=\vec{0}$ **Advertencia:** No todas las operaciones son cerradas en su espacio vectorial. 2.2 Suma de vectores en Python Vamos a rescatar el ejemplo de la clase pasada: el modelo aditivo RGB. Sabemos que podemos representar los vectores como listas, por ejemplo, el negro y el rojo son:
###Code
rojo = [255,0,0]
negro = [0,0,0]
###Output
_____no_output_____
###Markdown
El gran problema es que en Python el operador $+$ entre listas respresenta concatenación y no suma entrada a entrada:
###Code
print('rojo + negro resulta en',rojo+negro)
###Output
rojo + negro resulta en [255, 0, 0, 0, 0, 0]
###Markdown
Una solución a esto es crear una función que tome dos listas y las sume entrada por entrada
###Code
def suma_vectores(a,b):
return [i+j for i,j in zip(a,b)]
print('suma_vectores(rojo,negro) nos devuelve',suma_vectores(rojo,negro))
print('suma_vectores(verde,negro) nos devuelve',suma_vectores([0,255,0],negro))
###Output
suma_vectores(verde,negro) nos devuelve [0, 255, 0]
###Markdown
Al parecer con esta función gran parte de nuestros problemas se resuelven sin embargo a largo plazo nos será más últil comenzar a usar **Numpy**. **Numpy** es una biblioteca de Python que nos soporte para poder operar entre vectores y matrices. De igual manera contiene funciones matemáticas de alto nivel y que también podrán operar con los vectores y matrices. Lo primero que tenemos que hacer es importar la biblioteca numpy
###Code
import numpy as np
###Output
_____no_output_____
###Markdown
Después vamos a declarar nuestras listas ya creadas como *numpy.arrays*
###Code
rojo = np.array(rojo)
negro = np.array(negro)
###Output
_____no_output_____
###Markdown
Si verificamos el tipo de la función entonces notaremos que es una instancia de *numpy.ndarray*
###Code
print(type(rojo))
###Output
<class 'numpy.ndarray'>
###Markdown
Finalmente, notemos que *rojo* y *negro* ya no son listas de Python sino instancias de numpy. Entre ndarrays el operador $+$ funcionará exactamente como se espera entre vectores, entrada a entrada:
###Code
print('La suma de los numpy array rojo + negro es', rojo+negro)
###Output
La suma de los numpy array rojo + negro es [255 0 0]
###Markdown
Por completez vamos a realizar un ejercicio más. Sean $\mathbf{a}=(1,2,3,4,5)$, $\mathbf{b} = (-1,-2,-3,-4,5)$ y $\mathbf{c} = \mathbf{a}+\mathbf{b} = (0,0,0,0,10)$. Vamos a replicar este cálculo en Python con ayuda de numpy.
###Code
a = np.array([1,2,3,4,5]) #declaramos el arreglo/vector a
b = np.array([-1,-2,-3,-4,5]) #declaramos el arreglo/vector b
c = a+b
print('La el vector c = a+b =',c)
###Output
La el vector c = a+b = [ 0 0 0 0 10]
|
care/2.5_generate-tumormap-report.ipynb | ###Markdown
Create the standard "Tumormap Report" with link to a tumormap URLOutput ends up in this scriptModified from :report_on_local_neighborhoods.py by Yulia Newtonmd5 of original script:ac61f51b7dee830df54d8d59608c1c45 report_on_local_neighborhoods.py InputsDepends on steps:* 2.0 - json tumormap_results OutputsJson results include keys: - calculated_nof1_url - string - calculated_nof1_and_mcs_url - string - most_similar_samples - array of sample IDs - mcs_threshold_status - dict - sample id : string- blank or "failed threshold" or "pivot sample" - mcs_above_threshold_url - string - attribute_info - array of strings - the raw info from clinical files - centroid_y - float - centroid_x - float - pivot_sample - string - pivot sample ID - nof1_original_url - string - mcs_only_url - string - median_local_neighborhood_similarity - float - mcs_clinical_data - dict - sample id : { clin key : value, } - only from clinical.tsv
###Code
import optparse, sys, os
import operator
import numpy
import json
import logging
import csv
# Setup: load conf, retrieve sample ID, logging
with open("conf.json","r") as conf:
c=json.load(conf)
sample_id = c["sample_id"]
print("Running on sample: {}".format(sample_id))
logging.basicConfig(**c["info"]["logging_config"])
logging.info("\n2.5: Generate Tumormap Report")
def and_log(s):
logging.info(s)
return s
# Input : requires json from step 2.0
with open(c["json"]["2.0"],"r") as jf:
json_2pt0 = json.load(jf)
j = {}
# Set up the "printreport" function.
# This will print the passed text, as well as append it to the tumormap report.
def create_print_append(outfile):
def print_append(text):
with open(outfile, "a+") as out:
print >> out, text
print text
return print_append
print_report = create_print_append(c["file"]["tumormap_report"])
tumormap_report_text = []
#process input arguments:
in_sample = sample_id
in_euclidean_positions = c["tumormap"]["xy_coords"]
# Get all files in the cohort clinical data dir
attribute_files = []
for f in sorted(os.listdir(c["dir"]["cohort_clinical"])):
path_f = os.path.join(c["dir"]["cohort_clinical"], f)
if os.path.isfile(path_f):
attribute_files.append(path_f)
#read neighborhoods
n = json_2pt0["tumormap_results"]
j["pivot_sample"] = in_sample
j["most_similar_samples"] = n.keys()
j["median_local_neighborhood_similarity"] = numpy.median(n.values())
print_report( "Pivot sample: {}".format(j["pivot_sample"]) )
print_report( "Pivot neighbors: {}".format(", ".join(j["most_similar_samples"])))
print_report( "Median local neighborhood similarity: {}".format(str(j["median_local_neighborhood_similarity"])))
# position on tumormap if available
self_coords = []
neighbor_coords = []
mcs_above_threshold_coords = { "ids":[], "xcoords":[], "ycoords":[] }
if(os.path.exists(in_euclidean_positions)):
with open(in_euclidean_positions, 'r') as input:
x_pos = []
y_pos = []
for line in input:
line_elems = line.strip().split("\t")
# Don't crash horribly if we get a line that's missing fields--just skip it
if len(line_elems) < 3:
continue
# Get the MCS above threshold coords (will never include self-sample)
if line_elems[0] in json_2pt0["tumormap_results_above_threshold"].keys():
mcs_above_threshold_coords["ids"].append(line_elems[0])
mcs_above_threshold_coords["xcoords"].append(line_elems[1])
mcs_above_threshold_coords["ycoords"].append(line_elems[2])
if line_elems[0] in n.keys():
# If we encounter the self-sample, don't add it to x_pos / y_post as it
# should not contribute to the centroid; but do store it for display
if line_elems[0] == c["info"]["id_for_tumormap"]:
self_coords = [line_elems[1],line_elems[2]]
else:
x_pos.append(float(line_elems[1]))
y_pos.append(float(line_elems[2]))
# Also store the neighbor info for display
neighbor_coords.append(line_elems)
input.close()
if not(len(x_pos) == len(y_pos)):
raise KeyboardInterrupt("ERROR: number of x positions does not match number of y positions in the neighbors")
if(len(x_pos) == 0):
print_report( "No pivot position or TumorMap URL available: neighbors not found in coordinates file.")
else:
j["centroid_x"] = numpy.median(x_pos) #median
j["centroid_y"] = numpy.median(y_pos) #median
print_report( "Pivot position in the map: ("+str(j["centroid_x"])+", "+str(j["centroid_y"])+")")
tumormap_url=c["tumormap"]["info"]["url"]
if not tumormap_url:
print_report( "No TumorMap URL available.")
else:
j["calculated_nof1_url"]="{}&node={}&x={}&y={}".format(
tumormap_url, in_sample, str(j["centroid_x"]), str(j["centroid_y"]))
print_report( "URL - Calculated:" )
print_report(j["calculated_nof1_url"])
# Also print URL with MCS
# Format is node=Sample1,Sample2,Sample3&x=123,456,789&y=111,222,333
neighbor_url_ids = [in_sample]
neighbor_url_x = [str(j["centroid_x"])]
neighbor_url_y = [str(j["centroid_y"])]
for neighbor in neighbor_coords:
neighbor_url_ids.append(neighbor[0])
neighbor_url_x.append(neighbor[1])
neighbor_url_y.append(neighbor[2])
j["calculated_nof1_and_mcs_url"] = "{}&node={}&x={}&y={}".format(
tumormap_url, ",".join(neighbor_url_ids), ",".join(neighbor_url_x), ",".join(neighbor_url_y))
print_report( "URL - Sample and Most Similar Samples:" )
print_report( j["calculated_nof1_and_mcs_url"] )
# Also print the url for JUST the MCS; guaranteed to be at least one (see above, No pivot position...)
j["mcs_only_url"] = "{}&node={}&x={}&y={}".format(
tumormap_url,
",".join(neighbor_url_ids[1:]),
",".join(neighbor_url_x[1:]),
",".join(neighbor_url_y[1:])
)
print_report( "URL - Most Correlated Samples only:" )
print_report(j["mcs_only_url"])
# Report for just the MCS above threshold
j["mcs_above_threshold_url"] = "{}&node={}&x={}&y={}".format(
tumormap_url,
",".join(mcs_above_threshold_coords["ids"]),
",".join(mcs_above_threshold_coords["xcoords"]),
",".join(mcs_above_threshold_coords["ycoords"])
)
print_report("URL - Most Correlated Samples Above Threshold:")
print_report(j["mcs_above_threshold_url"])
# If the sample was already on the map, print a URL for that too
if(self_coords):
j["nof1_original_url"] = "{}&node={}&x={}&y={}".format(
tumormap_url, in_sample, self_coords[0], self_coords[1])
print_report( "URL - Original Placement:" )
print_report(j["nof1_original_url"])
else:
print_report( "No pivot position or TumorMap URL available: coordinates file not present." )
# Similarity with MCS & sample disease counts, rounded to 2 decimal places
# Also note the pivot sample and MCS that failed the correlation threshold
j["mcs_threshold_status"] = {}
print_report( "\nSimilarity with individual neighbors"
" (in order from highest to lowest correlation):" )
for k in sorted(n, key=n.get, reverse=True):
if k in json_2pt0["tumormap_results_above_threshold"].keys():
failed_threshold = ""
elif k == c["info"]["id_for_tumormap"]:
failed_threshold = "\t(pivot sample)"
else:
failed_threshold = "\t(failed correlation threshold)"
j["mcs_threshold_status"][k] = failed_threshold
print_report( "{}\t{}{}".format(k, '{:.2f}'.format(n[k]), failed_threshold))
print_report("\n")
print_report(json_2pt0["sample_disease_counts"])
# Print attribute info
j["attribute_info"]= []
for a in attribute_files:
print_report( "\n" )
with open(a, 'r') as input:
line_num = 0
for line in input:
line = line.replace("\n", "")
if line_num == 0:
print_report( line )
j["attribute_info"].append(line)
else:
line_elems = line.split("\t")
if line_elems[0] in n.keys():
print_report( line )
j["attribute_info"].append(line)
line_num += 1
###Output
_____no_output_____
###Markdown
Get the essential clinical info into the json for easy parsing downstream
###Code
j["mcs_clinical_data"] = {}
allsid = []
with open(c["cohort"]["essential_clinical"], "r") as essential_clinical:
clin_items = csv.DictReader(essential_clinical, dialect="excel-tab")
for sample in clin_items:
if sample["th_sampleid"] in n.keys():
j["mcs_clinical_data"][sample["th_sampleid"]] = sample
j["mcs_clinical_data"]
with open(c["json"]["2.5"], "w") as jf:
json.dump(j, jf, indent=2)
print("Done!")
###Output
_____no_output_____ |
Python for Finance - Code Files/64 Simple Returns - Part II/Online Financial Data (APIs)/Python 2 APIs/Simple Returns - Part II - Exercise_Morn.ipynb | ###Markdown
Simple Returns - Part II $$\frac{P_1 - P_0}{P_0} = \frac{P_1}{P_0} - 1$$
###Code
import numpy as np
from pandas_datareader import data as wb
MSFT = wb.DataReader('MSFT', data_source='morningstar', start='2002-1-1')
MSFT['simple_return'] = (MSFT['Close'] / MSFT['Close'].shift(1)) - 1
print MSFT['simple_return']
###Output
_____no_output_____ |
tutorials/W2D1_BayesianStatistics/student/W2D1_Tutorial1.ipynb | ###Markdown
Neuromatch Academy: Week 2, Day 1, Tutorial 1 Bayes rule with Gaussians**Tutorial Lecturer:** *Konrad Kording***Tutorial Content Creator:** *Vincent Valton* Introduction
###Code
#@title Video: Intro
from IPython.display import YouTubeVideo
video = YouTubeVideo(id='wbZ60vdnoqw', width=854, height=480, fs=1)
print("Video available at https://youtube.com/watch?v=" + video.id)
video
###Output
Video available at https://youtube.com/watch?v=wbZ60vdnoqw
###Markdown
---In this notebook we'll look at using *Bayes rule* with *Gaussian distributions*. That is, given a prior probability distribution, and a likelihood distribution, we will compute the posterior using Bayes rule and play with different likelihoods and Priors to get a good intuition of how it affects the posterior distribution. This is an example of a normative model. We assume that behavior has to deal with uncertainty and ask which behavior would be optimal. We can then ask if people show behavior that is similar to this optimal behavior. in the coming exercises, we will: 1. Implement a Gaussian prior1. Given Bayes rule, a Gaussian likelihood and prior, calculate the posterior distribution.1. Change the likelihood mean and variance and observe how posterior changes.1. Advanced (*optional*): Observe what happens if the prior is a mixture of two gaussians?--- Setup Please execute the cell below to initialize the notebook environment.
###Code
# imports
import time # import time
import numpy as np # import numpy
import scipy as sp # import scipy
import math # import basic math functions
import random # import basic random number generator functions
import os
import matplotlib.pyplot as plt # import matplotlib
from IPython import display
#@title Figure Settings
fig_w, fig_h = (8, 6)
plt.rcParams.update({'figure.figsize': (fig_w, fig_h)})
plt.style.use('ggplot')
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
#@title Helper functions
def my_plot_single(x, px):
"""
Plots normalized Gaussian distribution
Args:
x (numpy array of floats): points at which the likelihood has been evaluated
px (numpy array of floats): normalized probabilities for prior evaluated at each `x`
Returns:
Nothing.
"""
if px is None:
px = np.zeros_like(x)
plt.plot(x, px, '-', color='xkcd:green', LineWidth=2, label='Prior')
plt.legend()
plt.ylabel('Probability')
plt.xlabel('Orientation (Degrees)')
def my_plot(x, auditory=None, visual=None, posterior_pointwise=None):
"""
Plots normalized Gaussian distributions and posterior
Args:
x (numpy array of floats): points at which the likelihood has been evaluated
auditory (numpy array of floats): normalized probabilities for auditory likelihood evaluated at each `x`
visual (numpy array of floats): normalized probabilities for visual likelihood evaluated at each `x`
posterior (numpy array of floats): normalized probabilities for the posterior evaluated at each `x`
Returns:
Nothing.
"""
if auditory is None:
auditory = np.zeros_like(x)
if visual is None:
visual = np.zeros_like(x)
if posterior_pointwise is None:
posterior_pointwise = np.zeros_like(x)
plt.plot(x, auditory, '-r', LineWidth=2, label='Auditory')
plt.plot(x, visual, '-b', LineWidth=2, label='Visual')
plt.plot(x, posterior_pointwise, '-g', LineWidth=2, label='Posterior')
plt.legend()
plt.ylabel('Probability')
plt.xlabel('Orientation (Degrees)')
def plot_visual(mu_visuals, mu_posteriors, max_posteriors):
"""
Plots the comparison of computing the mean of the posterior analytically and
the max of the posterior empirically via multiplication.
Args:
mu_visuals (numpy array of floats): means of the visual likelihood
mu_posteriors (numpy array of floats): means of the posterior, calculated analytically
max_posteriors (numpy array of floats): max of the posteriors, calculated via maxing the max_posteriors.
posterior (numpy array of floats): normalized probabilities for the posterior evaluated at each `x`
Returns:
Nothing.
"""
fig = plt.figure(figsize=(fig_w, 2*fig_h))
plt.subplot(211)
plt.plot(mu_visuals, max_posteriors,'-g', label='argmax')
plt.xlabel('Visual stimulus position')
plt.ylabel('Multiplied max of position')
plt.title('Sample output')
plt.subplot(212)
plt.plot(mu_visuals, mu_posteriors, '--', color='xkcd:gray', label='argmax')
plt.xlabel('Visual stimulus position')
plt.ylabel('Analytical posterior mean')
plt.tight_layout()
plt.title('Hurray for math!')
plt.show()
###Output
_____no_output_____
###Markdown
a. Implement a GaussianIn this exercise, you will implement a Gaussian by filling in the missing portion of `my_gaussian` below. Plot it and play with its parameters, because you will need an intuition for how $\mu$ and $\sigma$ affect the shape of the Gaussian. Reminder: the equation for a Gaussian is:\begin{eqnarray}\mathcal{N}(\mu,\sigma^2) = \frac{1}{\sqrt{2\pi\sigma^2}}\exp\left(\frac{-(x-\mu)^2}{2\sigma^2}\right)\end{eqnarray}Later, we will later use this Gaussian as the prior as a function of the angle where the stimulus is coming from. Test out your implementation with a $\mu = -1$ and $\sigma = 1$. Then try to change $\mu$ and $\sigma$ and see what the results look like. **Helper function(s)**
###Code
help(my_plot_single)
###Output
Help on function my_plot_single in module __main__:
my_plot_single(x, px)
Plots normalized Gaussian distribution
Args:
x (numpy array of floats): points at which the likelihood has been evaluated
px (numpy array of floats): normalized probabilities for prior evaluated at each `x`
Returns:
Nothing.
###Markdown
Exercise 1
###Code
def my_gaussian(x_points, mu, sigma):
"""
Returns normalized Gaussian estimated at points `x_points`, with parameters: mean `mu` and std `sigma`
Args:
x_points (numpy array of floats): points at which the gaussian is evaluated
mu (scalar): mean of the Gaussian
sigma (scalar): std of the gaussian
Returns:
(numpy array of floats) : normalized Gaussian evaluated at `x`
"""
###################################################################
## Calculate the gaussian as a function of mu and sigma, for each x (incl. hints )
## Function Hints: exp -> np.exp()
## power -> z**2
##
## remove the raise when the function is complete
raise NotImplementedError("You need to implement the Gaussian function!")
###################################################################
x = np.arange(-8, 9, 0.1)
# Uncomment once the task (steps above) is complete
# px = my_gaussian(x, -1, 1)
# my_plot_single(x, px)
###Output
_____no_output_____
###Markdown
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W2D1_BayesianStatistics/solutions/W2D1_Tutorial1_Solution_b97eeff5.py)*Example output:* b. Given Bayes rule, a Gaussian likelihood and prior, calculate the posterior distribution
###Code
#@title Video: Bayes' theorem
video = YouTubeVideo(id='XLATXJci3qQ', width=854, height=480, fs=1)
print("Video available at https://youtube.com/watch?v=" + video.id)
video
###Output
Video available at https://youtube.com/watch?v=XLATXJci3qQ
###Markdown
Bayes' rule tells us how to combine two sources of information, the prior and the likelihood, to obtain a posterior distribution taking into account both pieces of information. Bayes' rule states:\begin{eqnarray}\text{Posterior} = \frac{ \text{Likelihood} \times \text{Prior}}{ \text{Normalization constant}}\end{eqnarray}Mathematically, if both the likelihood and the Prior are Gaussian, this translates into:\begin{eqnarray} \text{Likelihood} = \mathcal{N}(\mu_{likelihood},\sigma_{likelihood}^2) = \frac{1}{\sqrt{2\pi\sigma^2_{likelihood}}}\exp\left(\frac{-(x-\mu_{likelihood})^2}{2\sigma^2_{likelihood}}\right)\end{eqnarray}\begin{eqnarray} \text{Prior} = \mathcal{N}(\mu_{prior},\sigma_{prior}^2) = \frac{1}{\sqrt{2\pi\sigma^2_{prior}}}\exp\left(\frac{-(x-\mu_{prior})^2}{2\sigma^2_{prior}}\right)\end{eqnarray}\begin{eqnarray} \text{Posterior} \propto \mathcal{N}(\mu_{likelihood},\sigma_{likelihood}^2) \times \mathcal{N}(\mu_{prior},\sigma_{prior}^2) = \mathcal{N}\left( \frac{\sigma^2_{likelihood}\mu_{prior}+\sigma^2_{prior}\mu_{likelihood}}{\sigma^2_{likelihood}+\sigma^2_{prior}}, \frac{\sigma^2_{likelihood}\sigma^2_{prior}}{\sigma^2_{likelihood}+\sigma^2_{prior}} \right) \tag{1}\end{eqnarray}where $\mathcal{N}(\mu,\sigma^2)$ denotes a Gaussian distribution with parameters $\mu_{likelihood}$ and $\sigma^2_{likelihood}$.Note that although there's a closed-form solution for the particular case of two Gaussians (as shown above), we're going to combine them using pointwise multiplication, which works for any family of distributions. Exercise 2We have a Gaussian auditory Likelihood (in red), and a Gaussian visual prior (in blue), and we want to combine the two to generate our posterior using Bayes rule.We provide you with a ready-to-use plotting function, and a code skeleton.**Suggestions*** Use `my_gaussian` (the answer to exercise 1) to generate an auditory likelihood with parameters $\mu$ = 3 and $\sigma$ = 1.5* Similarly, generate a visual prior with parameters $\mu$ = -1 and $\sigma$ = 1.5* Calculate the posterior using pointwise multiplication of the likelihood and prior (don't forget to normalize so the posterior adds up to 1)* Plot the likelihood, prior and posterior using the predefined function `my_plot`* Now change the standard deviation ($\sigma$) of the visual likelihood to 0.5. See how a more precise (tighter) visual prior relative to auditory results in a posterior that is weighted more heavily towards the most precise source of information. **Helper function(s)**
###Code
help(my_plot)
# since we will use this function (my_gaussian) throughout the whole tutorial
# we provide you the solution to the previous exercise, to avoid any headaches
def my_gaussian(x_points, mu, sigma):
"""
Returns normalized Gaussian estimated at points `x_points`, with parameters: mean `mu` and std `sigma`
Args:
x_points (numpy array of floats): points at which the gaussian is evaluated
mu (scalar): mean of the Gaussian
sigma (scalar): std of the gaussian
Returns:
(numpy array of floats) : normalized Gaussian evaluated at `x`
"""
px = np.exp(- 1/2/sigma**2 * (mu - x) ** 2)
px = px / px.sum() # this is the normalization part with a very strong assumption, that
# x_points cover the big portion of probability mass around the mean.
# Please think/discuss when this would be a dangerous assumption.
return px
x = np.arange(-8,9,0.1)
mu_auditory = 3
sigma_auditory= 1.5
mu_visual = -1
sigma_visual= 1.5
################################################################################
## Insert your code here to:
## create a gaussian called 'auditory' with mean 3, and std 1.5
## create a gaussian called 'visual' with mean -1, and std 1.5
## calculate the posterior by multiplying (pointwise) the 'auditory' and 'visual' gaussians
## (Hint: Do not forget to normalise the gaussians before plotting them)
## plot the distributions using the function `my_plot`
##
## you can use the following variables (conveniently used in the plotting function)
# auditory = ...
# visual = ...
# posterior_pointwise = ...
################################################################################
# Uncomment once the task (steps above) is complete
# my_plot(x, auditory, visual, posterior_pointwise)
###Output
_____no_output_____
###Markdown
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W2D1_BayesianStatistics/solutions/W2D1_Tutorial1_Solution_08217508.py)*Example output:* d. Change the likelihood mean and variance and observe how posterior changes
###Code
#@title Video: Multiplying Gaussians
video = YouTubeVideo(id='LXWPe5_fZzQ', width=854, height=480, fs=1)
print("Video available at https://youtube.com/watch?v=" + video.id)
video
###Output
Video available at https://youtube.com/watch?v=LXWPe5_fZzQ
###Markdown
Now that we can compute *Bayes rule* with two *Gaussians*, let's keep the auditory likelihood fixed straight ahead (mean = 0), and play around with the visual stimulus position (mean) to see how that affects the posterior.Observe how the posterior changes as a function of both the position of the likelihood with respect to the prior, and the relative weight of the likelihood with respect to the prior.**Hit the Play button or Ctrl+Enter in the cell below** and play with the sliders to get an intuition for how the means and standard deviations of prior and likelihood influence the posterior.
###Code
#@title Interactive widget (Make sure to execute this cell)
###### MAKE SURE TO RUN THIS CELL VIA THE PLAY BUTTON TO ENABLE SLIDERS ########
x = np.arange(-10,11,0.1)
import ipywidgets as widgets
def refresh(mu_auditory=3, sigma_auditory=1.5, mu_visual=-1, sigma_visual=1.5):
auditory = my_gaussian(x, mu_auditory, sigma_auditory)
visual = my_gaussian(x, mu_visual, sigma_visual)
posterior_pointwise = visual * auditory
posterior_pointwise /= posterior_pointwise.sum()
w_auditory = (sigma_visual** 2) / (sigma_auditory**2 + sigma_visual**2)
theoretical_prediction = mu_auditory * w_auditory + mu_visual * (1 - w_auditory)
plt.plot([theoretical_prediction, theoretical_prediction],
[0, posterior_pointwise.max() * 1.2], '-.', color='xkcd:medium gray')
my_plot(x, auditory, visual, posterior_pointwise)
plt.title('Gray line shows analytical mean of posterior')
_ = widgets.interact(refresh,
mu_auditory = (-10, 10, .5),
sigma_auditory= (.5, 10, .5),
mu_visual = (-10, 10, .5),
sigma_visual= (.5, 10, .5))
###Output
_____no_output_____
###Markdown
e. Compute the posterior mean as a function of auditory meanWe can calculate the mean of the posterior as a function of the paramters of the visual and auditory distributions as follows:$$ \mu_{posterior} = \frac{\mu_{auditory} \cdot \frac{1}{\sigma_{auditory}^2} + \mu_{visual} \cdot \frac{1}{\sigma_{visual}^2}}{1/\sigma_{auditory}^2 + 1/\sigma_{visual}^2} = \frac{\mu_{auditory}~\sigma^2_{visual} + \mu_{visual}~ \sigma^2_{auditory}}{\sigma^2_{auditory} + \sigma^2_{visual}} $$This is a special case for the mean of a Gaussian ([equation 1](https://colab.research.google.com/drive/1p9Heh8WNiNkiSriNd63uxaGk29w71l2mscrollTo=HB2U9wCNyaSo&line=20&uniqifier=1)) that we saw in the previous section. Now it's your turn to calculate the mean as a function of different visual inputs:* Keep auditory parameters constant* Sweep through the visual mean `mu_visual`* Compute the analytical posterior mean from auditory and visual using the equation above.* Compute the empirical mode (*Mode* is defined as the most frequently occurring value in a data set, or value with highest probability in a PDF or PMF) of the posterior via multiplication using the `compute_mode_posterior_multiply` function* Plot the analytical posterior mean and the empirical posterior mode as a function of the visual mean. **Helper function(s)**
###Code
help(plot_visual)
mu_auditory = 3
sigma_auditory = 1.5
mu_visuals = np.linspace(-10, 10)
sigma_visual= 1.5
def compute_mode_posterior_multiply(x, mu_auditory, sigma_auditory,
mu_visual, sigma_visual):
"""
Computes the mode of the posterior via multiplication.
DO NOT EDIT THIS FUNCTION !!!
Args:
x (numpy array of floats):
mu_auditory (numpy array of floats): mean of the auditory likelihood
sigma_auditory (numpy array of floats): standard deviation of the auditory likelihood
mu_visual (numpy array of floats): mean of the visual likelihood
sigma_visual (numpy array of floats): standard deviation of the visual likelihood
Returns:
the mode of x
"""
auditory = my_gaussian(x, mu_auditory, sigma_auditory)
visual = my_gaussian(x, mu_visual, sigma_visual)
posterior_pointwise = auditory * visual
posterior_pointwise /= posterior_pointwise.sum()
return x[posterior_pointwise.argmax()]
################################################################################
## Insert your code here to:
## sweep through the mu_visuals with a for loop
## compute mu_posterior with the analytical formula in each case
## compute the max of the posterior by multiplying gaussians in each case
## using the compute_mode_posterior_multiply
## plot mu_posterior_analytical as a function of mu_posterior_multiply
################################################################################
###Output
_____no_output_____
###Markdown
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W2D1_BayesianStatistics/solutions/W2D1_Tutorial1_Solution_fd84cbd0.py)*Example output:*
###Code
#@title Video: Outro
video = YouTubeVideo(id='f-1E9W35hDw', width=854, height=480, fs=1)
print("Video available at https://youtube.com/watch?v=" + video.id)
video
###Output
Video available at https://youtube.com/watch?v=f-1E9W35hDw
###Markdown
--- f. ADDITIONAL exercise: Multimodal priors**Only do this if the first half-hour has not yet passed.**Bayes rule works similarly for cue combination (auditory + visual) as it would with a prior and likelihood.What do you think is going to happen to the posterior if we were to use a multimodal prior instead of a single Gaussian (i.e. a prior with multiple peaks)?**Suggestions*** Create a bi-modal prior by summing two Gaussians centered on -3 and 3 respectively, with $\sigma_{prior}$ = 1* Similarly to the previous exercise, allow the mean of the likelihood to vary and plot the prior, likelihood and posterior using the function `my_plot`. - Observe what happens to the posterior as the likelihood gets closer to the different peaks of the prior. - Notice what happens to the posterior when the likelihood is exactly in between the two modes of the prior (i.e. $\mu_{Likelihood}$ = 0)* Plot the mode of the posterior as a function of the visual stimulus mean. - What to you observe? How does it compare to the previous exercise?
###Code
x = np.arange(-10, 10, 0.1)
mu_visuals = np.arange(-6, 6, 0.1)
std_visual = 1
mu1_auditory = -3
mu2_auditory = 3
std_auditory = 1
################################################################################
## Insert your code here
## Reuse your code from Exercise 2, but replace the prior with a bimodal prior
## by summing two Gaussians with variance = 1, and means [-3, 3] respectively
################################################################################
###Output
_____no_output_____
###Markdown
Neuromatch Academy: Week 2, Day 1, Tutorial 1 Bayes rule with Gaussians__Content creators:__ Vincent Valton, Konrad Kording, with help from Matt Krause__Content reviewers:__ Matt Krause, Jesse Livezey, Karolina Stosio, Saeed Salehi, Michael Waskom Tutorial ObjectivesThis is the first in a series of three main tutorials (+ one bonus tutorial) on Bayesian statistics. In these tutorials, we will develop a Bayesian model for localizing sounds based on audio and visual cues. This model will combine **prior** information about where sounds generally originate with sensory information about the **likelihood** that a specific sound came from a particular location. As we will see in subsequent lessons, the resulting **posterior distribution** not only allows us to make optimal decision about the sound's origin, but also lets us quantify how uncertain that decision is. Bayesian techniques are therefore useful **normative models**: the behavior of human or animal subjects can be compared against these models to determine how efficiently they make use of information. This notebook will introduce two fundamental building blocks for Bayesian statistics: the Gaussian distribution and the Bayes Theorem. You will: 1. Implement a Gaussian distribution2. Use Bayes' Theorem to find the posterior from a Gaussian-distributed prior and likelihood. 3. Change the likelihood mean and variance and observe how posterior changes.4. Advanced (*optional*): Observe what happens if the prior is a mixture of two gaussians?
###Code
#@title Video 1: Introduction to Bayesian Statistics
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = "https://player.bilibili.com/player.html?bvid={0}&page={1}".format(id, page)
super(BiliVideo, self).__init__(src, width, height, **kwargs)
video = BiliVideo(id='BV1pZ4y1u7PD', width=854, height=480, fs=1)
print("Video available at https://www.bilibili.com/video/{0}".format(video.id))
video
###Output
Video available at https://www.bilibili.com/video/BV1pZ4y1u7PD
###Markdown
Setup Please execute the cells below to initialize the notebook environment.
###Code
import numpy as np
import matplotlib.pyplot as plt
#@title Figure Settings
import ipywidgets as widgets
plt.style.use("/share/dataset/COMMON/nma.mplstyle.txt")
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
#@title Helper functions
def my_plot_single(x, px):
"""
Plots normalized Gaussian distribution
Args:
x (numpy array of floats): points at which the likelihood has been evaluated
px (numpy array of floats): normalized probabilities for prior evaluated at each `x`
Returns:
Nothing.
"""
if px is None:
px = np.zeros_like(x)
fig, ax = plt.subplots()
ax.plot(x, px, '-', color='xkcd:green', LineWidth=2, label='Prior')
ax.legend()
ax.set_ylabel('Probability')
ax.set_xlabel('Orientation (Degrees)')
def posterior_plot(x, likelihood=None, prior=None, posterior_pointwise=None, ax=None):
"""
Plots normalized Gaussian distributions and posterior
Args:
x (numpy array of floats): points at which the likelihood has been evaluated
auditory (numpy array of floats): normalized probabilities for auditory likelihood evaluated at each `x`
visual (numpy array of floats): normalized probabilities for visual likelihood evaluated at each `x`
posterior (numpy array of floats): normalized probabilities for the posterior evaluated at each `x`
ax: Axis in which to plot. If None, create new axis.
Returns:
Nothing.
"""
if likelihood is None:
likelihood = np.zeros_like(x)
if prior is None:
prior = np.zeros_like(x)
if posterior_pointwise is None:
posterior_pointwise = np.zeros_like(x)
if ax is None:
fig, ax = plt.subplots()
ax.plot(x, likelihood, '-r', LineWidth=2, label='Auditory')
ax.plot(x, prior, '-b', LineWidth=2, label='Visual')
ax.plot(x, posterior_pointwise, '-g', LineWidth=2, label='Posterior')
ax.legend()
ax.set_ylabel('Probability')
ax.set_xlabel('Orientation (Degrees)')
return ax
def plot_visual(mu_visuals, mu_posteriors, max_posteriors):
"""
Plots the comparison of computing the mean of the posterior analytically and
the max of the posterior empirically via multiplication.
Args:
mu_visuals (numpy array of floats): means of the visual likelihood
mu_posteriors (numpy array of floats): means of the posterior, calculated analytically
max_posteriors (numpy array of floats): max of the posteriors, calculated via maxing the max_posteriors.
posterior (numpy array of floats): normalized probabilities for the posterior evaluated at each `x`
Returns:
Nothing.
"""
fig_w, fig_h = plt.rcParams.get('figure.figsize')
fig, ax = plt.subplots(nrows=2, ncols=1, figsize=(fig_w, 2 * fig_h))
ax[0].plot(mu_visuals, max_posteriors, '-g', label='mean')
ax[0].set_xlabel('Visual stimulus position')
ax[0].set_ylabel('Multiplied posterior mean')
ax[0].set_title('Sample output')
ax[1].plot(mu_visuals, mu_posteriors, '--', color='xkcd:gray', label='argmax')
ax[1].set_xlabel('Visual stimulus position')
ax[1].set_ylabel('Analytical posterior mean')
fig.tight_layout()
ax[1].set_title('Hurray for math!')
def multimodal_plot(x, example_prior, example_likelihood,
mu_visuals, posterior_modes):
"""Helper function for plotting Section 4 results"""
fig_w, fig_h = plt.rcParams.get('figure.figsize')
fig, ax = plt.subplots(nrows=2, ncols=1, figsize=(fig_w, 2*fig_h), sharex=True)
# Plot the last instance that we tried.
posterior_plot(x,
example_prior,
example_likelihood,
compute_posterior_pointwise(example_prior, example_likelihood),
ax=ax[0]
)
ax[0].set_title('Example combination')
ax[1].plot(mu_visuals, posterior_modes, '-g', label='argmax')
ax[1].set_xlabel('Visual stimulus position\n(Mean of blue dist. above)')
ax[1].set_ylabel('Posterior mode\n(Peak of green dist. above)')
fig.tight_layout()
###Output
_____no_output_____
###Markdown
Section 1: The Gaussian DistributionBayesian analysis operates on probability distributions. Although these can take many forms, the Gaussian distribution is a very common choice. Because of the central limit theorem, many quantities are Gaussian-distributed. Gaussians also have some mathematical properties that permit simple closed-form solutions to several important problems. In this exercise, you will implement a Gaussian by filling in the missing portion of `my_gaussian` below. Gaussians have two parameters. The **mean** $\mu$, which sets the location of its center. Its "scale" or spread is controlled by its **standard deviation** $\sigma$ or its square, the **variance** $\sigma^2$. (Be careful not to use one when the other is required). The equation for a Gaussian is:$$\mathcal{N}(\mu,\sigma^2) = \frac{1}{\sqrt{2\pi\sigma^2}}\exp\left(\frac{-(x-\mu)^2}{2\sigma^2}\right)$$Also, don't forget that this is a probability distribution and should therefore sum to one. While this happens "automatically" when integrated from $-\infty$ to $\infty$, your version will only be computed over a finite number of points. You therefore need to explicitly normalize it yourself. Test out your implementation with a $\mu = -1$ and $\sigma = 1$. After you have it working, play with the parameters to develop an intuition for how changing $\mu$ and $\sigma$ alter the shape of the Gaussian. This is important, because subsequent exercises will be built out of Gaussians. Exercise 1: Implement a Gaussian
###Code
def my_gaussian(x_points, mu, sigma):
"""
Returns normalized Gaussian estimated at points `x_points`, with parameters:
mean `mu` and std `sigma`
Args:
x_points (numpy array of floats): points at which the gaussian is
evaluated
mu (scalar): mean of the Gaussian
sigma (scalar): std of the gaussian
Returns:
(numpy array of floats) : normalized Gaussian evaluated at `x`
"""
###################################################################
## Add code to calcualte the gaussian px as a function of mu and sigma,
## for every x in x_points
## Function Hints: exp -> np.exp()
## power -> z**2
## remove the raise below to test your function
raise NotImplementedError("You need to implement the Gaussian function!")
###################################################################
px = ...
return px
x = np.arange(-8, 9, 0.1)
# Uncomment to plot the results
# px = my_gaussian(x, -1, 1)
# my_plot_single(x, px)
###Output
_____no_output_____
###Markdown
[*Click for solution*](https://github.com/erlichlab/course-content/tree/master//tutorials/W2D1_BayesianStatistics/solutions/W2D1_Tutorial1_Solution_aeeeaedf.py)*Example output:* Section 2. Bayes' Theorem and the Posterior
###Code
#@title Video 2: Bayes' theorem
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = "https://player.bilibili.com/player.html?bvid={0}&page={1}".format(id, page)
super(BiliVideo, self).__init__(src, width, height, **kwargs)
video = BiliVideo(id='BV1Hi4y1V7UN', width=854, height=480, fs=1)
print("Video available at https://www.bilibili.com/video/{0}".format(video.id))
video
###Output
Video available at https://www.bilibili.com/video/BV1Hi4y1V7UN
###Markdown
Bayes' rule tells us how to combine two sources of information: the prior (e.g., a noisy representation of our expectations about where the stimulus might come from) and the likelihood (e.g., a noisy representation of the stimulus position on a given trial), to obtain a posterior distribution taking into account both pieces of information. Bayes' rule states:\begin{eqnarray}\text{Posterior} = \frac{ \text{Likelihood} \times \text{Prior}}{ \text{Normalization constant}}\end{eqnarray}When both the prior and likelihood are Gaussians, this translates into the following form:$$\begin{array}{rcl}\text{Likelihood} &=& \mathcal{N}(\mu_{likelihood},\sigma_{likelihood}^2) \\\text{Prior} &=& \mathcal{N}(\mu_{prior},\sigma_{prior}^2) \\\text{Posterior} &\propto& \mathcal{N}(\mu_{likelihood},\sigma_{likelihood}^2) \times \mathcal{N}(\mu_{prior},\sigma_{prior}^2) \\&&= \mathcal{N}\left( \frac{\sigma^2_{likelihood}\mu_{prior}+\sigma^2_{prior}\mu_{likelihood}}{\sigma^2_{likelihood}+\sigma^2_{prior}}, \frac{\sigma^2_{likelihood}\sigma^2_{prior}}{\sigma^2_{likelihood}+\sigma^2_{prior}} \right) \end{array}$$In these equations, $\mathcal{N}(\mu,\sigma^2)$ denotes a Gaussian distribution with parameters $\mu$ and $\sigma^2$:$$\mathcal{N}(\mu, \sigma) = \frac{1}{\sqrt{2 \pi \sigma^2}} \; \exp \bigg( \frac{-(x-\mu)^2}{2\sigma^2} \bigg)$$In Exercise 2A, we will use the first form of the posterior, where the two distributions are combined via pointwise multiplication. Although this method requires more computation, it works for any type of probability distribution. In Exercise 2B, we will see that the closed-form solution shown on the line below produces the same result. Exercise 2A: Finding the posterior computationallyImagine an experiment where participants estimate the location of a noise-emitting object. To estimate its position, the participants can use two sources of information: 1. new noisy auditory information (the likelihood) 2. prior visual expectations of where the stimulus is likely to come from (visual prior). The auditory and visual information are both noisy, so participants will combine these sources of information to better estimate the position of the object.We will use Gaussian distributions to represent the auditory likelihood (in red), and a Gaussian visual prior (expectations - in blue). Using Bayes rule, you will combine them into a posterior distribution that summarizes the probability that the object is in each location. We have provided you with a ready-to-use plotting function, and a code skeleton.* Use `my_gaussian`, the answer to exercise 1, to generate an auditory likelihood with parameters $\mu$ = 3 and $\sigma$ = 1.5* Generate a visual prior with parameters $\mu$ = -1 and $\sigma$ = 1.5* Calculate the posterior using pointwise multiplication of the likelihood and prior. Don't forget to normalize so the posterior adds up to 1. * Plot the likelihood, prior and posterior using the predefined function `posterior_plot`
###Code
def compute_posterior_pointwise(prior, likelihood):
##############################################################################
# Write code to compute the posterior from the prior and likelihood via
# pointwise multiplication. (You may assume both are defined over the same x-axis)
#
# Comment out the line below to test your solution
raise NotImplementedError("Finish the simulation code first")
##############################################################################
posterior = ...
return posterior
def localization_simulation(mu_auditory=3.0, sigma_auditory=1.5,
mu_visual=-1.0, sigma_visual=1.5):
##############################################################################
## Using the x variable below,
## create a gaussian called 'auditory' with mean 3, and std 1.5
## create a gaussian called 'visual' with mean -1, and std 1.5
#
#
## Comment out the line below to test your solution
raise NotImplementedError("Finish the simulation code first")
###############################################################################
x = np.arange(-8, 9, 0.1)
auditory = ...
visual = ...
posterior = compute_posterior_pointwise(auditory, visual)
return x, auditory, visual, posterior
# Uncomment the lines below to plot the results
# x, auditory, visual, posterior_pointwise = localization_simulation()
# posterior_plot(x, auditory, visual, posterior_pointwise)
###Output
_____no_output_____
###Markdown
[*Click for solution*](https://github.com/erlichlab/course-content/tree/master//tutorials/W2D1_BayesianStatistics/solutions/W2D1_Tutorial1_Solution_39d14917.py)*Example output:* Interactive Demo: What affects the posterior?Now that we can compute the posterior of two Gaussians with *Bayes rule*, let's vary the parameters of those Gaussians to see how changing the prior and likelihood affect the posterior. **Hit the Play button or Ctrl+Enter in the cell below** and play with the sliders to get an intuition for how the means and standard deviations of prior and likelihood influence the posterior.When does the prior have the strongest influence over the posterior? When is it the weakest?
###Code
#@title
#@markdown Make sure you execute this cell to enable the widget!
x = np.arange(-10, 11, 0.1)
import ipywidgets as widgets
def refresh(mu_auditory=3, sigma_auditory=1.5, mu_visual=-1, sigma_visual=1.5):
auditory = my_gaussian(x, mu_auditory, sigma_auditory)
visual = my_gaussian(x, mu_visual, sigma_visual)
posterior_pointwise = visual * auditory
posterior_pointwise /= posterior_pointwise.sum()
w_auditory = (sigma_visual** 2) / (sigma_auditory**2 + sigma_visual**2)
theoretical_prediction = mu_auditory * w_auditory + mu_visual * (1 - w_auditory)
ax = posterior_plot(x, auditory, visual, posterior_pointwise)
ax.plot([theoretical_prediction, theoretical_prediction],
[0, posterior_pointwise.max() * 1.2], '-.', color='xkcd:medium gray')
ax.set_title(f"Gray line shows analytical mean of posterior: {theoretical_prediction:0.2f}")
plt.show()
style = {'description_width': 'initial'}
_ = widgets.interact(refresh,
mu_auditory=widgets.FloatSlider(value=2, min=-10, max=10, step=0.5, description="mu_auditory:", style=style),
sigma_auditory=widgets.FloatSlider(value=0.5, min=0.5, max=10, step=0.5, description="sigma_auditory:", style=style),
mu_visual=widgets.FloatSlider(value=-2, min=-10, max=10, step=0.5, description="mu_visual:", style=style),
sigma_visual=widgets.FloatSlider(value=0.5, min=0.5, max=10, step=0.5, description="sigma_visual:", style=style)
)
###Output
/opt/hostedtoolcache/Python/3.7.8/x64/lib/python3.7/site-packages/ipykernel_launcher.py:49: MatplotlibDeprecationWarning: Case-insensitive properties were deprecated in 3.3 and support will be removed two minor releases later
/opt/hostedtoolcache/Python/3.7.8/x64/lib/python3.7/site-packages/ipykernel_launcher.py:50: MatplotlibDeprecationWarning: Case-insensitive properties were deprecated in 3.3 and support will be removed two minor releases later
/opt/hostedtoolcache/Python/3.7.8/x64/lib/python3.7/site-packages/ipykernel_launcher.py:51: MatplotlibDeprecationWarning: Case-insensitive properties were deprecated in 3.3 and support will be removed two minor releases later
###Markdown
Video 3: Multiplying Gaussians
###Code
#@title
from IPython.display import YouTubeVideo
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = "https://player.bilibili.com/player.html?bvid={0}&page={1}".format(id, page)
super(BiliVideo, self).__init__(src, width, height, **kwargs)
video = BiliVideo(id='BV1ni4y1V7bQ', width=854, height=480, fs=1)
print("Video available at https://www.bilibili.com/video/{0}".format(video.id))
video
###Output
Video available at https://www.bilibili.com/video/BV1ni4y1V7bQ
###Markdown
Exercise 2B: Finding the posterior analytically[If you are running short on time, feel free to skip the coding exercise below].As you may have noticed from the interactive demo, the product of two Gaussian distributions, like our prior and likelihood, remains a Gaussian, regardless of the parameters. We can directly compute the parameters of that Gaussian from the means and variances of the prior and likelihood. For example, the posterior mean is given by:$$ \mu_{posterior} = \frac{\mu_{auditory} \cdot \frac{1}{\sigma_{auditory}^2} + \mu_{visual} \cdot \frac{1}{\sigma_{visual}^2}}{1/\sigma_{auditory}^2 + 1/\sigma_{visual}^2} $$This formula is a special case for two Gaussians, but is a very useful one because:* The posterior has the same form (here, a normal distribution) as the prior, and* There is simple, closed-form expression for its parameters.When these properties hold, we call them **conjugate distributions** or **conjugate priors** (for a particular likelihood). Working with conjugate distributions is very convenient; otherwise, it is often necessary to use computationally-intensive numerical methods to combine the prior and likelihood. In this exercise, we ask you to verify that property. To do so, we will hold our auditory likelihood constant as an $\mathcal{N}(3, 1.5)$ distribution, while considering visual priors with different means ranging from $\mu=-10$ to $\mu=10$. For each prior,* Compute the posterior distribution using the function you wrote in Exercise 2A. Next, find its mean. The mean of a probability distribution is $\int_x p(x) dx$ or $\sum_x x\cdot p(x)$. * Compute the analytical posterior mean from auditory and visual using the equation above.* Use the provided plotting code to plot both estimates of the mean. Are the estimates of the posterior mean the same in both cases? Using these results, try to predict the posterior mean for the combination of a $\mathcal{N}(-4,4)$ prior and and $\mathcal{N}(4, 2)$ likelihood. Use the widget above to check your prediction. You can enter values directly by clicking on the numbers to the right of each slider; $\sqrt{2} \approx 1.41$.
###Code
def compare_computational_analytical_means():
x = np.arange(-10, 11, 0.1)
# Fixed auditory likelihood
mu_auditory = 3
sigma_auditory = 1.5
likelihood = my_gaussian(x, mu_auditory, sigma_auditory)
# Varying visual prior
mu_visuals = np.linspace(-10, 10)
sigma_visual = 1.5
# Accumulate results here
mus_by_integration = []
mus_analytical = []
for mu_visual in mu_visuals:
prior = my_gaussian(x, mu_visual, sigma_visual)
posterior = compute_posterior_pointwise(prior, likelihood)
############################################################################
## Add code that will find the posterior mean via numerical integration
#
############################################################################
mu_integrated = ...
############################################################################
## Add more code below that will calculate the posterior mean analytically
#
# Comment out the line below to test your solution
raise NotImplementedError("Please add code to find the mean both ways first")
############################################################################
mu_analytical = ...
mus_by_integration.append(mu_integrated)
mus_analytical.append(mu_analytical)
return mu_visuals, mus_by_integration, mus_analytical
# Uncomment the lines below to visualize your results
# mu_visuals, mu_computational, mu_analytical = compare_computational_analytical_means()
# plot_visual(mu_visuals, mu_computational, mu_analytical)
###Output
_____no_output_____
###Markdown
[*Click for solution*](https://github.com/erlichlab/course-content/tree/master//tutorials/W2D1_BayesianStatistics/solutions/W2D1_Tutorial1_Solution_8e15215d.py)*Example output:* Section 3: ConclusionThis tutorial introduced the Gaussian distribution and used Bayes' Theorem to combine Gaussians representing priors and likelihoods. In the next tutorial, we will use these concepts to probe how subjects integrate sensory information.
###Code
#@title Video 4: Conclusion
from IPython.display import YouTubeVideo
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = "https://player.bilibili.com/player.html?bvid={0}&page={1}".format(id, page)
super(BiliVideo, self).__init__(src, width, height, **kwargs)
video = BiliVideo(id='BV1wv411q7ex', width=854, height=480, fs=1)
print("Video available at https://www.bilibili.com/video/{0}".format(video.id))
video
###Output
Video available at https://www.bilibili.com/video/BV1wv411q7ex
###Markdown
Bonus Section: Multimodal Priors**Only do this if the first half-hour has not yet passed.**The preceeding exercises used a Gaussian prior, implying that participants expected the stimulus to come from a single location, though they might not know precisely where. However, suppose the subjects actually thought that sound might come from one of two distinct locations. Perhaps they can see two speakers (and know that speakers often emit noise). We could model this using a Gaussian prior with a large $\sigma$ that covers both locations, but that would also make every point in between seem likely too.A better approach is to adjust the form of the prior so that it better matches the participants' experiences/expectations. In this optional exercise, we will build a bimodal (2-peaked) prior out of Gaussians and examine the resulting posterior and its peaks. Exercise 3: Implement and test a multimodal prior* Complete the `bimodal_prior` function below to create a bimodal prior, comprised of the sum of two Gaussians with means $\mu = -3$ and $\mu = 3$. Use $\sigma=1$ for both Gaussians. Be sure to normalize the result so it is a proper probability distribution. * In Exercise 2, we used the mean location to summarize the posterior distribution. This is not always the best choice, especially for multimodal distributions. What is the mean of our new prior? Is it a particularly likely location for the stimulus? Instead, we will use the posterior **mode** to summarize the distribution. The mode is the *location* of the most probable part of the distribution. Complete `posterior_mode` below, to find it. (Hint: `np.argmax` returns the *index* of the largest element in an array).* Run the provided simulation and plotting code. Observe what happens to the posterior as the likelihood gets closer to the different peaks of the prior.* Notice what happens to the posterior when the likelihood is exactly in between the two modes of the prior (i.e., $\mu_{Likelihood} = 0$)
###Code
def bimodal_prior(x, mu_1=-3, sigma_1=1, mu_2=3, sigma_2=1):
################################################################################
## Finish this function so that it returns a bimodal prior, comprised of the
# sum of two Gaussians
#
# Comment out the line below to test out your solution
raise NotImplementedError("Please implement the bimodal prior")
################################################################################
prior = ...
return prior
def posterior_mode(x, posterior):
################################################################################
## Finish this function so that it returns the location of the mode
#
# Comment out the line below to test out your solution
raise NotImplementedError("Please implement the bimodal prior")
################################################################################
mode = ...
return mode
def multimodal_simulation(x, mus_visual, sigma_visual=1):
"""
Simulate an experiment where bimodal prior is held constant while
a Gaussian visual likelihood is shifted across locations.
Args:
x: array of points at which prior/likelihood/posterior are evaluated
mus_visual: array of means for the Gaussian likelihood
sigma_visual: scalar standard deviation for the Gaussian likelihood
Returns:
posterior_modes: array containing the posterior mode for each mean in mus_visual
"""
prior = bimodal_prior(x, -3, 1, 3, 1)
posterior_modes = []
for mu in mus_visual:
likelihood = my_gaussian(x, mu, 3)
posterior = compute_posterior_pointwise(prior, likelihood)
p_mode = posterior_mode(x, posterior)
posterior_modes.append(p_mode)
return posterior_modes
x = np.arange(-10, 10, 0.1)
mus = np.arange(-8, 8, 0.05)
# Uncomment the lines below to visualize your results
# posterior_modes = multimodal_simulation(x, mus, 1)
# multimodal_plot(x,
# bimodal_prior(x, -3, 1, 3, 1),
# my_gaussian(x, 1, 1),
# mus, posterior_modes)
###Output
_____no_output_____
###Markdown
Neuromatch Academy: Week 2, Day 1, Tutorial 1 Bayes rule with Gaussians__Content creators:__ Vincent Valton, Konrad Kording, with help from Matt Krause__Content reviewers:__ Matt Krause, Jesse Livezey, Karolina Stosio, Saeed Salehi, Michael Waskom Tutorial ObjectivesThis is the first in a series of three main tutorials (+ one bonus tutorial) on Bayesian statistics. In these tutorials, we will develop a Bayesian model for localizing sounds based on audio and visual cues. This model will combine **prior** information about where sounds generally originate with sensory information about the **likelihood** that a specific sound came from a particular location. As we will see in subsequent lessons, the resulting **posterior distribution** not only allows us to make optimal decision about the sound's origin, but also lets us quantify how uncertain that decision is. Bayesian techniques are therefore useful **normative models**: the behavior of human or animal subjects can be compared against these models to determine how efficiently they make use of information. This notebook will introduce two fundamental building blocks for Bayesian statistics: the Gaussian distribution and the Bayes Theorem. You will: 1. Implement a Gaussian distribution2. Use Bayes' Theorem to find the posterior from a Gaussian-distributed prior and likelihood. 3. Change the likelihood mean and variance and observe how posterior changes.4. Advanced (*optional*): Observe what happens if the prior is a mixture of two gaussians?
###Code
#@title Video 1: Introduction to Bayesian Statistics
from IPython.display import YouTubeVideo
video = YouTubeVideo(id='K4sSKZtk-Sc', width=854, height=480, fs=1)
print("Video available at https://youtube.com/watch?v=" + video.id)
video
###Output
_____no_output_____
###Markdown
Setup Please execute the cells below to initialize the notebook environment.
###Code
import numpy as np
import matplotlib.pyplot as plt
#@title Figure Settings
import ipywidgets as widgets
plt.style.use("https://raw.githubusercontent.com/NeuromatchAcademy/course-content/master/nma.mplstyle")
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
#@title Helper functions
def my_plot_single(x, px):
"""
Plots normalized Gaussian distribution
Args:
x (numpy array of floats): points at which the likelihood has been evaluated
px (numpy array of floats): normalized probabilities for prior evaluated at each `x`
Returns:
Nothing.
"""
if px is None:
px = np.zeros_like(x)
fig, ax = plt.subplots()
ax.plot(x, px, '-', color='C2', LineWidth=2, label='Prior')
ax.legend()
ax.set_ylabel('Probability')
ax.set_xlabel('Orientation (Degrees)')
def posterior_plot(x, likelihood=None, prior=None, posterior_pointwise=None, ax=None):
"""
Plots normalized Gaussian distributions and posterior
Args:
x (numpy array of floats): points at which the likelihood has been evaluated
auditory (numpy array of floats): normalized probabilities for auditory likelihood evaluated at each `x`
visual (numpy array of floats): normalized probabilities for visual likelihood evaluated at each `x`
posterior (numpy array of floats): normalized probabilities for the posterior evaluated at each `x`
ax: Axis in which to plot. If None, create new axis.
Returns:
Nothing.
"""
if likelihood is None:
likelihood = np.zeros_like(x)
if prior is None:
prior = np.zeros_like(x)
if posterior_pointwise is None:
posterior_pointwise = np.zeros_like(x)
if ax is None:
fig, ax = plt.subplots()
ax.plot(x, likelihood, '-C1', LineWidth=2, label='Auditory')
ax.plot(x, prior, '-C0', LineWidth=2, label='Visual')
ax.plot(x, posterior_pointwise, '-C2', LineWidth=2, label='Posterior')
ax.legend()
ax.set_ylabel('Probability')
ax.set_xlabel('Orientation (Degrees)')
return ax
def plot_visual(mu_visuals, mu_posteriors, max_posteriors):
"""
Plots the comparison of computing the mean of the posterior analytically and
the max of the posterior empirically via multiplication.
Args:
mu_visuals (numpy array of floats): means of the visual likelihood
mu_posteriors (numpy array of floats): means of the posterior, calculated analytically
max_posteriors (numpy array of floats): max of the posteriors, calculated via maxing the max_posteriors.
posterior (numpy array of floats): normalized probabilities for the posterior evaluated at each `x`
Returns:
Nothing.
"""
fig_w, fig_h = plt.rcParams.get('figure.figsize')
fig, ax = plt.subplots(nrows=2, ncols=1, figsize=(fig_w, 2 * fig_h))
ax[0].plot(mu_visuals, max_posteriors, '-C2', label='mean')
ax[0].set_xlabel('Visual stimulus position')
ax[0].set_ylabel('Multiplied posterior mean')
ax[0].set_title('Sample output')
ax[1].plot(mu_visuals, mu_posteriors, '--', color='xkcd:gray', label='argmax')
ax[1].set_xlabel('Visual stimulus position')
ax[1].set_ylabel('Analytical posterior mean')
fig.tight_layout()
ax[1].set_title('Hurray for math!')
def multimodal_plot(x, example_prior, example_likelihood,
mu_visuals, posterior_modes):
"""Helper function for plotting Section 4 results"""
fig_w, fig_h = plt.rcParams.get('figure.figsize')
fig, ax = plt.subplots(nrows=2, ncols=1, figsize=(fig_w, 2*fig_h), sharex=True)
# Plot the last instance that we tried.
posterior_plot(x,
example_prior,
example_likelihood,
compute_posterior_pointwise(example_prior, example_likelihood),
ax=ax[0]
)
ax[0].set_title('Example combination')
ax[1].plot(mu_visuals, posterior_modes, '-C2', label='argmax')
ax[1].set_xlabel('Visual stimulus position\n(Mean of blue dist. above)')
ax[1].set_ylabel('Posterior mode\n(Peak of green dist. above)')
fig.tight_layout()
###Output
_____no_output_____
###Markdown
Section 1: The Gaussian DistributionBayesian analysis operates on probability distributions. Although these can take many forms, the Gaussian distribution is a very common choice. Because of the central limit theorem, many quantities are Gaussian-distributed. Gaussians also have some mathematical properties that permit simple closed-form solutions to several important problems. In this exercise, you will implement a Gaussian by filling in the missing portion of `my_gaussian` below. Gaussians have two parameters. The **mean** $\mu$, which sets the location of its center. Its "scale" or spread is controlled by its **standard deviation** $\sigma$ or its square, the **variance** $\sigma^2$. (Be careful not to use one when the other is required). The equation for a Gaussian is:$$\mathcal{N}(\mu,\sigma^2) = \frac{1}{\sqrt{2\pi\sigma^2}}\exp\left(\frac{-(x-\mu)^2}{2\sigma^2}\right)$$Also, don't forget that this is a probability distribution and should therefore sum to one. While this happens "automatically" when integrated from $-\infty$ to $\infty$, your version will only be computed over a finite number of points. You therefore need to explicitly normalize it yourself. Test out your implementation with a $\mu = -1$ and $\sigma = 1$. After you have it working, play with the parameters to develop an intuition for how changing $\mu$ and $\sigma$ alter the shape of the Gaussian. This is important, because subsequent exercises will be built out of Gaussians. Exercise 1: Implement a Gaussian
###Code
def my_gaussian(x_points, mu, sigma):
"""
Returns normalized Gaussian estimated at points `x_points`, with parameters:
mean `mu` and std `sigma`
Args:
x_points (numpy array of floats): points at which the gaussian is
evaluated
mu (scalar): mean of the Gaussian
sigma (scalar): std of the gaussian
Returns:
(numpy array of floats) : normalized Gaussian evaluated at `x`
"""
###################################################################
## Add code to calcualte the gaussian px as a function of mu and sigma,
## for every x in x_points
## Function Hints: exp -> np.exp()
## power -> z**2
## remove the raise below to test your function
raise NotImplementedError("You need to implement the Gaussian function!")
###################################################################
px = ...
return px
x = np.arange(-8, 9, 0.1)
# Uncomment to plot the results
# px = my_gaussian(x, -1, 1)
# my_plot_single(x, px)
###Output
_____no_output_____
###Markdown
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W2D1_BayesianStatistics/solutions/W2D1_Tutorial1_Solution_cce0848d.py)*Example output:* Section 2. Bayes' Theorem and the Posterior
###Code
#@title Video 2: Bayes' theorem
from IPython.display import YouTubeVideo
video = YouTubeVideo(id='ewQPHQMcdBs', width=854, height=480, fs=1)
print("Video available at https://youtube.com/watch?v=" + video.id)
video
###Output
_____no_output_____
###Markdown
Bayes' rule tells us how to combine two sources of information: the prior (e.g., a noisy representation of our expectations about where the stimulus might come from) and the likelihood (e.g., a noisy representation of the stimulus position on a given trial), to obtain a posterior distribution taking into account both pieces of information. Bayes' rule states:\begin{eqnarray}\text{Posterior} = \frac{ \text{Likelihood} \times \text{Prior}}{ \text{Normalization constant}}\end{eqnarray}When both the prior and likelihood are Gaussians, this translates into the following form:$$\begin{array}{rcl}\text{Likelihood} &=& \mathcal{N}(\mu_{likelihood},\sigma_{likelihood}^2) \\\text{Prior} &=& \mathcal{N}(\mu_{prior},\sigma_{prior}^2) \\\text{Posterior} &\propto& \mathcal{N}(\mu_{likelihood},\sigma_{likelihood}^2) \times \mathcal{N}(\mu_{prior},\sigma_{prior}^2) \\&&= \mathcal{N}\left( \frac{\sigma^2_{likelihood}\mu_{prior}+\sigma^2_{prior}\mu_{likelihood}}{\sigma^2_{likelihood}+\sigma^2_{prior}}, \frac{\sigma^2_{likelihood}\sigma^2_{prior}}{\sigma^2_{likelihood}+\sigma^2_{prior}} \right) \end{array}$$In these equations, $\mathcal{N}(\mu,\sigma^2)$ denotes a Gaussian distribution with parameters $\mu$ and $\sigma^2$:$$\mathcal{N}(\mu, \sigma) = \frac{1}{\sqrt{2 \pi \sigma^2}} \; \exp \bigg( \frac{-(x-\mu)^2}{2\sigma^2} \bigg)$$In Exercise 2A, we will use the first form of the posterior, where the two distributions are combined via pointwise multiplication. Although this method requires more computation, it works for any type of probability distribution. In Exercise 2B, we will see that the closed-form solution shown on the line below produces the same result. Exercise 2A: Finding the posterior computationallyImagine an experiment where participants estimate the location of a noise-emitting object. To estimate its position, the participants can use two sources of information: 1. new noisy auditory information (the likelihood) 2. prior visual expectations of where the stimulus is likely to come from (visual prior). The auditory and visual information are both noisy, so participants will combine these sources of information to better estimate the position of the object.We will use Gaussian distributions to represent the auditory likelihood (in red), and a Gaussian visual prior (expectations - in blue). Using Bayes rule, you will combine them into a posterior distribution that summarizes the probability that the object is in each location. We have provided you with a ready-to-use plotting function, and a code skeleton.* Use `my_gaussian`, the answer to exercise 1, to generate an auditory likelihood with parameters $\mu$ = 3 and $\sigma$ = 1.5* Generate a visual prior with parameters $\mu$ = -1 and $\sigma$ = 1.5* Calculate the posterior using pointwise multiplication of the likelihood and prior. Don't forget to normalize so the posterior adds up to 1. * Plot the likelihood, prior and posterior using the predefined function `posterior_plot`
###Code
def compute_posterior_pointwise(prior, likelihood):
##############################################################################
# Write code to compute the posterior from the prior and likelihood via
# pointwise multiplication. (You may assume both are defined over the same x-axis)
#
# Comment out the line below to test your solution
raise NotImplementedError("Finish the simulation code first")
##############################################################################
posterior = ...
return posterior
def localization_simulation(mu_auditory=3.0, sigma_auditory=1.5,
mu_visual=-1.0, sigma_visual=1.5):
##############################################################################
## Using the x variable below,
## create a gaussian called 'auditory' with mean 3, and std 1.5
## create a gaussian called 'visual' with mean -1, and std 1.5
#
#
## Comment out the line below to test your solution
raise NotImplementedError("Finish the simulation code first")
###############################################################################
x = np.arange(-8, 9, 0.1)
auditory = ...
visual = ...
posterior = compute_posterior_pointwise(auditory, visual)
return x, auditory, visual, posterior
# Uncomment the lines below to plot the results
# x, auditory, visual, posterior_pointwise = localization_simulation()
# posterior_plot(x, auditory, visual, posterior_pointwise)
###Output
_____no_output_____
###Markdown
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W2D1_BayesianStatistics/solutions/W2D1_Tutorial1_Solution_67c48f25.py)*Example output:* Interactive Demo: What affects the posterior?Now that we can compute the posterior of two Gaussians with *Bayes rule*, let's vary the parameters of those Gaussians to see how changing the prior and likelihood affect the posterior. **Hit the Play button or Ctrl+Enter in the cell below** and play with the sliders to get an intuition for how the means and standard deviations of prior and likelihood influence the posterior.When does the prior have the strongest influence over the posterior? When is it the weakest?
###Code
#@title
#@markdown Make sure you execute this cell to enable the widget!
x = np.arange(-10, 11, 0.1)
import ipywidgets as widgets
def refresh(mu_auditory=3, sigma_auditory=1.5, mu_visual=-1, sigma_visual=1.5):
auditory = my_gaussian(x, mu_auditory, sigma_auditory)
visual = my_gaussian(x, mu_visual, sigma_visual)
posterior_pointwise = visual * auditory
posterior_pointwise /= posterior_pointwise.sum()
w_auditory = (sigma_visual** 2) / (sigma_auditory**2 + sigma_visual**2)
theoretical_prediction = mu_auditory * w_auditory + mu_visual * (1 - w_auditory)
ax = posterior_plot(x, auditory, visual, posterior_pointwise)
ax.plot([theoretical_prediction, theoretical_prediction],
[0, posterior_pointwise.max() * 1.2], '-.', color='xkcd:medium gray')
ax.set_title(f"Gray line shows analytical mean of posterior: {theoretical_prediction:0.2f}")
plt.show()
style = {'description_width': 'initial'}
_ = widgets.interact(refresh,
mu_auditory=widgets.FloatSlider(value=2, min=-10, max=10, step=0.5, description="mu_auditory:", style=style),
sigma_auditory=widgets.FloatSlider(value=0.5, min=0.5, max=10, step=0.5, description="sigma_auditory:", style=style),
mu_visual=widgets.FloatSlider(value=-2, min=-10, max=10, step=0.5, description="mu_visual:", style=style),
sigma_visual=widgets.FloatSlider(value=0.5, min=0.5, max=10, step=0.5, description="sigma_visual:", style=style)
)
###Output
_____no_output_____
###Markdown
Video 3: Multiplying Gaussians
###Code
#@title
from IPython.display import YouTubeVideo
video = YouTubeVideo(id='AbXorOLBrws', width=854, height=480, fs=1)
print("Video available at https://youtube.com/watch?v=" + video.id)
video
###Output
_____no_output_____
###Markdown
Exercise 2B: Finding the posterior analytically[If you are running short on time, feel free to skip the coding exercise below].As you may have noticed from the interactive demo, the product of two Gaussian distributions, like our prior and likelihood, remains a Gaussian, regardless of the parameters. We can directly compute the parameters of that Gaussian from the means and variances of the prior and likelihood. For example, the posterior mean is given by:$$ \mu_{posterior} = \frac{\mu_{auditory} \cdot \frac{1}{\sigma_{auditory}^2} + \mu_{visual} \cdot \frac{1}{\sigma_{visual}^2}}{1/\sigma_{auditory}^2 + 1/\sigma_{visual}^2} $$This formula is a special case for two Gaussians, but is a very useful one because:* The posterior has the same form (here, a normal distribution) as the prior, and* There is simple, closed-form expression for its parameters.When these properties hold, we call them **conjugate distributions** or **conjugate priors** (for a particular likelihood). Working with conjugate distributions is very convenient; otherwise, it is often necessary to use computationally-intensive numerical methods to combine the prior and likelihood. In this exercise, we ask you to verify that property. To do so, we will hold our auditory likelihood constant as an $\mathcal{N}(3, 1.5)$ distribution, while considering visual priors with different means ranging from $\mu=-10$ to $\mu=10$. For each prior,* Compute the posterior distribution using the function you wrote in Exercise 2A. Next, find its mean. The mean of a probability distribution is $\int_x p(x) dx$ or $\sum_x x\cdot p(x)$. * Compute the analytical posterior mean from auditory and visual using the equation above.* Use the provided plotting code to plot both estimates of the mean. Are the estimates of the posterior mean the same in both cases? Using these results, try to predict the posterior mean for the combination of a $\mathcal{N}(-4,4)$ prior and and $\mathcal{N}(4, 2)$ likelihood. Use the widget above to check your prediction. You can enter values directly by clicking on the numbers to the right of each slider; $\sqrt{2} \approx 1.41$.
###Code
def compare_computational_analytical_means():
x = np.arange(-10, 11, 0.1)
# Fixed auditory likelihood
mu_auditory = 3
sigma_auditory = 1.5
likelihood = my_gaussian(x, mu_auditory, sigma_auditory)
# Varying visual prior
mu_visuals = np.linspace(-10, 10)
sigma_visual = 1.5
# Accumulate results here
mus_by_integration = []
mus_analytical = []
for mu_visual in mu_visuals:
prior = my_gaussian(x, mu_visual, sigma_visual)
posterior = compute_posterior_pointwise(prior, likelihood)
############################################################################
## Add code that will find the posterior mean via numerical integration
#
############################################################################
mu_integrated = ...
############################################################################
## Add more code below that will calculate the posterior mean analytically
#
# Comment out the line below to test your solution
raise NotImplementedError("Please add code to find the mean both ways first")
############################################################################
mu_analytical = ...
mus_by_integration.append(mu_integrated)
mus_analytical.append(mu_analytical)
return mu_visuals, mus_analytical, mus_by_integration
# Uncomment the lines below to visualize your results
# mu_visuals, mu_analytical, mu_computational = compare_computational_analytical_means()
# plot_visual(mu_visuals, mu_analytical, mu_computational)
###Output
_____no_output_____
###Markdown
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W2D1_BayesianStatistics/solutions/W2D1_Tutorial1_Solution_642e1b02.py)*Example output:* Section 3: ConclusionThis tutorial introduced the Gaussian distribution and used Bayes' Theorem to combine Gaussians representing priors and likelihoods. In the next tutorial, we will use these concepts to probe how subjects integrate sensory information.
###Code
#@title Video 4: Conclusion
from IPython.display import YouTubeVideo
video = YouTubeVideo(id='YC8GylOAAHs', width=854, height=480, fs=1)
print("Video available at https://youtube.com/watch?v=" + video.id)
video
###Output
_____no_output_____
###Markdown
Bonus Section: Multimodal Priors**Only do this if the first half-hour has not yet passed.**The preceeding exercises used a Gaussian prior, implying that participants expected the stimulus to come from a single location, though they might not know precisely where. However, suppose the subjects actually thought that sound might come from one of two distinct locations. Perhaps they can see two speakers (and know that speakers often emit noise). We could model this using a Gaussian prior with a large $\sigma$ that covers both locations, but that would also make every point in between seem likely too.A better approach is to adjust the form of the prior so that it better matches the participants' experiences/expectations. In this optional exercise, we will build a bimodal (2-peaked) prior out of Gaussians and examine the resulting posterior and its peaks. Exercise 3: Implement and test a multimodal prior* Complete the `bimodal_prior` function below to create a bimodal prior, comprised of the sum of two Gaussians with means $\mu = -3$ and $\mu = 3$. Use $\sigma=1$ for both Gaussians. Be sure to normalize the result so it is a proper probability distribution. * In Exercise 2, we used the mean location to summarize the posterior distribution. This is not always the best choice, especially for multimodal distributions. What is the mean of our new prior? Is it a particularly likely location for the stimulus? Instead, we will use the posterior **mode** to summarize the distribution. The mode is the *location* of the most probable part of the distribution. Complete `posterior_mode` below, to find it. (Hint: `np.argmax` returns the *index* of the largest element in an array).* Run the provided simulation and plotting code. Observe what happens to the posterior as the likelihood gets closer to the different peaks of the prior.* Notice what happens to the posterior when the likelihood is exactly in between the two modes of the prior (i.e., $\mu_{Likelihood} = 0$)
###Code
def bimodal_prior(x, mu_1=-3, sigma_1=1, mu_2=3, sigma_2=1):
################################################################################
## Finish this function so that it returns a bimodal prior, comprised of the
# sum of two Gaussians
#
# Comment out the line below to test out your solution
raise NotImplementedError("Please implement the bimodal prior")
################################################################################
prior = ...
return prior
def posterior_mode(x, posterior):
################################################################################
## Finish this function so that it returns the location of the mode
#
# Comment out the line below to test out your solution
raise NotImplementedError("Please implement the posterior mode")
################################################################################
mode = ...
return mode
def multimodal_simulation(x, mus_visual, sigma_visual=1):
"""
Simulate an experiment where bimodal prior is held constant while
a Gaussian visual likelihood is shifted across locations.
Args:
x: array of points at which prior/likelihood/posterior are evaluated
mus_visual: array of means for the Gaussian likelihood
sigma_visual: scalar standard deviation for the Gaussian likelihood
Returns:
posterior_modes: array containing the posterior mode for each mean in mus_visual
"""
prior = bimodal_prior(x, -3, 1, 3, 1)
posterior_modes = []
for mu in mus_visual:
likelihood = my_gaussian(x, mu, 3)
posterior = compute_posterior_pointwise(prior, likelihood)
p_mode = posterior_mode(x, posterior)
posterior_modes.append(p_mode)
return posterior_modes
x = np.arange(-10, 10, 0.1)
mus = np.arange(-8, 8, 0.05)
# Uncomment the lines below to visualize your results
# posterior_modes = multimodal_simulation(x, mus, 1)
# multimodal_plot(x,
# bimodal_prior(x, -3, 1, 3, 1),
# my_gaussian(x, 1, 1),
# mus, posterior_modes)
###Output
_____no_output_____
###Markdown
Neuromatch Academy: Week 2, Day 1, Tutorial 1 Bayes rule with Gaussians__Content creators:__ Vincent Valton, Konrad Kording, with help from Matt Krause__Content reviewers:__ Matt Krause, Jesse Livezey, Karolina Stosio, Saeed Salehi, Michael Waskom Tutorial ObjectivesThis is the first in a series of three main tutorials (+ one bonus tutorial) on Bayesian statistics. In these tutorials, we will develop a Bayesian model for localizing sounds based on audio and visual cues. This model will combine **prior** information about where sounds generally originate with sensory information about the **likelihood** that a specific sound came from a particular location. As we will see in subsequent lessons, the resulting **posterior distribution** not only allows us to make optimal decision about the sound's origin, but also lets us quantify how uncertain that decision is. Bayesian techniques are therefore useful **normative models**: the behavior of human or animal subjects can be compared against these models to determine how efficiently they make use of information. This notebook will introduce two fundamental building blocks for Bayesian statistics: the Gaussian distribution and the Bayes Theorem. You will: 1. Implement a Gaussian distribution2. Use Bayes' Theorem to find the posterior from a Gaussian-distributed prior and likelihood. 3. Change the likelihood mean and variance and observe how posterior changes.4. Advanced (*optional*): Observe what happens if the prior is a mixture of two gaussians?
###Code
#@title Video 1: Introduction to Bayesian Statistics
from IPython.display import YouTubeVideo
video = YouTubeVideo(id='K4sSKZtk-Sc', width=854, height=480, fs=1)
print("Video available at https://youtube.com/watch?v=" + video.id)
video
###Output
Video available at https://youtube.com/watch?v=K4sSKZtk-Sc
###Markdown
Setup Please execute the cells below to initialize the notebook environment.
###Code
import numpy as np
import matplotlib.pyplot as plt
#@title Figure Settings
import ipywidgets as widgets
plt.style.use("https://raw.githubusercontent.com/NeuromatchAcademy/course-content/master/nma.mplstyle")
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
#@title Helper functions
def my_plot_single(x, px):
"""
Plots normalized Gaussian distribution
Args:
x (numpy array of floats): points at which the likelihood has been evaluated
px (numpy array of floats): normalized probabilities for prior evaluated at each `x`
Returns:
Nothing.
"""
if px is None:
px = np.zeros_like(x)
fig, ax = plt.subplots()
ax.plot(x, px, '-', color='xkcd:green', LineWidth=2, label='Prior')
ax.legend()
ax.set_ylabel('Probability')
ax.set_xlabel('Orientation (Degrees)')
def posterior_plot(x, likelihood=None, prior=None, posterior_pointwise=None, ax=None):
"""
Plots normalized Gaussian distributions and posterior
Args:
x (numpy array of floats): points at which the likelihood has been evaluated
auditory (numpy array of floats): normalized probabilities for auditory likelihood evaluated at each `x`
visual (numpy array of floats): normalized probabilities for visual likelihood evaluated at each `x`
posterior (numpy array of floats): normalized probabilities for the posterior evaluated at each `x`
ax: Axis in which to plot. If None, create new axis.
Returns:
Nothing.
"""
if likelihood is None:
likelihood = np.zeros_like(x)
if prior is None:
prior = np.zeros_like(x)
if posterior_pointwise is None:
posterior_pointwise = np.zeros_like(x)
if ax is None:
fig, ax = plt.subplots()
ax.plot(x, likelihood, '-r', LineWidth=2, label='Auditory')
ax.plot(x, prior, '-b', LineWidth=2, label='Visual')
ax.plot(x, posterior_pointwise, '-g', LineWidth=2, label='Posterior')
ax.legend()
ax.set_ylabel('Probability')
ax.set_xlabel('Orientation (Degrees)')
return ax
def plot_visual(mu_visuals, mu_posteriors, max_posteriors):
"""
Plots the comparison of computing the mean of the posterior analytically and
the max of the posterior empirically via multiplication.
Args:
mu_visuals (numpy array of floats): means of the visual likelihood
mu_posteriors (numpy array of floats): means of the posterior, calculated analytically
max_posteriors (numpy array of floats): max of the posteriors, calculated via maxing the max_posteriors.
posterior (numpy array of floats): normalized probabilities for the posterior evaluated at each `x`
Returns:
Nothing.
"""
fig_w, fig_h = plt.rcParams.get('figure.figsize')
fig, ax = plt.subplots(nrows=2, ncols=1, figsize=(fig_w, 2 * fig_h))
ax[0].plot(mu_visuals, max_posteriors, '-g', label='mean')
ax[0].set_xlabel('Visual stimulus position')
ax[0].set_ylabel('Multiplied posterior mean')
ax[0].set_title('Sample output')
ax[1].plot(mu_visuals, mu_posteriors, '--', color='xkcd:gray', label='argmax')
ax[1].set_xlabel('Visual stimulus position')
ax[1].set_ylabel('Analytical posterior mean')
fig.tight_layout()
ax[1].set_title('Hurray for math!')
def multimodal_plot(x, example_prior, example_likelihood,
mu_visuals, posterior_modes):
"""Helper function for plotting Section 4 results"""
fig_w, fig_h = plt.rcParams.get('figure.figsize')
fig, ax = plt.subplots(nrows=2, ncols=1, figsize=(fig_w, 2*fig_h), sharex=True)
# Plot the last instance that we tried.
posterior_plot(x,
example_prior,
example_likelihood,
compute_posterior_pointwise(example_prior, example_likelihood),
ax=ax[0]
)
ax[0].set_title('Example combination')
ax[1].plot(mu_visuals, posterior_modes, '-g', label='argmax')
ax[1].set_xlabel('Visual stimulus position\n(Mean of blue dist. above)')
ax[1].set_ylabel('Posterior mode\n(Peak of green dist. above)')
fig.tight_layout()
###Output
_____no_output_____
###Markdown
Section 1: The Gaussian DistributionBayesian analysis operates on probability distributions. Although these can take many forms, the Gaussian distribution is a very common choice. Because of the central limit theorem, many quantities are Gaussian-distributed. Gaussians also have some mathematical properties that permit simple closed-form solutions to several important problems. In this exercise, you will implement a Gaussian by filling in the missing portion of `my_gaussian` below. Gaussians have two parameters. The **mean** $\mu$, which sets the location of its center. Its "scale" or spread is controlled by its **standard deviation** $\sigma$ or its square, the **variance** $\sigma^2$. (Be careful not to use one when the other is required). The equation for a Gaussian is:$$\mathcal{N}(\mu,\sigma^2) = \frac{1}{\sqrt{2\pi\sigma^2}}\exp\left(\frac{-(x-\mu)^2}{2\sigma^2}\right)$$Also, don't forget that this is a probability distribution and should therefore sum to one. While this happens "automatically" when integrated from $-\infty$ to $\infty$, your version will only be computed over a finite number of points. You therefore need to explicitly normalize it yourself. Test out your implementation with a $\mu = -1$ and $\sigma = 1$. After you have it working, play with the parameters to develop an intuition for how changing $\mu$ and $\sigma$ alter the shape of the Gaussian. This is important, because subsequent exercises will be built out of Gaussians. Exercise 1: Implement a Gaussian
###Code
def my_gaussian(x_points, mu, sigma):
"""
Returns normalized Gaussian estimated at points `x_points`, with parameters:
mean `mu` and std `sigma`
Args:
x_points (numpy array of floats): points at which the gaussian is
evaluated
mu (scalar): mean of the Gaussian
sigma (scalar): std of the gaussian
Returns:
(numpy array of floats) : normalized Gaussian evaluated at `x`
"""
###################################################################
## Add code to calcualte the gaussian px as a function of mu and sigma,
## for every x in x_points
## Function Hints: exp -> np.exp()
## power -> z**2
## remove the raise below to test your function
raise NotImplementedError("You need to implement the Gaussian function!")
###################################################################
px = ...
return px
x = np.arange(-8, 9, 0.1)
# Uncomment to plot the results
# px = my_gaussian(x, -1, 1)
# my_plot_single(x, px)
###Output
_____no_output_____
###Markdown
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W2D1_BayesianStatistics/solutions/W2D1_Tutorial1_Solution_aeeeaedf.py)*Example output:* Section 2. Bayes' Theorem and the Posterior
###Code
#@title Video 2: Bayes' theorem
from IPython.display import YouTubeVideo
video = YouTubeVideo(id='ewQPHQMcdBs', width=854, height=480, fs=1)
print("Video available at https://youtube.com/watch?v=" + video.id)
video
###Output
Video available at https://youtube.com/watch?v=ewQPHQMcdBs
###Markdown
Bayes' rule tells us how to combine two sources of information: the prior (e.g., a noisy representation of our expectations about where the stimulus might come from) and the likelihood (e.g., a noisy representation of the stimulus position on a given trial), to obtain a posterior distribution taking into account both pieces of information. Bayes' rule states:\begin{eqnarray}\text{Posterior} = \frac{ \text{Likelihood} \times \text{Prior}}{ \text{Normalization constant}}\end{eqnarray}When both the prior and likelihood are Gaussians, this translates into the following form:$$\begin{array}{rcl}\text{Likelihood} &=& \mathcal{N}(\mu_{likelihood},\sigma_{likelihood}^2) \\\text{Prior} &=& \mathcal{N}(\mu_{prior},\sigma_{prior}^2) \\\text{Posterior} &\propto& \mathcal{N}(\mu_{likelihood},\sigma_{likelihood}^2) \times \mathcal{N}(\mu_{prior},\sigma_{prior}^2) \\&&= \mathcal{N}\left( \frac{\sigma^2_{likelihood}\mu_{prior}+\sigma^2_{prior}\mu_{likelihood}}{\sigma^2_{likelihood}+\sigma^2_{prior}}, \frac{\sigma^2_{likelihood}\sigma^2_{prior}}{\sigma^2_{likelihood}+\sigma^2_{prior}} \right) \end{array}$$In these equations, $\mathcal{N}(\mu,\sigma^2)$ denotes a Gaussian distribution with parameters $\mu$ and $\sigma^2$:$$\mathcal{N}(\mu, \sigma) = \frac{1}{\sqrt{2 \pi \sigma^2}} \; \exp \bigg( \frac{-(x-\mu)^2}{2\sigma^2} \bigg)$$In Exercise 2A, we will use the first form of the posterior, where the two distributions are combined via pointwise multiplication. Although this method requires more computation, it works for any type of probability distribution. In Exercise 2B, we will see that the closed-form solution shown on the line below produces the same result. Exercise 2A: Finding the posterior computationallyImagine an experiment where participants estimate the location of a noise-emitting object. To estimate its position, the participants can use two sources of information: 1. new noisy auditory information (the likelihood) 2. prior visual expectations of where the stimulus is likely to come from (visual prior). The auditory and visual information are both noisy, so participants will combine these sources of information to better estimate the position of the object.We will use Gaussian distributions to represent the auditory likelihood (in red), and a Gaussian visual prior (expectations - in blue). Using Bayes rule, you will combine them into a posterior distribution that summarizes the probability that the object is in each location. We have provided you with a ready-to-use plotting function, and a code skeleton.* Use `my_gaussian`, the answer to exercise 1, to generate an auditory likelihood with parameters $\mu$ = 3 and $\sigma$ = 1.5* Generate a visual prior with parameters $\mu$ = -1 and $\sigma$ = 1.5* Calculate the posterior using pointwise multiplication of the likelihood and prior. Don't forget to normalize so the posterior adds up to 1. * Plot the likelihood, prior and posterior using the predefined function `posterior_plot`
###Code
def compute_posterior_pointwise(prior, likelihood):
##############################################################################
# Write code to compute the posterior from the prior and likelihood via
# pointwise multiplication. (You may assume both are defined over the same x-axis)
#
# Comment out the line below to test your solution
raise NotImplementedError("Finish the simulation code first")
##############################################################################
posterior = ...
return posterior
def localization_simulation(mu_auditory=3.0, sigma_auditory=1.5,
mu_visual=-1.0, sigma_visual=1.5):
##############################################################################
## Using the x variable below,
## create a gaussian called 'auditory' with mean 3, and std 1.5
## create a gaussian called 'visual' with mean -1, and std 1.5
#
#
## Comment out the line below to test your solution
raise NotImplementedError("Finish the simulation code first")
###############################################################################
x = np.arange(-8, 9, 0.1)
auditory = ...
visual = ...
posterior = compute_posterior_pointwise(auditory, visual)
return x, auditory, visual, posterior
# Uncomment the lines below to plot the results
# x, auditory, visual, posterior_pointwise = localization_simulation()
# posterior_plot(x, auditory, visual, posterior_pointwise)
###Output
_____no_output_____
###Markdown
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W2D1_BayesianStatistics/solutions/W2D1_Tutorial1_Solution_39d14917.py)*Example output:* Interactive Demo: What affects the posterior?Now that we can compute the posterior of two Gaussians with *Bayes rule*, let's vary the parameters of those Gaussians to see how changing the prior and likelihood affect the posterior. **Hit the Play button or Ctrl+Enter in the cell below** and play with the sliders to get an intuition for how the means and standard deviations of prior and likelihood influence the posterior.When does the prior have the strongest influence over the posterior? When is it the weakest?
###Code
#@title
#@markdown Make sure you execute this cell to enable the widget!
x = np.arange(-10, 11, 0.1)
import ipywidgets as widgets
def refresh(mu_auditory=3, sigma_auditory=1.5, mu_visual=-1, sigma_visual=1.5):
auditory = my_gaussian(x, mu_auditory, sigma_auditory)
visual = my_gaussian(x, mu_visual, sigma_visual)
posterior_pointwise = visual * auditory
posterior_pointwise /= posterior_pointwise.sum()
w_auditory = (sigma_visual** 2) / (sigma_auditory**2 + sigma_visual**2)
theoretical_prediction = mu_auditory * w_auditory + mu_visual * (1 - w_auditory)
ax = posterior_plot(x, auditory, visual, posterior_pointwise)
ax.plot([theoretical_prediction, theoretical_prediction],
[0, posterior_pointwise.max() * 1.2], '-.', color='xkcd:medium gray')
ax.set_title(f"Gray line shows analytical mean of posterior: {theoretical_prediction:0.2f}")
plt.show()
style = {'description_width': 'initial'}
_ = widgets.interact(refresh,
mu_auditory=widgets.FloatSlider(value=2, min=-10, max=10, step=0.5, description="mu_auditory:", style=style),
sigma_auditory=widgets.FloatSlider(value=0.5, min=0.5, max=10, step=0.5, description="sigma_auditory:", style=style),
mu_visual=widgets.FloatSlider(value=-2, min=-10, max=10, step=0.5, description="mu_visual:", style=style),
sigma_visual=widgets.FloatSlider(value=0.5, min=0.5, max=10, step=0.5, description="sigma_visual:", style=style)
)
###Output
/opt/hostedtoolcache/Python/3.7.8/x64/lib/python3.7/site-packages/ipykernel_launcher.py:49: MatplotlibDeprecationWarning: Case-insensitive properties were deprecated in 3.3 and support will be removed two minor releases later
/opt/hostedtoolcache/Python/3.7.8/x64/lib/python3.7/site-packages/ipykernel_launcher.py:50: MatplotlibDeprecationWarning: Case-insensitive properties were deprecated in 3.3 and support will be removed two minor releases later
/opt/hostedtoolcache/Python/3.7.8/x64/lib/python3.7/site-packages/ipykernel_launcher.py:51: MatplotlibDeprecationWarning: Case-insensitive properties were deprecated in 3.3 and support will be removed two minor releases later
###Markdown
Video 3: Multiplying Gaussians
###Code
#@title
from IPython.display import YouTubeVideo
video = YouTubeVideo(id='AbXorOLBrws', width=854, height=480, fs=1)
print("Video available at https://youtube.com/watch?v=" + video.id)
video
###Output
Video available at https://youtube.com/watch?v=AbXorOLBrws
###Markdown
Exercise 2B: Finding the posterior analytically[If you are running short on time, feel free to skip the coding exercise below].As you may have noticed from the interactive demo, the product of two Gaussian distributions, like our prior and likelihood, remains a Gaussian, regardless of the parameters. We can directly compute the parameters of that Gaussian from the means and variances of the prior and likelihood. For example, the posterior mean is given by:$$ \mu_{posterior} = \frac{\mu_{auditory} \cdot \frac{1}{\sigma_{auditory}^2} + \mu_{visual} \cdot \frac{1}{\sigma_{visual}^2}}{1/\sigma_{auditory}^2 + 1/\sigma_{visual}^2} $$This formula is a special case for two Gaussians, but is a very useful one because:* The posterior has the same form (here, a normal distribution) as the prior, and* There is simple, closed-form expression for its parameters.When these properties hold, we call them **conjugate distributions** or **conjugate priors** (for a particular likelihood). Working with conjugate distributions is very convenient; otherwise, it is often necessary to use computationally-intensive numerical methods to combine the prior and likelihood. In this exercise, we ask you to verify that property. To do so, we will hold our auditory likelihood constant as an $\mathcal{N}(3, 1.5)$ distribution, while considering visual priors with different means ranging from $\mu=-10$ to $\mu=10$. For each prior,* Compute the posterior distribution using the function you wrote in Exercise 2A. Next, find its mean. The mean of a probability distribution is $\int_x p(x) dx$ or $\sum_x x\cdot p(x)$. * Compute the analytical posterior mean from auditory and visual using the equation above.* Use the provided plotting code to plot both estimates of the mean. Are the estimates of the posterior mean the same in both cases? Using these results, try to predict the posterior mean for the combination of a $\mathcal{N}(-4,4)$ prior and and $\mathcal{N}(4, 2)$ likelihood. Use the widget above to check your prediction. You can enter values directly by clicking on the numbers to the right of each slider; $\sqrt{2} \approx 1.41$.
###Code
def compare_computational_analytical_means():
x = np.arange(-10, 11, 0.1)
# Fixed auditory likelihood
mu_auditory = 3
sigma_auditory = 1.5
likelihood = my_gaussian(x, mu_auditory, sigma_auditory)
# Varying visual prior
mu_visuals = np.linspace(-10, 10)
sigma_visual = 1.5
# Accumulate results here
mus_by_integration = []
mus_analytical = []
for mu_visual in mu_visuals:
prior = my_gaussian(x, mu_visual, sigma_visual)
posterior = compute_posterior_pointwise(prior, likelihood)
############################################################################
## Add code that will find the posterior mean via numerical integration
#
############################################################################
mu_integrated = ...
############################################################################
## Add more code below that will calculate the posterior mean analytically
#
# Comment out the line below to test your solution
raise NotImplementedError("Please add code to find the mean both ways first")
############################################################################
mu_analytical = ...
mus_by_integration.append(mu_integrated)
mus_analytical.append(mu_analytical)
return mu_visuals, mus_by_integration, mus_analytical
# Uncomment the lines below to visualize your results
# mu_visuals, mu_computational, mu_analytical = compare_computational_analytical_means()
# plot_visual(mu_visuals, mu_computational, mu_analytical)
###Output
_____no_output_____
###Markdown
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W2D1_BayesianStatistics/solutions/W2D1_Tutorial1_Solution_8e15215d.py)*Example output:* Section 3: ConclusionThis tutorial introduced the Gaussian distribution and used Bayes' Theorem to combine Gaussians representing priors and likelihoods. In the next tutorial, we will use these concepts to probe how subjects integrate sensory information.
###Code
#@title Video 4: Conclusion
from IPython.display import YouTubeVideo
video = YouTubeVideo(id='YC8GylOAAHs', width=854, height=480, fs=1)
print("Video available at https://youtube.com/watch?v=" + video.id)
video
###Output
Video available at https://youtube.com/watch?v=YC8GylOAAHs
###Markdown
Bonus Section: Multimodal Priors**Only do this if the first half-hour has not yet passed.**The preceeding exercises used a Gaussian prior, implying that participants expected the stimulus to come from a single location, though they might not know precisely where. However, suppose the subjects actually thought that sound might come from one of two distinct locations. Perhaps they can see two speakers (and know that speakers often emit noise). We could model this using a Gaussian prior with a large $\sigma$ that covers both locations, but that would also make every point in between seem likely too.A better approach is to adjust the form of the prior so that it better matches the participants' experiences/expectations. In this optional exercise, we will build a bimodal (2-peaked) prior out of Gaussians and examine the resulting posterior and its peaks. Exercise 3: Implement and test a multimodal prior* Complete the `bimodal_prior` function below to create a bimodal prior, comprised of the sum of two Gaussians with means $\mu = -3$ and $\mu = 3$. Use $\sigma=1$ for both Gaussians. Be sure to normalize the result so it is a proper probability distribution. * In Exercise 2, we used the mean location to summarize the posterior distribution. This is not always the best choice, especially for multimodal distributions. What is the mean of our new prior? Is it a particularly likely location for the stimulus? Instead, we will use the posterior **mode** to summarize the distribution. The mode is the *location* of the most probable part of the distribution. Complete `posterior_mode` below, to find it. (Hint: `np.argmax` returns the *index* of the largest element in an array).* Run the provided simulation and plotting code. Observe what happens to the posterior as the likelihood gets closer to the different peaks of the prior.* Notice what happens to the posterior when the likelihood is exactly in between the two modes of the prior (i.e., $\mu_{Likelihood} = 0$)
###Code
def bimodal_prior(x, mu_1=-3, sigma_1=1, mu_2=3, sigma_2=1):
################################################################################
## Finish this function so that it returns a bimodal prior, comprised of the
# sum of two Gaussians
#
# Comment out the line below to test out your solution
raise NotImplementedError("Please implement the bimodal prior")
################################################################################
prior = ...
return prior
def posterior_mode(x, posterior):
################################################################################
## Finish this function so that it returns the location of the mode
#
# Comment out the line below to test out your solution
raise NotImplementedError("Please implement the bimodal prior")
################################################################################
mode = ...
return mode
def multimodal_simulation(x, mus_visual, sigma_visual=1):
"""
Simulate an experiment where bimodal prior is held constant while
a Gaussian visual likelihood is shifted across locations.
Args:
x: array of points at which prior/likelihood/posterior are evaluated
mus_visual: array of means for the Gaussian likelihood
sigma_visual: scalar standard deviation for the Gaussian likelihood
Returns:
posterior_modes: array containing the posterior mode for each mean in mus_visual
"""
prior = bimodal_prior(x, -3, 1, 3, 1)
posterior_modes = []
for mu in mus_visual:
likelihood = my_gaussian(x, mu, 3)
posterior = compute_posterior_pointwise(prior, likelihood)
p_mode = posterior_mode(x, posterior)
posterior_modes.append(p_mode)
return posterior_modes
x = np.arange(-10, 10, 0.1)
mus = np.arange(-8, 8, 0.05)
# Uncomment the lines below to visualize your results
# posterior_modes = multimodal_simulation(x, mus, 1)
# multimodal_plot(x,
# bimodal_prior(x, -3, 1, 3, 1),
# my_gaussian(x, 1, 1),
# mus, posterior_modes)
###Output
_____no_output_____
###Markdown
Neuromatch Academy: Week 2, Day 1, Tutorial 1 Bayes rule with Gaussians__Content creators:__ Vincent Valton, Konrad Kording, with help from Matt Krause__Content reviewers:__ Matt Krause, Jesse Livezey, Karolina Stosio, Saeed Salehi, Michael Waskom Tutorial ObjectivesThis is the first in a series of three main tutorials (+ one bonus tutorial) on Bayesian statistics. In these tutorials, we will develop a Bayesian model for localizing sounds based on audio and visual cues. This model will combine **prior** information about where sounds generally originate with sensory information about the **likelihood** that a specific sound came from a particular location. As we will see in subsequent lessons, the resulting **posterior distribution** not only allows us to make optimal decision about the sound's origin, but also lets us quantify how uncertain that decision is. Bayesian techniques are therefore useful **normative models**: the behavior of human or animal subjects can be compared against these models to determine how efficiently they make use of information. This notebook will introduce two fundamental building blocks for Bayesian statistics: the Gaussian distribution and the Bayes Theorem. You will: 1. Implement a Gaussian distribution2. Use Bayes' Theorem to find the posterior from a Gaussian-distributed prior and likelihood. 3. Change the likelihood mean and variance and observe how posterior changes.4. Advanced (*optional*): Observe what happens if the prior is a mixture of two gaussians?
###Code
#@title Video 1: Introduction to Bayesian Statistics
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = "https://player.bilibili.com/player.html?bvid={0}&page={1}".format(id, page)
super(BiliVideo, self).__init__(src, width, height, **kwargs)
video = BiliVideo(id='BV1pZ4y1u7PD', width=854, height=480, fs=1)
print("Video available at https://www.bilibili.com/video/{0}".format(video.id))
video
###Output
Video available at https://www.bilibili.com/video/BV1pZ4y1u7PD
###Markdown
Setup Please execute the cells below to initialize the notebook environment.
###Code
import numpy as np
import matplotlib.pyplot as plt
#@title Figure Settings
import ipywidgets as widgets
plt.style.use("https://raw.githubusercontent.com/NeuromatchAcademy/course-content/master/nma.mplstyle")
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
#@title Helper functions
def my_plot_single(x, px):
"""
Plots normalized Gaussian distribution
Args:
x (numpy array of floats): points at which the likelihood has been evaluated
px (numpy array of floats): normalized probabilities for prior evaluated at each `x`
Returns:
Nothing.
"""
if px is None:
px = np.zeros_like(x)
fig, ax = plt.subplots()
ax.plot(x, px, '-', color='xkcd:green', LineWidth=2, label='Prior')
ax.legend()
ax.set_ylabel('Probability')
ax.set_xlabel('Orientation (Degrees)')
def posterior_plot(x, likelihood=None, prior=None, posterior_pointwise=None, ax=None):
"""
Plots normalized Gaussian distributions and posterior
Args:
x (numpy array of floats): points at which the likelihood has been evaluated
auditory (numpy array of floats): normalized probabilities for auditory likelihood evaluated at each `x`
visual (numpy array of floats): normalized probabilities for visual likelihood evaluated at each `x`
posterior (numpy array of floats): normalized probabilities for the posterior evaluated at each `x`
ax: Axis in which to plot. If None, create new axis.
Returns:
Nothing.
"""
if likelihood is None:
likelihood = np.zeros_like(x)
if prior is None:
prior = np.zeros_like(x)
if posterior_pointwise is None:
posterior_pointwise = np.zeros_like(x)
if ax is None:
fig, ax = plt.subplots()
ax.plot(x, likelihood, '-r', LineWidth=2, label='Auditory')
ax.plot(x, prior, '-b', LineWidth=2, label='Visual')
ax.plot(x, posterior_pointwise, '-g', LineWidth=2, label='Posterior')
ax.legend()
ax.set_ylabel('Probability')
ax.set_xlabel('Orientation (Degrees)')
return ax
def plot_visual(mu_visuals, mu_posteriors, max_posteriors):
"""
Plots the comparison of computing the mean of the posterior analytically and
the max of the posterior empirically via multiplication.
Args:
mu_visuals (numpy array of floats): means of the visual likelihood
mu_posteriors (numpy array of floats): means of the posterior, calculated analytically
max_posteriors (numpy array of floats): max of the posteriors, calculated via maxing the max_posteriors.
posterior (numpy array of floats): normalized probabilities for the posterior evaluated at each `x`
Returns:
Nothing.
"""
fig_w, fig_h = plt.rcParams.get('figure.figsize')
fig, ax = plt.subplots(nrows=2, ncols=1, figsize=(fig_w, 2 * fig_h))
ax[0].plot(mu_visuals, max_posteriors, '-g', label='mean')
ax[0].set_xlabel('Visual stimulus position')
ax[0].set_ylabel('Multiplied posterior mean')
ax[0].set_title('Sample output')
ax[1].plot(mu_visuals, mu_posteriors, '--', color='xkcd:gray', label='argmax')
ax[1].set_xlabel('Visual stimulus position')
ax[1].set_ylabel('Analytical posterior mean')
fig.tight_layout()
ax[1].set_title('Hurray for math!')
def multimodal_plot(x, example_prior, example_likelihood,
mu_visuals, posterior_modes):
"""Helper function for plotting Section 4 results"""
fig_w, fig_h = plt.rcParams.get('figure.figsize')
fig, ax = plt.subplots(nrows=2, ncols=1, figsize=(fig_w, 2*fig_h), sharex=True)
# Plot the last instance that we tried.
posterior_plot(x,
example_prior,
example_likelihood,
compute_posterior_pointwise(example_prior, example_likelihood),
ax=ax[0]
)
ax[0].set_title('Example combination')
ax[1].plot(mu_visuals, posterior_modes, '-g', label='argmax')
ax[1].set_xlabel('Visual stimulus position\n(Mean of blue dist. above)')
ax[1].set_ylabel('Posterior mode\n(Peak of green dist. above)')
fig.tight_layout()
###Output
_____no_output_____
###Markdown
Section 1: The Gaussian DistributionBayesian analysis operates on probability distributions. Although these can take many forms, the Gaussian distribution is a very common choice. Because of the central limit theorem, many quantities are Gaussian-distributed. Gaussians also have some mathematical properties that permit simple closed-form solutions to several important problems. In this exercise, you will implement a Gaussian by filling in the missing portion of `my_gaussian` below. Gaussians have two parameters. The **mean** $\mu$, which sets the location of its center. Its "scale" or spread is controlled by its **standard deviation** $\sigma$ or its square, the **variance** $\sigma^2$. (Be careful not to use one when the other is required). The equation for a Gaussian is:$$\mathcal{N}(\mu,\sigma^2) = \frac{1}{\sqrt{2\pi\sigma^2}}\exp\left(\frac{-(x-\mu)^2}{2\sigma^2}\right)$$Also, don't forget that this is a probability distribution and should therefore sum to one. While this happens "automatically" when integrated from $-\infty$ to $\infty$, your version will only be computed over a finite number of points. You therefore need to explicitly normalize it yourself. Test out your implementation with a $\mu = -1$ and $\sigma = 1$. After you have it working, play with the parameters to develop an intuition for how changing $\mu$ and $\sigma$ alter the shape of the Gaussian. This is important, because subsequent exercises will be built out of Gaussians. Exercise 1: Implement a Gaussian
###Code
def my_gaussian(x_points, mu, sigma):
"""
Returns normalized Gaussian estimated at points `x_points`, with parameters:
mean `mu` and std `sigma`
Args:
x_points (numpy array of floats): points at which the gaussian is
evaluated
mu (scalar): mean of the Gaussian
sigma (scalar): std of the gaussian
Returns:
(numpy array of floats) : normalized Gaussian evaluated at `x`
"""
###################################################################
## Add code to calcualte the gaussian px as a function of mu and sigma,
## for every x in x_points
## Function Hints: exp -> np.exp()
## power -> z**2
## remove the raise below to test your function
raise NotImplementedError("You need to implement the Gaussian function!")
###################################################################
px = ...
return px
x = np.arange(-8, 9, 0.1)
# Uncomment to plot the results
# px = my_gaussian(x, -1, 1)
# my_plot_single(x, px)
###Output
_____no_output_____
###Markdown
[*Click for solution*](https://github.com/erlichlab/course-content/tree/master//tutorials/W2D1_BayesianStatistics/solutions/W2D1_Tutorial1_Solution_aeeeaedf.py)*Example output:* Section 2. Bayes' Theorem and the Posterior
###Code
#@title Video 2: Bayes' theorem
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = "https://player.bilibili.com/player.html?bvid={0}&page={1}".format(id, page)
super(BiliVideo, self).__init__(src, width, height, **kwargs)
video = BiliVideo(id='BV1Hi4y1V7UN', width=854, height=480, fs=1)
print("Video available at https://www.bilibili.com/video/{0}".format(video.id))
video
###Output
Video available at https://www.bilibili.com/video/BV1Hi4y1V7UN
###Markdown
Bayes' rule tells us how to combine two sources of information: the prior (e.g., a noisy representation of our expectations about where the stimulus might come from) and the likelihood (e.g., a noisy representation of the stimulus position on a given trial), to obtain a posterior distribution taking into account both pieces of information. Bayes' rule states:\begin{eqnarray}\text{Posterior} = \frac{ \text{Likelihood} \times \text{Prior}}{ \text{Normalization constant}}\end{eqnarray}When both the prior and likelihood are Gaussians, this translates into the following form:$$\begin{array}{rcl}\text{Likelihood} &=& \mathcal{N}(\mu_{likelihood},\sigma_{likelihood}^2) \\\text{Prior} &=& \mathcal{N}(\mu_{prior},\sigma_{prior}^2) \\\text{Posterior} &\propto& \mathcal{N}(\mu_{likelihood},\sigma_{likelihood}^2) \times \mathcal{N}(\mu_{prior},\sigma_{prior}^2) \\&&= \mathcal{N}\left( \frac{\sigma^2_{likelihood}\mu_{prior}+\sigma^2_{prior}\mu_{likelihood}}{\sigma^2_{likelihood}+\sigma^2_{prior}}, \frac{\sigma^2_{likelihood}\sigma^2_{prior}}{\sigma^2_{likelihood}+\sigma^2_{prior}} \right) \end{array}$$In these equations, $\mathcal{N}(\mu,\sigma^2)$ denotes a Gaussian distribution with parameters $\mu$ and $\sigma^2$:$$\mathcal{N}(\mu, \sigma) = \frac{1}{\sqrt{2 \pi \sigma^2}} \; \exp \bigg( \frac{-(x-\mu)^2}{2\sigma^2} \bigg)$$In Exercise 2A, we will use the first form of the posterior, where the two distributions are combined via pointwise multiplication. Although this method requires more computation, it works for any type of probability distribution. In Exercise 2B, we will see that the closed-form solution shown on the line below produces the same result. Exercise 2A: Finding the posterior computationallyImagine an experiment where participants estimate the location of a noise-emitting object. To estimate its position, the participants can use two sources of information: 1. new noisy auditory information (the likelihood) 2. prior visual expectations of where the stimulus is likely to come from (visual prior). The auditory and visual information are both noisy, so participants will combine these sources of information to better estimate the position of the object.We will use Gaussian distributions to represent the auditory likelihood (in red), and a Gaussian visual prior (expectations - in blue). Using Bayes rule, you will combine them into a posterior distribution that summarizes the probability that the object is in each location. We have provided you with a ready-to-use plotting function, and a code skeleton.* Use `my_gaussian`, the answer to exercise 1, to generate an auditory likelihood with parameters $\mu$ = 3 and $\sigma$ = 1.5* Generate a visual prior with parameters $\mu$ = -1 and $\sigma$ = 1.5* Calculate the posterior using pointwise multiplication of the likelihood and prior. Don't forget to normalize so the posterior adds up to 1. * Plot the likelihood, prior and posterior using the predefined function `posterior_plot`
###Code
def compute_posterior_pointwise(prior, likelihood):
##############################################################################
# Write code to compute the posterior from the prior and likelihood via
# pointwise multiplication. (You may assume both are defined over the same x-axis)
#
# Comment out the line below to test your solution
raise NotImplementedError("Finish the simulation code first")
##############################################################################
posterior = ...
return posterior
def localization_simulation(mu_auditory=3.0, sigma_auditory=1.5,
mu_visual=-1.0, sigma_visual=1.5):
##############################################################################
## Using the x variable below,
## create a gaussian called 'auditory' with mean 3, and std 1.5
## create a gaussian called 'visual' with mean -1, and std 1.5
#
#
## Comment out the line below to test your solution
raise NotImplementedError("Finish the simulation code first")
###############################################################################
x = np.arange(-8, 9, 0.1)
auditory = ...
visual = ...
posterior = compute_posterior_pointwise(auditory, visual)
return x, auditory, visual, posterior
# Uncomment the lines below to plot the results
# x, auditory, visual, posterior_pointwise = localization_simulation()
# posterior_plot(x, auditory, visual, posterior_pointwise)
###Output
_____no_output_____
###Markdown
[*Click for solution*](https://github.com/erlichlab/course-content/tree/master//tutorials/W2D1_BayesianStatistics/solutions/W2D1_Tutorial1_Solution_39d14917.py)*Example output:* Interactive Demo: What affects the posterior?Now that we can compute the posterior of two Gaussians with *Bayes rule*, let's vary the parameters of those Gaussians to see how changing the prior and likelihood affect the posterior. **Hit the Play button or Ctrl+Enter in the cell below** and play with the sliders to get an intuition for how the means and standard deviations of prior and likelihood influence the posterior.When does the prior have the strongest influence over the posterior? When is it the weakest?
###Code
#@title
#@markdown Make sure you execute this cell to enable the widget!
x = np.arange(-10, 11, 0.1)
import ipywidgets as widgets
def refresh(mu_auditory=3, sigma_auditory=1.5, mu_visual=-1, sigma_visual=1.5):
auditory = my_gaussian(x, mu_auditory, sigma_auditory)
visual = my_gaussian(x, mu_visual, sigma_visual)
posterior_pointwise = visual * auditory
posterior_pointwise /= posterior_pointwise.sum()
w_auditory = (sigma_visual** 2) / (sigma_auditory**2 + sigma_visual**2)
theoretical_prediction = mu_auditory * w_auditory + mu_visual * (1 - w_auditory)
ax = posterior_plot(x, auditory, visual, posterior_pointwise)
ax.plot([theoretical_prediction, theoretical_prediction],
[0, posterior_pointwise.max() * 1.2], '-.', color='xkcd:medium gray')
ax.set_title(f"Gray line shows analytical mean of posterior: {theoretical_prediction:0.2f}")
plt.show()
style = {'description_width': 'initial'}
_ = widgets.interact(refresh,
mu_auditory=widgets.FloatSlider(value=2, min=-10, max=10, step=0.5, description="mu_auditory:", style=style),
sigma_auditory=widgets.FloatSlider(value=0.5, min=0.5, max=10, step=0.5, description="sigma_auditory:", style=style),
mu_visual=widgets.FloatSlider(value=-2, min=-10, max=10, step=0.5, description="mu_visual:", style=style),
sigma_visual=widgets.FloatSlider(value=0.5, min=0.5, max=10, step=0.5, description="sigma_visual:", style=style)
)
###Output
/opt/hostedtoolcache/Python/3.7.8/x64/lib/python3.7/site-packages/ipykernel_launcher.py:49: MatplotlibDeprecationWarning: Case-insensitive properties were deprecated in 3.3 and support will be removed two minor releases later
/opt/hostedtoolcache/Python/3.7.8/x64/lib/python3.7/site-packages/ipykernel_launcher.py:50: MatplotlibDeprecationWarning: Case-insensitive properties were deprecated in 3.3 and support will be removed two minor releases later
/opt/hostedtoolcache/Python/3.7.8/x64/lib/python3.7/site-packages/ipykernel_launcher.py:51: MatplotlibDeprecationWarning: Case-insensitive properties were deprecated in 3.3 and support will be removed two minor releases later
###Markdown
Video 3: Multiplying Gaussians
###Code
#@title
from IPython.display import YouTubeVideo
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = "https://player.bilibili.com/player.html?bvid={0}&page={1}".format(id, page)
super(BiliVideo, self).__init__(src, width, height, **kwargs)
video = BiliVideo(id='BV1ni4y1V7bQ', width=854, height=480, fs=1)
print("Video available at https://www.bilibili.com/video/{0}".format(video.id))
video
###Output
Video available at https://www.bilibili.com/video/BV1ni4y1V7bQ
###Markdown
Exercise 2B: Finding the posterior analytically[If you are running short on time, feel free to skip the coding exercise below].As you may have noticed from the interactive demo, the product of two Gaussian distributions, like our prior and likelihood, remains a Gaussian, regardless of the parameters. We can directly compute the parameters of that Gaussian from the means and variances of the prior and likelihood. For example, the posterior mean is given by:$$ \mu_{posterior} = \frac{\mu_{auditory} \cdot \frac{1}{\sigma_{auditory}^2} + \mu_{visual} \cdot \frac{1}{\sigma_{visual}^2}}{1/\sigma_{auditory}^2 + 1/\sigma_{visual}^2} $$This formula is a special case for two Gaussians, but is a very useful one because:* The posterior has the same form (here, a normal distribution) as the prior, and* There is simple, closed-form expression for its parameters.When these properties hold, we call them **conjugate distributions** or **conjugate priors** (for a particular likelihood). Working with conjugate distributions is very convenient; otherwise, it is often necessary to use computationally-intensive numerical methods to combine the prior and likelihood. In this exercise, we ask you to verify that property. To do so, we will hold our auditory likelihood constant as an $\mathcal{N}(3, 1.5)$ distribution, while considering visual priors with different means ranging from $\mu=-10$ to $\mu=10$. For each prior,* Compute the posterior distribution using the function you wrote in Exercise 2A. Next, find its mean. The mean of a probability distribution is $\int_x p(x) dx$ or $\sum_x x\cdot p(x)$. * Compute the analytical posterior mean from auditory and visual using the equation above.* Use the provided plotting code to plot both estimates of the mean. Are the estimates of the posterior mean the same in both cases? Using these results, try to predict the posterior mean for the combination of a $\mathcal{N}(-4,4)$ prior and and $\mathcal{N}(4, 2)$ likelihood. Use the widget above to check your prediction. You can enter values directly by clicking on the numbers to the right of each slider; $\sqrt{2} \approx 1.41$.
###Code
def compare_computational_analytical_means():
x = np.arange(-10, 11, 0.1)
# Fixed auditory likelihood
mu_auditory = 3
sigma_auditory = 1.5
likelihood = my_gaussian(x, mu_auditory, sigma_auditory)
# Varying visual prior
mu_visuals = np.linspace(-10, 10)
sigma_visual = 1.5
# Accumulate results here
mus_by_integration = []
mus_analytical = []
for mu_visual in mu_visuals:
prior = my_gaussian(x, mu_visual, sigma_visual)
posterior = compute_posterior_pointwise(prior, likelihood)
############################################################################
## Add code that will find the posterior mean via numerical integration
#
############################################################################
mu_integrated = ...
############################################################################
## Add more code below that will calculate the posterior mean analytically
#
# Comment out the line below to test your solution
raise NotImplementedError("Please add code to find the mean both ways first")
############################################################################
mu_analytical = ...
mus_by_integration.append(mu_integrated)
mus_analytical.append(mu_analytical)
return mu_visuals, mus_by_integration, mus_analytical
# Uncomment the lines below to visualize your results
# mu_visuals, mu_computational, mu_analytical = compare_computational_analytical_means()
# plot_visual(mu_visuals, mu_computational, mu_analytical)
###Output
_____no_output_____
###Markdown
[*Click for solution*](https://github.com/erlichlab/course-content/tree/master//tutorials/W2D1_BayesianStatistics/solutions/W2D1_Tutorial1_Solution_8e15215d.py)*Example output:* Section 3: ConclusionThis tutorial introduced the Gaussian distribution and used Bayes' Theorem to combine Gaussians representing priors and likelihoods. In the next tutorial, we will use these concepts to probe how subjects integrate sensory information.
###Code
#@title Video 4: Conclusion
from IPython.display import YouTubeVideo
from IPython.display import IFrame
class BiliVideo(IFrame):
def __init__(self, id, page=1, width=400, height=300, **kwargs):
self.id=id
src = "https://player.bilibili.com/player.html?bvid={0}&page={1}".format(id, page)
super(BiliVideo, self).__init__(src, width, height, **kwargs)
video = BiliVideo(id='BV1wv411q7ex', width=854, height=480, fs=1)
print("Video available at https://www.bilibili.com/video/{0}".format(video.id))
video
###Output
Video available at https://www.bilibili.com/video/BV1wv411q7ex
###Markdown
Bonus Section: Multimodal Priors**Only do this if the first half-hour has not yet passed.**The preceeding exercises used a Gaussian prior, implying that participants expected the stimulus to come from a single location, though they might not know precisely where. However, suppose the subjects actually thought that sound might come from one of two distinct locations. Perhaps they can see two speakers (and know that speakers often emit noise). We could model this using a Gaussian prior with a large $\sigma$ that covers both locations, but that would also make every point in between seem likely too.A better approach is to adjust the form of the prior so that it better matches the participants' experiences/expectations. In this optional exercise, we will build a bimodal (2-peaked) prior out of Gaussians and examine the resulting posterior and its peaks. Exercise 3: Implement and test a multimodal prior* Complete the `bimodal_prior` function below to create a bimodal prior, comprised of the sum of two Gaussians with means $\mu = -3$ and $\mu = 3$. Use $\sigma=1$ for both Gaussians. Be sure to normalize the result so it is a proper probability distribution. * In Exercise 2, we used the mean location to summarize the posterior distribution. This is not always the best choice, especially for multimodal distributions. What is the mean of our new prior? Is it a particularly likely location for the stimulus? Instead, we will use the posterior **mode** to summarize the distribution. The mode is the *location* of the most probable part of the distribution. Complete `posterior_mode` below, to find it. (Hint: `np.argmax` returns the *index* of the largest element in an array).* Run the provided simulation and plotting code. Observe what happens to the posterior as the likelihood gets closer to the different peaks of the prior.* Notice what happens to the posterior when the likelihood is exactly in between the two modes of the prior (i.e., $\mu_{Likelihood} = 0$)
###Code
def bimodal_prior(x, mu_1=-3, sigma_1=1, mu_2=3, sigma_2=1):
################################################################################
## Finish this function so that it returns a bimodal prior, comprised of the
# sum of two Gaussians
#
# Comment out the line below to test out your solution
raise NotImplementedError("Please implement the bimodal prior")
################################################################################
prior = ...
return prior
def posterior_mode(x, posterior):
################################################################################
## Finish this function so that it returns the location of the mode
#
# Comment out the line below to test out your solution
raise NotImplementedError("Please implement the bimodal prior")
################################################################################
mode = ...
return mode
def multimodal_simulation(x, mus_visual, sigma_visual=1):
"""
Simulate an experiment where bimodal prior is held constant while
a Gaussian visual likelihood is shifted across locations.
Args:
x: array of points at which prior/likelihood/posterior are evaluated
mus_visual: array of means for the Gaussian likelihood
sigma_visual: scalar standard deviation for the Gaussian likelihood
Returns:
posterior_modes: array containing the posterior mode for each mean in mus_visual
"""
prior = bimodal_prior(x, -3, 1, 3, 1)
posterior_modes = []
for mu in mus_visual:
likelihood = my_gaussian(x, mu, 3)
posterior = compute_posterior_pointwise(prior, likelihood)
p_mode = posterior_mode(x, posterior)
posterior_modes.append(p_mode)
return posterior_modes
x = np.arange(-10, 10, 0.1)
mus = np.arange(-8, 8, 0.05)
# Uncomment the lines below to visualize your results
# posterior_modes = multimodal_simulation(x, mus, 1)
# multimodal_plot(x,
# bimodal_prior(x, -3, 1, 3, 1),
# my_gaussian(x, 1, 1),
# mus, posterior_modes)
###Output
_____no_output_____
###Markdown
###Code
# Mount Google Drive
from google.colab import drive # import drive from google colab
ROOT = "/content/drive" # default location for the drive
print(ROOT) # print content of ROOT (Optional)
drive.mount(ROOT,force_remount=True)
###Output
/content/drive
Go to this URL in a browser: https://accounts.google.com/o/oauth2/auth?client_id=947318989803-6bn6qk8qdgf4n4g3pfee6491hc0brc4i.apps.googleusercontent.com&redirect_uri=urn%3aietf%3awg%3aoauth%3a2.0%3aoob&response_type=code&scope=email%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdocs.test%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive%20https%3a%2f%2fwww.googleapis.com%2fauth%2fdrive.photos.readonly%20https%3a%2f%2fwww.googleapis.com%2fauth%2fpeopleapi.readonly
Enter your authorization code:
··········
Mounted at /content/drive
###Markdown
Neuromatch Academy: Week 2, Day 1, Tutorial 1 Bayes rule with Gaussians__Content creators:__ Vincent Valton, Konrad Kording, with help from Matt Krause__Content reviewers:__ Matt Krause, Jesse Livezey, Karolina Stosio, Saeed Salehi, Michael Waskom Tutorial ObjectivesThis is the first in a series of three main tutorials (+ one bonus tutorial) on Bayesian statistics. In these tutorials, we will develop a Bayesian model for localizing sounds based on audio and visual cues. This model will combine **prior** information about where sounds generally originate with sensory information about the **likelihood** that a specific sound came from a particular location. As we will see in subsequent lessons, the resulting **posterior distribution** not only allows us to make optimal decision about the sound's origin, but also lets us quantify how uncertain that decision is. Bayesian techniques are therefore useful **normative models**: the behavior of human or animal subjects can be compared against these models to determine how efficiently they make use of information. This notebook will introduce two fundamental building blocks for Bayesian statistics: the Gaussian distribution and the Bayes Theorem. You will: 1. Implement a Gaussian distribution2. Use Bayes' Theorem to find the posterior from a Gaussian-distributed prior and likelihood. 3. Change the likelihood mean and variance and observe how posterior changes.4. Advanced (*optional*): Observe what happens if the prior is a mixture of two gaussians?
###Code
#@title Video 1: Introduction to Bayesian Statistics
from IPython.display import YouTubeVideo
video = YouTubeVideo(id='K4sSKZtk-Sc', width=854, height=480, fs=1)
print("Video available at https://youtube.com/watch?v=" + video.id)
video
###Output
Video available at https://youtube.com/watch?v=K4sSKZtk-Sc
###Markdown
Setup Please execute the cells below to initialize the notebook environment.
###Code
import numpy as np
import matplotlib.pyplot as plt
#@title Figure Settings
import ipywidgets as widgets
plt.style.use("https://raw.githubusercontent.com/NeuromatchAcademy/course-content/master/nma.mplstyle")
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
#@title Helper functions
def my_plot_single(x, px):
"""
Plots normalized Gaussian distribution
Args:
x (numpy array of floats): points at which the likelihood has been evaluated
px (numpy array of floats): normalized probabilities for prior evaluated at each `x`
Returns:
Nothing.
"""
if px is None:
px = np.zeros_like(x)
fig, ax = plt.subplots()
ax.plot(x, px, '-', color='xkcd:green', LineWidth=2, label='Prior')
ax.legend()
ax.set_ylabel('Probability')
ax.set_xlabel('Orientation (Degrees)')
def posterior_plot(x, likelihood=None, prior=None, posterior_pointwise=None, ax=None):
"""
Plots normalized Gaussian distributions and posterior
Args:
x (numpy array of floats): points at which the likelihood has been evaluated
auditory (numpy array of floats): normalized probabilities for auditory likelihood evaluated at each `x`
visual (numpy array of floats): normalized probabilities for visual likelihood evaluated at each `x`
posterior (numpy array of floats): normalized probabilities for the posterior evaluated at each `x`
ax: Axis in which to plot. If None, create new axis.
Returns:
Nothing.
"""
if likelihood is None:
likelihood = np.zeros_like(x)
if prior is None:
prior = np.zeros_like(x)
if posterior_pointwise is None:
posterior_pointwise = np.zeros_like(x)
if ax is None:
fig, ax = plt.subplots()
ax.plot(x, likelihood, '-r', LineWidth=2, label='Auditory')
ax.plot(x, prior, '-b', LineWidth=2, label='Visual')
ax.plot(x, posterior_pointwise, '-g', LineWidth=2, label='Posterior')
ax.legend()
ax.set_ylabel('Probability')
ax.set_xlabel('Orientation (Degrees)')
return ax
def plot_visual(mu_visuals, mu_posteriors, max_posteriors):
"""
Plots the comparison of computing the mean of the posterior analytically and
the max of the posterior empirically via multiplication.
Args:
mu_visuals (numpy array of floats): means of the visual likelihood
mu_posteriors (numpy array of floats): means of the posterior, calculated analytically
max_posteriors (numpy array of floats): max of the posteriors, calculated via maxing the max_posteriors.
posterior (numpy array of floats): normalized probabilities for the posterior evaluated at each `x`
Returns:
Nothing.
"""
fig_w, fig_h = plt.rcParams.get('figure.figsize')
fig, ax = plt.subplots(nrows=2, ncols=1, figsize=(fig_w, 2 * fig_h))
ax[0].plot(mu_visuals, max_posteriors, '-g', label='mean')
ax[0].set_xlabel('Visual stimulus position')
ax[0].set_ylabel('Multiplied posterior mean')
ax[0].set_title('Sample output')
ax[1].plot(mu_visuals, mu_posteriors, '--', color='xkcd:gray', label='argmax')
ax[1].set_xlabel('Visual stimulus position')
ax[1].set_ylabel('Analytical posterior mean')
fig.tight_layout()
ax[1].set_title('Hurray for math!')
def multimodal_plot(x, example_prior, example_likelihood,
mu_visuals, posterior_modes):
"""Helper function for plotting Section 4 results"""
fig_w, fig_h = plt.rcParams.get('figure.figsize')
fig, ax = plt.subplots(nrows=2, ncols=1, figsize=(fig_w, 2*fig_h), sharex=True)
# Plot the last instance that we tried.
posterior_plot(x,
example_prior,
example_likelihood,
compute_posterior_pointwise(example_prior, example_likelihood),
ax=ax[0]
)
ax[0].set_title('Example combination')
ax[1].plot(mu_visuals, posterior_modes, '-g', label='argmax')
ax[1].set_xlabel('Visual stimulus position\n(Mean of blue dist. above)')
ax[1].set_ylabel('Posterior mode\n(Peak of green dist. above)')
fig.tight_layout()
###Output
_____no_output_____
###Markdown
Section 1: The Gaussian DistributionBayesian analysis operates on probability distributions. Although these can take many forms, the Gaussian distribution is a very common choice. Because of the central limit theorem, many quantities are Gaussian-distributed. Gaussians also have some mathematical properties that permit simple closed-form solutions to several important problems. In this exercise, you will implement a Gaussian by filling in the missing portion of `my_gaussian` below. Gaussians have two parameters. The **mean** $\mu$, which sets the location of its center. Its "scale" or spread is controlled by its **standard deviation** $\sigma$ or its square, the **variance** $\sigma^2$. (Be careful not to use one when the other is required). The equation for a Gaussian is:$$\mathcal{N}(\mu,\sigma^2) = \frac{1}{\sqrt{2\pi\sigma^2}}\exp\left(\frac{-(x-\mu)^2}{2\sigma^2}\right)$$Also, don't forget that this is a probability distribution and should therefore sum to one. While this happens "automatically" when integrated from $-\infty$ to $\infty$, your version will only be computed over a finite number of points. You therefore need to explicitly normalize it yourself. Test out your implementation with a $\mu = -1$ and $\sigma = 1$. After you have it working, play with the parameters to develop an intuition for how changing $\mu$ and $\sigma$ alter the shape of the Gaussian. This is important, because subsequent exercises will be built out of Gaussians. Exercise 1: Implement a Gaussian
###Code
def my_gaussian(x_points, mu, sigma):
"""
Returns normalized Gaussian estimated at points `x_points`, with parameters:
mean `mu` and std `sigma`
Args:
x_points (numpy array of floats): points at which the gaussian is
evaluated
mu (scalar): mean of the Gaussian
sigma (scalar): std of the gaussian
Returns:
(numpy array of floats) : normalized Gaussian evaluated at `x`
"""
###################################################################
## Add code to calcualte the gaussian px as a function of mu and sigma,
## for every x in x_points
## Function Hints: exp -> np.exp()
## power -> z**2
## remove the raise below to test your function
#raise NotImplementedError("You need to implement the Gaussian function!")
###################################################################
px = np.exp(-(x_points-mu)**2/(2*sigma**2))/np.sqrt(2*np.pi*sigma**2)
px /= np.sum(px)
return px
x = np.arange(-8, 9, 0.1)
# Uncomment to plot the results
px = my_gaussian(x, -1, 1)
my_plot_single(x, px)
###Output
_____no_output_____
###Markdown
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W2D1_BayesianStatistics/solutions/W2D1_Tutorial1_Solution_aeeeaedf.py)*Example output:* Section 2. Bayes' Theorem and the Posterior
###Code
#@title Video 2: Bayes' theorem
from IPython.display import YouTubeVideo
video = YouTubeVideo(id='ewQPHQMcdBs', width=854, height=480, fs=1)
print("Video available at https://youtube.com/watch?v=" + video.id)
video
###Output
Video available at https://youtube.com/watch?v=ewQPHQMcdBs
###Markdown
Bayes' rule tells us how to combine two sources of information: the prior (e.g., a noisy representation of our expectations about where the stimulus might come from) and the likelihood (e.g., a noisy representation of the stimulus position on a given trial), to obtain a posterior distribution taking into account both pieces of information. Bayes' rule states:\begin{eqnarray}\text{Posterior} = \frac{ \text{Likelihood} \times \text{Prior}}{ \text{Normalization constant}}\end{eqnarray}When both the prior and likelihood are Gaussians, this translates into the following form:$$\begin{array}{rcl}\text{Likelihood} &=& \mathcal{N}(\mu_{likelihood},\sigma_{likelihood}^2) \\\text{Prior} &=& \mathcal{N}(\mu_{prior},\sigma_{prior}^2) \\\text{Posterior} &\propto& \mathcal{N}(\mu_{likelihood},\sigma_{likelihood}^2) \times \mathcal{N}(\mu_{prior},\sigma_{prior}^2) \\&&= \mathcal{N}\left( \frac{\sigma^2_{likelihood}\mu_{prior}+\sigma^2_{prior}\mu_{likelihood}}{\sigma^2_{likelihood}+\sigma^2_{prior}}, \frac{\sigma^2_{likelihood}\sigma^2_{prior}}{\sigma^2_{likelihood}+\sigma^2_{prior}} \right) \end{array}$$In these equations, $\mathcal{N}(\mu,\sigma^2)$ denotes a Gaussian distribution with parameters $\mu$ and $\sigma^2$:$$\mathcal{N}(\mu, \sigma) = \frac{1}{\sqrt{2 \pi \sigma^2}} \; \exp \bigg( \frac{-(x-\mu)^2}{2\sigma^2} \bigg)$$In Exercise 2A, we will use the first form of the posterior, where the two distributions are combined via pointwise multiplication. Although this method requires more computation, it works for any type of probability distribution. In Exercise 2B, we will see that the closed-form solution shown on the line below produces the same result. Exercise 2A: Finding the posterior computationallyImagine an experiment where participants estimate the location of a noise-emitting object. To estimate its position, the participants can use two sources of information: 1. new noisy auditory information (the likelihood) 2. prior visual expectations of where the stimulus is likely to come from (visual prior). The auditory and visual information are both noisy, so participants will combine these sources of information to better estimate the position of the object.We will use Gaussian distributions to represent the auditory likelihood (in red), and a Gaussian visual prior (expectations - in blue). Using Bayes rule, you will combine them into a posterior distribution that summarizes the probability that the object is in each location. We have provided you with a ready-to-use plotting function, and a code skeleton.* Use `my_gaussian`, the answer to exercise 1, to generate an auditory likelihood with parameters $\mu$ = 3 and $\sigma$ = 1.5* Generate a visual prior with parameters $\mu$ = -1 and $\sigma$ = 1.5* Calculate the posterior using pointwise multiplication of the likelihood and prior. Don't forget to normalize so the posterior adds up to 1. * Plot the likelihood, prior and posterior using the predefined function `posterior_plot`
###Code
def compute_posterior_pointwise(prior, likelihood):
##############################################################################
# Write code to compute the posterior from the prior and likelihood via
# pointwise multiplication. (You may assume both are defined over the same x-axis)
#
# Comment out the line below to test your solution
#raise NotImplementedError("Finish the simulation code first")
##############################################################################
posterior = prior*likelihood
posterior /= np.sum(posterior)
return posterior
def localization_simulation(mu_auditory=3.0, sigma_auditory=1.5,
mu_visual=-1.0, sigma_visual=1.5):
##############################################################################
## Using the x variable below,
## create a gaussian called 'auditory' with mean 3, and std 1.5
## create a gaussian called 'visual' with mean -1, and std 1.5
#
#
## Comment out the line below to test your solution
#raise NotImplementedError("Finish the simulation code first")
###############################################################################
x = np.arange(-8, 9, 0.1)
auditory = my_gaussian(x,mu_auditory,sigma_auditory)
visual = my_gaussian(x,mu_visual,sigma_visual)
posterior = compute_posterior_pointwise(auditory, visual)
return x, auditory, visual, posterior
# Uncomment the lines below to plot the results
x, auditory, visual, posterior_pointwise = localization_simulation()
posterior_plot(x, auditory, visual, posterior_pointwise)
###Output
_____no_output_____
###Markdown
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W2D1_BayesianStatistics/solutions/W2D1_Tutorial1_Solution_39d14917.py)*Example output:* Interactive Demo: What affects the posterior?Now that we can compute the posterior of two Gaussians with *Bayes rule*, let's vary the parameters of those Gaussians to see how changing the prior and likelihood affect the posterior. **Hit the Play button or Ctrl+Enter in the cell below** and play with the sliders to get an intuition for how the means and standard deviations of prior and likelihood influence the posterior.When does the prior have the strongest influence over the posterior? When is it the weakest?
###Code
#@title
#@markdown Make sure you execute this cell to enable the widget!
x = np.arange(-10, 11, 0.1)
import ipywidgets as widgets
def refresh(mu_auditory=3, sigma_auditory=1.5, mu_visual=-1, sigma_visual=1.5):
auditory = my_gaussian(x, mu_auditory, sigma_auditory)
visual = my_gaussian(x, mu_visual, sigma_visual)
posterior_pointwise = visual * auditory
posterior_pointwise /= posterior_pointwise.sum()
w_auditory = (sigma_visual** 2) / (sigma_auditory**2 + sigma_visual**2)
theoretical_prediction = mu_auditory * w_auditory + mu_visual * (1 - w_auditory)
ax = posterior_plot(x, auditory, visual, posterior_pointwise)
ax.plot([theoretical_prediction, theoretical_prediction],
[0, posterior_pointwise.max() * 1.2], '-.', color='xkcd:medium gray')
ax.set_title(f"Gray line shows analytical mean of posterior: {theoretical_prediction:0.2f}")
plt.show()
style = {'description_width': 'initial'}
_ = widgets.interact(refresh,
mu_auditory=widgets.FloatSlider(value=2, min=-10, max=10, step=0.5, description="mu_auditory:", style=style),
sigma_auditory=widgets.FloatSlider(value=0.5, min=0.5, max=10, step=0.5, description="sigma_auditory:", style=style),
mu_visual=widgets.FloatSlider(value=-2, min=-10, max=10, step=0.5, description="mu_visual:", style=style),
sigma_visual=widgets.FloatSlider(value=0.5, min=0.5, max=10, step=0.5, description="sigma_visual:", style=style)
)
###Output
_____no_output_____
###Markdown
Video 3: Multiplying Gaussians
###Code
#@title
from IPython.display import YouTubeVideo
video = YouTubeVideo(id='AbXorOLBrws', width=854, height=480, fs=1)
print("Video available at https://youtube.com/watch?v=" + video.id)
video
###Output
Video available at https://youtube.com/watch?v=AbXorOLBrws
###Markdown
Exercise 2B: Finding the posterior analytically[If you are running short on time, feel free to skip the coding exercise below].As you may have noticed from the interactive demo, the product of two Gaussian distributions, like our prior and likelihood, remains a Gaussian, regardless of the parameters. We can directly compute the parameters of that Gaussian from the means and variances of the prior and likelihood. For example, the posterior mean is given by:$$ \mu_{posterior} = \frac{\mu_{auditory} \cdot \frac{1}{\sigma_{auditory}^2} + \mu_{visual} \cdot \frac{1}{\sigma_{visual}^2}}{1/\sigma_{auditory}^2 + 1/\sigma_{visual}^2} $$This formula is a special case for two Gaussians, but is a very useful one because:* The posterior has the same form (here, a normal distribution) as the prior, and* There is simple, closed-form expression for its parameters.When these properties hold, we call them **conjugate distributions** or **conjugate priors** (for a particular likelihood). Working with conjugate distributions is very convenient; otherwise, it is often necessary to use computationally-intensive numerical methods to combine the prior and likelihood. In this exercise, we ask you to verify that property. To do so, we will hold our auditory likelihood constant as an $\mathcal{N}(3, 1.5)$ distribution, while considering visual priors with different means ranging from $\mu=-10$ to $\mu=10$. For each prior,* Compute the posterior distribution using the function you wrote in Exercise 2A. Next, find its mean. The mean of a probability distribution is $\int_x p(x) dx$ or $\sum_x x\cdot p(x)$. * Compute the analytical posterior mean from auditory and visual using the equation above.* Use the provided plotting code to plot both estimates of the mean. Are the estimates of the posterior mean the same in both cases? Using these results, try to predict the posterior mean for the combination of a $\mathcal{N}(-4,4)$ prior and and $\mathcal{N}(4, 2)$ likelihood. Use the widget above to check your prediction. You can enter values directly by clicking on the numbers to the right of each slider; $\sqrt{2} \approx 1.41$.
###Code
def compare_computational_analytical_means():
x = np.arange(-10, 11, 0.1)
# Fixed auditory likelihood
mu_auditory = 3
sigma_auditory = 1.5
likelihood = my_gaussian(x, mu_auditory, sigma_auditory)
# Varying visual prior
mu_visuals = np.linspace(-10, 10)
sigma_visual = 1.5
# Accumulate results here
mus_by_integration = []
mus_analytical = []
for mu_visual in mu_visuals:
prior = my_gaussian(x, mu_visual, sigma_visual)
posterior = compute_posterior_pointwise(prior, likelihood)
############################################################################
## Add code that will find the posterior mean via numerical integration
#
############################################################################
mu_integrated = np.sum(x*posterior)
############################################################################
## Add more code below that will calculate the posterior mean analytically
#
# Comment out the line below to test your solution
#raise NotImplementedError("Please add code to find the mean both ways first")
############################################################################
mu_analytical = (mu_visual/sigma_visual**2 + mu_auditory/sigma_auditory**2)/(1/sigma_auditory**2 + 1/sigma_visual**2)
mus_by_integration.append(mu_integrated)
mus_analytical.append(mu_analytical)
return mu_visuals, mus_by_integration, mus_analytical
# Uncomment the lines below to visualize your results
mu_visuals, mu_computational, mu_analytical = compare_computational_analytical_means()
plot_visual(mu_visuals, mu_computational, mu_analytical)
###Output
_____no_output_____
###Markdown
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W2D1_BayesianStatistics/solutions/W2D1_Tutorial1_Solution_8e15215d.py)*Example output:* Section 3: ConclusionThis tutorial introduced the Gaussian distribution and used Bayes' Theorem to combine Gaussians representing priors and likelihoods. In the next tutorial, we will use these concepts to probe how subjects integrate sensory information.
###Code
#@title Video 4: Conclusion
from IPython.display import YouTubeVideo
video = YouTubeVideo(id='YC8GylOAAHs', width=854, height=480, fs=1)
print("Video available at https://youtube.com/watch?v=" + video.id)
video
###Output
Video available at https://youtube.com/watch?v=YC8GylOAAHs
###Markdown
Bonus Section: Multimodal Priors**Only do this if the first half-hour has not yet passed.**The preceeding exercises used a Gaussian prior, implying that participants expected the stimulus to come from a single location, though they might not know precisely where. However, suppose the subjects actually thought that sound might come from one of two distinct locations. Perhaps they can see two speakers (and know that speakers often emit noise). We could model this using a Gaussian prior with a large $\sigma$ that covers both locations, but that would also make every point in between seem likely too.A better approach is to adjust the form of the prior so that it better matches the participants' experiences/expectations. In this optional exercise, we will build a bimodal (2-peaked) prior out of Gaussians and examine the resulting posterior and its peaks. Exercise 3: Implement and test a multimodal prior* Complete the `bimodal_prior` function below to create a bimodal prior, comprised of the sum of two Gaussians with means $\mu = -3$ and $\mu = 3$. Use $\sigma=1$ for both Gaussians. Be sure to normalize the result so it is a proper probability distribution. * In Exercise 2, we used the mean location to summarize the posterior distribution. This is not always the best choice, especially for multimodal distributions. What is the mean of our new prior? Is it a particularly likely location for the stimulus? Instead, we will use the posterior **mode** to summarize the distribution. The mode is the *location* of the most probable part of the distribution. Complete `posterior_mode` below, to find it. (Hint: `np.argmax` returns the *index* of the largest element in an array).* Run the provided simulation and plotting code. Observe what happens to the posterior as the likelihood gets closer to the different peaks of the prior.* Notice what happens to the posterior when the likelihood is exactly in between the two modes of the prior (i.e., $\mu_{Likelihood} = 0$)
###Code
def bimodal_prior(x, mu_1=-3, sigma_1=1, mu_2=3, sigma_2=1):
################################################################################
## Finish this function so that it returns a bimodal prior, comprised of the
# sum of two Gaussians
#
# Comment out the line below to test out your solution
raise NotImplementedError("Please implement the bimodal prior")
################################################################################
prior = ...
return prior
def posterior_mode(x, posterior):
################################################################################
## Finish this function so that it returns the location of the mode
#
# Comment out the line below to test out your solution
raise NotImplementedError("Please implement the bimodal prior")
################################################################################
mode = ...
return mode
def multimodal_simulation(x, mus_visual, sigma_visual=1):
"""
Simulate an experiment where bimodal prior is held constant while
a Gaussian visual likelihood is shifted across locations.
Args:
x: array of points at which prior/likelihood/posterior are evaluated
mus_visual: array of means for the Gaussian likelihood
sigma_visual: scalar standard deviation for the Gaussian likelihood
Returns:
posterior_modes: array containing the posterior mode for each mean in mus_visual
"""
prior = bimodal_prior(x, -3, 1, 3, 1)
posterior_modes = []
for mu in mus_visual:
likelihood = my_gaussian(x, mu, 3)
posterior = compute_posterior_pointwise(prior, likelihood)
p_mode = posterior_mode(x, posterior)
posterior_modes.append(p_mode)
return posterior_modes
x = np.arange(-10, 10, 0.1)
mus = np.arange(-8, 8, 0.05)
# Uncomment the lines below to visualize your results
# posterior_modes = multimodal_simulation(x, mus, 1)
# multimodal_plot(x,
# bimodal_prior(x, -3, 1, 3, 1),
# my_gaussian(x, 1, 1),
# mus, posterior_modes)
###Output
_____no_output_____
###Markdown
Neuromatch Academy: Week 2, Day 1, Tutorial 1 Bayes rule with Gaussians**Tutorial Lecturer:** *Konrad Kording***Tutorial Content Creator:** *Vincent Valton* Introduction
###Code
#@title Video: Intro
from IPython.display import YouTubeVideo
video = YouTubeVideo(id='wbZ60vdnoqw', width=854, height=480, fs=1)
print("Video available at https://youtube.com/watch?v=" + video.id)
video
###Output
Video available at https://youtube.com/watch?v=wbZ60vdnoqw
###Markdown
---In this notebook we'll look at using *Bayes rule* with *Gaussian distributions*. That is, given a prior probability distribution, and a likelihood distribution, we will compute the posterior using Bayes rule and play with different likelihoods and Priors to get a good intuition of how it affects the posterior distribution. This is an example of a normative model. We assume that behavior has to deal with uncertainty and ask which behavior would be optimal. We can then ask if people show behavior that is similar to this optimal behavior. in the coming exercises, we will: 1. Implement a Gaussian prior1. Given Bayes rule, a Gaussian likelihood and prior, calculate the posterior distribution.1. Change the likelihood mean and variance and observe how posterior changes.1. Advanced (*optional*): Observe what happens if the prior is a mixture of two gaussians?--- Setup Please execute the cell below to initialize the notebook environment.
###Code
# imports
import time # import time
import numpy as np # import numpy
import scipy as sp # import scipy
import math # import basic math functions
import random # import basic random number generator functions
import os
import matplotlib.pyplot as plt # import matplotlib
from IPython import display
#@title Figure Settings
fig_w, fig_h = (8, 6)
plt.rcParams.update({'figure.figsize': (fig_w, fig_h)})
plt.style.use('ggplot')
%matplotlib inline
%config InlineBackend.figure_format = 'retina'
#@title Helper functions
def my_plot_single(x, px):
"""
Plots normalized Gaussian distribution
Args:
x (numpy array of floats): points at which the likelihood has been evaluated
px (numpy array of floats): normalized probabilities for prior evaluated at each `x`
Returns:
Nothing.
"""
if px is None:
px = np.zeros_like(x)
plt.plot(x, px, '-', color='xkcd:green', LineWidth=2, label='Prior')
plt.legend()
plt.ylabel('Probability')
plt.xlabel('Orientation (Degrees)')
def my_plot(x, auditory=None, visual=None, posterior_pointwise=None):
"""
Plots normalized Gaussian distributions and posterior
Args:
x (numpy array of floats): points at which the likelihood has been evaluated
auditory (numpy array of floats): normalized probabilities for auditory likelihood evaluated at each `x`
visual (numpy array of floats): normalized probabilities for visual likelihood evaluated at each `x`
posterior (numpy array of floats): normalized probabilities for the posterior evaluated at each `x`
Returns:
Nothing.
"""
if auditory is None:
auditory = np.zeros_like(x)
if visual is None:
visual = np.zeros_like(x)
if posterior_pointwise is None:
posterior_pointwise = np.zeros_like(x)
plt.plot(x, auditory, '-r', LineWidth=2, label='Auditory')
plt.plot(x, visual, '-b', LineWidth=2, label='Visual')
plt.plot(x, posterior_pointwise, '-g', LineWidth=2, label='Posterior')
plt.legend()
plt.ylabel('Probability')
plt.xlabel('Orientation (Degrees)')
def plot_visual(mu_visuals, mu_posteriors, max_posteriors):
"""
Plots the comparison of computing the mean of the posterior analytically and
the max of the posterior empirically via multiplication.
Args:
mu_visuals (numpy array of floats): means of the visual likelihood
mu_posteriors (numpy array of floats): means of the posterior, calculated analytically
max_posteriors (numpy array of floats): max of the posteriors, calculated via maxing the max_posteriors.
posterior (numpy array of floats): normalized probabilities for the posterior evaluated at each `x`
Returns:
Nothing.
"""
fig = plt.figure(figsize=(fig_w, 2*fig_h))
plt.subplot(211)
plt.plot(mu_visuals, max_posteriors,'-g', label='argmax')
plt.xlabel('Visual stimulus position')
plt.ylabel('Multiplied max of position')
plt.title('Sample output')
plt.subplot(212)
plt.plot(mu_visuals, mu_posteriors, '--', color='xkcd:gray', label='argmax')
plt.xlabel('Visual stimulus position')
plt.ylabel('Analytical posterior mean')
plt.tight_layout()
plt.title('Hurray for math!')
plt.show()
###Output
_____no_output_____
###Markdown
a. Implement a GaussianIn this exercise, you will implement a Gaussian by filling in the missing portion of `my_gaussian` below. Plot it and play with its parameters, because you will need an intuition for how $\mu$ and $\sigma$ affect the shape of the Gaussian. Reminder: the equation for a Gaussian is:\begin{eqnarray}\mathcal{N}(\mu,\sigma^2) = \frac{1}{\sqrt{2\pi\sigma^2}}\exp\left(\frac{-(x-\mu)^2}{2\sigma^2}\right)\end{eqnarray}Later, we will later use this Gaussian as the prior as a function of the angle where the stimulus is coming from. Test out your implementation with a $\mu = -1$ and $\sigma = 1$. Then try to change $\mu$ and $\sigma$ and see what the results look like. **Helper function(s)**
###Code
help(my_plot_single)
###Output
Help on function my_plot_single in module __main__:
my_plot_single(x, px)
Plots normalized Gaussian distribution
Args:
x (numpy array of floats): points at which the likelihood has been evaluated
px (numpy array of floats): normalized probabilities for prior evaluated at each `x`
Returns:
Nothing.
###Markdown
Exercise 1
###Code
def my_gaussian(x_points, mu, sigma):
"""
Returns normalized Gaussian estimated at points `x_points`, with parameters: mean `mu` and std `sigma`
Args:
x_points (numpy array of floats): points at which the gaussian is evaluated
mu (scalar): mean of the Gaussian
sigma (scalar): std of the gaussian
Returns:
(numpy array of floats) : normalized Gaussian evaluated at `x`
"""
###################################################################
## Calculate the gaussian as a function of mu and sigma, for each x (incl. hints )
## Function Hints: exp -> np.exp()
## power -> z**2
##
## remove the raise when the function is complete
# raise NotImplementedError("You need to implement the Gaussian function!")
###################################################################
return (1/np.sqrt(2*np.pi*sigma**2)*np.exp(-(x_points-mu)**2/(2*sigma**2)))
x = np.arange(-8, 9, 0.1)
# Uncomment once the task (steps above) is complete
px = my_gaussian(x, -1, 1)
my_plot_single(x, px)
###Output
_____no_output_____
###Markdown
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W2D1_BayesianStatistics/solutions/W2D1_Tutorial1_Solution_b97eeff5.py)*Example output:* b. Given Bayes rule, a Gaussian likelihood and prior, calculate the posterior distribution
###Code
#@title Video: Bayes' theorem
video = YouTubeVideo(id='XLATXJci3qQ', width=854, height=480, fs=1)
print("Video available at https://youtube.com/watch?v=" + video.id)
video
###Output
Video available at https://youtube.com/watch?v=XLATXJci3qQ
###Markdown
Bayes' rule tells us how to combine two sources of information, the prior and the likelihood, to obtain a posterior distribution taking into account both pieces of information. Bayes' rule states:\begin{eqnarray}\text{Posterior} = \frac{ \text{Likelihood} \times \text{Prior}}{ \text{Normalization constant}}\end{eqnarray}Mathematically, if both the likelihood and the Prior are Gaussian, this translates into:\begin{eqnarray} \text{Likelihood} = \mathcal{N}(\mu_{likelihood},\sigma_{likelihood}^2) = \frac{1}{\sqrt{2\pi\sigma^2_{likelihood}}}\exp\left(\frac{-(x-\mu_{likelihood})^2}{2\sigma^2_{likelihood}}\right)\end{eqnarray}\begin{eqnarray} \text{Prior} = \mathcal{N}(\mu_{prior},\sigma_{prior}^2) = \frac{1}{\sqrt{2\pi\sigma^2_{prior}}}\exp\left(\frac{-(x-\mu_{prior})^2}{2\sigma^2_{prior}}\right)\end{eqnarray}\begin{eqnarray} \text{Posterior} \propto \mathcal{N}(\mu_{likelihood},\sigma_{likelihood}^2) \times \mathcal{N}(\mu_{prior},\sigma_{prior}^2) = \mathcal{N}\left( \frac{\sigma^2_{likelihood}\mu_{prior}+\sigma^2_{prior}\mu_{likelihood}}{\sigma^2_{likelihood}+\sigma^2_{prior}}, \frac{\sigma^2_{likelihood}\sigma^2_{prior}}{\sigma^2_{likelihood}+\sigma^2_{prior}} \right) \tag{1}\end{eqnarray}where $\mathcal{N}(\mu,\sigma^2)$ denotes a Gaussian distribution with parameters $\mu_{likelihood}$ and $\sigma^2_{likelihood}$.Note that although there's a closed-form solution for the particular case of two Gaussians (as shown above), we're going to combine them using pointwise multiplication, which works for any family of distributions. Exercise 2We have a Gaussian auditory Likelihood (in red), and a Gaussian visual prior (in blue), and we want to combine the two to generate our posterior using Bayes rule.We provide you with a ready-to-use plotting function, and a code skeleton.**Suggestions*** Use `my_gaussian` (the answer to exercise 1) to generate an auditory likelihood with parameters $\mu$ = 3 and $\sigma$ = 1.5* Similarly, generate a visual prior with parameters $\mu$ = -1 and $\sigma$ = 1.5* Calculate the posterior using pointwise multiplication of the likelihood and prior (don't forget to normalize so the posterior adds up to 1)* Plot the likelihood, prior and posterior using the predefined function `my_plot`* Now change the standard deviation ($\sigma$) of the visual likelihood to 0.5. See how a more precise (tighter) visual prior relative to auditory results in a posterior that is weighted more heavily towards the most precise source of information. **Helper function(s)**
###Code
help(my_plot)
# since we will use this function (my_gaussian) throughout the whole tutorial
# we provide you the solution to the previous exercise, to avoid any headaches
def my_gaussian(x_points, mu, sigma):
"""
Returns normalized Gaussian estimated at points `x_points`, with parameters: mean `mu` and std `sigma`
Args:
x_points (numpy array of floats): points at which the gaussian is evaluated
mu (scalar): mean of the Gaussian
sigma (scalar): std of the gaussian
Returns:
(numpy array of floats) : normalized Gaussian evaluated at `x`
"""
px = np.exp(- 1/2/sigma**2 * (mu - x) ** 2)
px = px / px.sum() # this is the normalization part with a very strong assumption, that
# x_points cover the big portion of probability mass around the mean.
# Please think/discuss when this would be a dangerous assumption.
return px
x = np.arange(-8,9,0.1)
mu_auditory = 3
sigma_auditory= 1.5
mu_visual = -1
sigma_visual= 1.5
################################################################################
## Insert your code here to:
## create a gaussian called 'auditory' with mean 3, and std 1.5
## create a gaussian called 'visual' with mean -1, and std 1.5
## calculate the posterior by multiplying (pointwise) the 'auditory' and 'visual' gaussians
## (Hint: Do not forget to normalise the gaussians before plotting them)
## plot the distributions using the function `my_plot`
##
## you can use the following variables (conveniently used in the plotting function)
auditory = my_gaussian(x,mu_auditory,sigma_auditory)
visual = my_gaussian(x,mu_visual,sigma_visual)
posterior_pointwise = visual*auditory/(visual*auditory).sum()
################################################################################
# Uncomment once the task (steps above) is complete
my_plot(x, auditory, visual, posterior_pointwise)
###Output
_____no_output_____
###Markdown
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W2D1_BayesianStatistics/solutions/W2D1_Tutorial1_Solution_08217508.py)*Example output:* d. Change the likelihood mean and variance and observe how posterior changes
###Code
#@title Video: Multiplying Gaussians
video = YouTubeVideo(id='LXWPe5_fZzQ', width=854, height=480, fs=1)
print("Video available at https://youtube.com/watch?v=" + video.id)
video
###Output
Video available at https://youtube.com/watch?v=LXWPe5_fZzQ
###Markdown
Now that we can compute *Bayes rule* with two *Gaussians*, let's keep the auditory likelihood fixed straight ahead (mean = 0), and play around with the visual stimulus position (mean) to see how that affects the posterior.Observe how the posterior changes as a function of both the position of the likelihood with respect to the prior, and the relative weight of the likelihood with respect to the prior.**Hit the Play button or Ctrl+Enter in the cell below** and play with the sliders to get an intuition for how the means and standard deviations of prior and likelihood influence the posterior.
###Code
#@title Interactive widget (Make sure to execute this cell)
###### MAKE SURE TO RUN THIS CELL VIA THE PLAY BUTTON TO ENABLE SLIDERS ########
x = np.arange(-10,11,0.1)
import ipywidgets as widgets
def refresh(mu_auditory=-5, sigma_auditory=1.5, mu_visual=-1, sigma_visual=1.5):
auditory = my_gaussian(x, mu_auditory, sigma_auditory)+my_gaussian(x, mu_auditory+10, sigma_auditory)
auditory/=np.sum(auditory)
visual = my_gaussian(x, mu_visual, sigma_visual)
posterior_pointwise = visual * auditory
posterior_pointwise /= posterior_pointwise.sum()
w_auditory = (sigma_visual** 2) / (sigma_auditory**2 + sigma_visual**2)
theoretical_prediction = mu_auditory * w_auditory + mu_visual * (1 - w_auditory)
#plt.plot([theoretical_prediction, theoretical_prediction],
# [0, posterior_pointwise.max() * 1.2], '-.', color='xkcd:medium gray')
my_plot(x, auditory, visual, posterior_pointwise)
plt.title('Gray line shows analytical mean of posterior')
_ = widgets.interact(refresh,
mu_auditory = (-10, 10, .5),
sigma_auditory= (.5, 10, .5),
mu_visual = (-10, 10, .5),
sigma_visual= (.5, 10, .5))
###Output
_____no_output_____
###Markdown
e. Compute the posterior mean as a function of auditory meanWe can calculate the mean of the posterior as a function of the paramters of the visual and auditory distributions as follows:$$ \mu_{posterior} = \frac{\mu_{auditory} \cdot \frac{1}{\sigma_{auditory}^2} + \mu_{visual} \cdot \frac{1}{\sigma_{visual}^2}}{1/\sigma_{auditory}^2 + 1/\sigma_{visual}^2} = \frac{\mu_{auditory}~\sigma^2_{visual} + \mu_{visual}~ \sigma^2_{auditory}}{\sigma^2_{auditory} + \sigma^2_{visual}} $$This is a special case for the mean of a Gaussian ([equation 1](https://colab.research.google.com/drive/1p9Heh8WNiNkiSriNd63uxaGk29w71l2mscrollTo=HB2U9wCNyaSo&line=20&uniqifier=1)) that we saw in the previous section. Now it's your turn to calculate the mean as a function of different visual inputs:* Keep auditory parameters constant* Sweep through the visual mean `mu_visual`* Compute the analytical posterior mean from auditory and visual using the equation above.* Compute the empirical mode (*Mode* is defined as the most frequently occurring value in a data set, or value with highest probability in a PDF or PMF) of the posterior via multiplication using the `compute_mode_posterior_multiply` function* Plot the analytical posterior mean and the empirical posterior mode as a function of the visual mean. **Helper function(s)**
###Code
help(plot_visual)
mu_auditory = 3
sigma_auditory = 1.5
mu_visuals = np.linspace(-10, 10)
sigma_visual= 1.5
def compute_mode_posterior_multiply(x, mu_auditory, sigma_auditory,
mu_visual, sigma_visual):
"""
Computes the mode of the posterior via multiplication.
DO NOT EDIT THIS FUNCTION !!!
Args:
x (numpy array of floats):
mu_auditory (numpy array of floats): mean of the auditory likelihood
sigma_auditory (numpy array of floats): standard deviation of the auditory likelihood
mu_visual (numpy array of floats): mean of the visual likelihood
sigma_visual (numpy array of floats): standard deviation of the visual likelihood
Returns:
the mode of x
"""
auditory = my_gaussian(x, mu_auditory, sigma_auditory)
visual = my_gaussian(x, mu_visual, sigma_visual)
posterior_pointwise = auditory * visual
posterior_pointwise /= posterior_pointwise.sum()
return x[posterior_pointwise.argmax()]
################################################################################
## Insert your code here to:
## sweep through the mu_visuals with a for loop
## compute mu_posterior with the analytical formula in each case
## compute the max of the posterior by multiplying gaussians in each case
## using the compute_mode_posterior_multiply
## plot mu_posterior_analytical as a function of mu_posterior_multiply
################################################################################
mu_posteriors=[]
max_posteriors = []
for mu_visual in mu_visuals:
max_posteriors.append(compute_mode_posterior_multiply(x, mu_auditory, sigma_auditory,mu_visual, sigma_visual))
mu_posteriors.append((mu_auditory/sigma_auditory**2 + mu_visual/sigma_visual**2)/(1/sigma_auditory**2 + 1/sigma_visual**2))
plot_visual(mu_visuals, mu_posteriors, max_posteriors)
###Output
_____no_output_____
###Markdown
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W2D1_BayesianStatistics/solutions/W2D1_Tutorial1_Solution_fd84cbd0.py)*Example output:*
###Code
#@title Video: Outro
video = YouTubeVideo(id='f-1E9W35hDw', width=854, height=480, fs=1)
print("Video available at https://youtube.com/watch?v=" + video.id)
video
###Output
Video available at https://youtube.com/watch?v=f-1E9W35hDw
###Markdown
--- f. ADDITIONAL exercise: Multimodal priors**Only do this if the first half-hour has not yet passed.**Bayes rule works similarly for cue combination (auditory + visual) as it would with a prior and likelihood.What do you think is going to happen to the posterior if we were to use a multimodal prior instead of a single Gaussian (i.e. a prior with multiple peaks)?**Suggestions*** Create a bi-modal prior by summing two Gaussians centered on -3 and 3 respectively, with $\sigma_{prior}$ = 1* Similarly to the previous exercise, allow the mean of the likelihood to vary and plot the prior, likelihood and posterior using the function `my_plot`. - Observe what happens to the posterior as the likelihood gets closer to the different peaks of the prior. - Notice what happens to the posterior when the likelihood is exactly in between the two modes of the prior (i.e. $\mu_{Likelihood}$ = 0)* Plot the mode of the posterior as a function of the visual stimulus mean. - What to you observe? How does it compare to the previous exercise?
###Code
x = np.arange(-10, 10, 0.1)
mu_visuals = np.arange(-6, 6, 0.1)
std_visual = 1
mu1_auditory = -3
mu2_auditory = 3
std_auditory = 1
################################################################################
## Insert your code here
## Reuse your code from Exercise 2, but replace the prior with a bimodal prior
## by summing two Gaussians with variance = 1, and means [-3, 3] respectively
################################################################################
auditory = my_gaussian(x, mu1_auditory, std_auditory) + my_gaussian(x, mu2_auditory, std_auditory)
auditory /= np.sum(auditory)
mode_posteriors = []
for mu_visual in mu_visuals:
visual = my_gaussian(x, mu_visual, std_visual)
posterior_pointwise = auditory * visual
mode_posteriors.append(x[posterior_pointwise.argmax()])
visual = my_gaussian(x, mu_visual, std_visual)
posterior_pointwise = auditory * visual
fig = plt.figure(figsize=(fig_w, 2*fig_h))
plt.subplot(2, 1, 1)
my_plot(x,
auditory,
visual,
posterior_pointwise / np.sum(posterior_pointwise)
)
plt.title('Sample solution')
plt.subplot(2, 1, 2)
plt.plot(mu_visuals, mode_posteriors, '-g' , label='argmax')
plt.xlabel('Visual stimulus position')
plt.ylabel('Posterior max')
plt.tight_layout()
plt.show()
###Output
_____no_output_____ |
test_colab.ipynb | ###Markdown
###Code
pwd
###Output
_____no_output_____
###Markdown
###Code
import os
from google.colab import files
files.upload()
from google.colab import widgets
grid = widgets.Grid(3, 3, header_column=True, header_row=True)
for i in range(3):
for j in range(3):
with grid.output_to(i, j):
print(i + j)
from google.colab import drive
drive.mount('/content/drive')
!pwd
!rm *.CSV
import csv
import pandas as pd
df = pd.read_csv('constituents (2).csv')
!cp 'constituents (2).csv' '/content/drive/My Drive'
###Output
_____no_output_____
###Markdown
**Test Colab** 새 2
###Code
import numpy as np
import pandas as pd
import scipy as sp
from scipy import stats
from matplotlib import pyplot as plt
import seaborn as sns
sns.set()
%precision 3
%matplotlib inline
from google.colab import files
uploaded = files.upload()
for fn in uploaded.keys():
print('User uploaded file "{name}" with length {length} bytes'.format(
name=fn, length=len(uploaded[fn])))
paired_test_data = pd.read_csv("3-9-1-paired-t-test.csv")
print(paired_test_data)
###Output
person medicine body_temperature
0 A before 36.2
1 B before 36.2
2 C before 35.3
3 D before 36.1
4 E before 36.1
5 A after 36.8
6 B after 36.1
7 C after 36.8
8 D after 37.1
9 E after 36.9
|
AnalisisDeDatos/4_Data_Wrangling_Avanzado/ejercicio/ejercicio.ipynb | ###Markdown
Recordá abrir en una nueva pestaña Ejercicio: Informe macroeconómico de ArgentinaLa consultora "Nuevos Horizontes" quiere hacer un análisis del mercado argentino para entender como ha evolucionado en los últimos años. Van a analizar dos indicadores macroeconómicos principales: el **IPC: Índice de Precios al Consumidor** (para medir inflación) y el tipo de cambio (**cotización del dólar**). IPC: Índice de Precios al ConsumidorPara más información sobre el IPC pueden visitar la siguiente página del INDEC: https://www.indec.gob.ar/indec/web/Nivel4-Tema-3-5-31La base de IPC a analizar tiene como base diciembre de 2016, al cual le corresponde el índice 100. Los precios se encuentran con cuatro niveles de apertura: * General: Indice de Precios de toda la canasta de bienes y servicios considerada en el análisis* Estacional: Bienes y servicios con comportamiento estacional. Por ejemplo: frutas y verduras* Regulados: Bienes y servicios cuyos precios están sujetos a regulación o tienen alto componente impositivo. Por ejemplo: electricidad* Núcleo: : Resto de los grupos del IPCSu jefa quiere analizar el comportamiento de los cuatro niveles de apertura del indice de precios en los años que componen el dataset. Para eso le pide que obtenga el promedio, mediana e índice máximo anuales para cada nivel de apertura. Luego, de ser posible, graficar la evolución anual del índice medio a nivel general.**Pasos sugeridos:** 1) Leer los datos del IPC. 2) Modificar la tabla para que cumpla con la definición de tidy data: cada variable debe ser una columna (Apertura, Fecha e Indice). 3) Convertir la variable de fecha al formato date-time y extraer el año y el mes. *Ayuda*: Vas a tener que utilizar el argumento format en la función to_datetime de pandas. En esta página vas a poder encontrar los códigos de formato o directivas necesarios para convertir las fechas: https://docs.python.org/es/3/library/datetime.htmlstrftime-and-strptime-behavior 4) Calcular el indice promedio, mediano y maximo por año para cada nivel de apertura. 5) Graficar.
###Code
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
%matplotlib inline
###Output
_____no_output_____
###Markdown
**1) Leer los datos del IPC.**
###Code
ipc_df = pd.read_csv('https://datasets-humai.s3.amazonaws.com/datasets/ipc_indec.csv')
###Output
_____no_output_____
###Markdown
**2) Modificar la tabla** para que cumpla con la definición de tidy data: cada variable debe ser una columna (Apertura, Fecha e Indice). **3)** Convertir la **variable de fecha** al formato date-time y extraer el año y el mes **4)** Calcular el **indice promedio, mediano y maximo** por año para cada nivel de apertura. **5) Graficar** DolarLa base de cotización de dolar traer los precios de compra y venta oficiales de la divisa en Argentina desde el 01-06-2015 hasta el 03-08-2020 según el portal Ámbito Financiero.Para proseguir con el informe se quiere obtener la cotización media diaria (promedio entre compra y venta) y obtener la mediana mensual con su respectivo gráfico. Adicionalmente, se quiere encontrar el top 5 de los días con mayores aumentos porcentuales en el tipo de cambio para la misma ventana de tiempo que se analizó el IPC (desde 01-12-2016 hasta el 30-06-2020)**Pasos sugeridos:** 1) Leer los datos de la cotización del dolar 2) Crear una variable que compute el valor promedio entre compra y venta por día 3) Convertir la fecha de un dato tipo string a un objeto datetime (to_datetime). Construir las variables de año y mes. 4) Calcular el promedio mensual y graficar (recordar ordenar en forma ascendente la fecha) 5) Ordenar de manera ascendente por fecha, filtrar las fechas señaladas y calcular la variación porcentual diaria en la cotización 6) Hallar los 5 días con mayor variación en la cotización. **1)** Leer los datos de la cotización del dolar
###Code
dolar_df = pd.read_csv('https://datasets-humai.s3.amazonaws.com/datasets/dolar_oficial_ambito.csv')
###Output
_____no_output_____
###Markdown
Recordá abrir en una nueva pestaña Ejercicio: Informe macroeconómico de ArgentinaLa consultora "Nuevos Horizontes" quiere hacer un análisis del mercado argentino para entender como ha evolucionado en los últimos años. Van a analizar dos indicadores macroeconómicos principales: el **IPC: Índice de Precios al Consumidor** (para medir inflación) y el tipo de cambio (**cotización del dólar**). IPC: Índice de Precios al ConsumidorPara más información sobre el IPC pueden visitar la siguiente página del INDEC: https://www.indec.gob.ar/indec/web/Nivel4-Tema-3-5-31La base de IPC a analizar tiene como base diciembre de 2016, al cual le corresponde el índice 100. Los precios se encuentran con cuatro niveles de apertura: * General: Indice de Precios de toda la canasta de bienes y servicios considerada en el análisis* Estacional: Bienes y servicios con comportamiento estacional. Por ejemplo: frutas y verduras* Regulados: Bienes y servicios cuyos precios están sujetos a regulación o tienen alto componente impositivo. Por ejemplo: electricidad* Núcleo: : Resto de los grupos del IPCSu jefa quiere analizar el comportamiento de los cuatro niveles de apertura del indice de precios en los años que componen el dataset. Para eso le pide que obtenga el promedio, mediana e índice máximo anuales para cada nivel de apertura. Luego, de ser posible, graficar la evolución anual del índice medio a nivel general.**Pasos sugeridos:** 1) Leer los datos del IPC. 2) Modificar la tabla para que cumpla con la definición de tidy data: cada variable debe ser una columna (Apertura, Fecha e Indice). 3) Convertir la variable de fecha al formato date-time y extraer el año y el mes. *Ayuda*: Vas a tener que utilizar el argumento format en la función to_datetime de pandas. En esta página vas a poder encontrar los códigos de formato o directivas necesarios para convertir las fechas: https://docs.python.org/es/3/library/datetime.htmlstrftime-and-strptime-behavior 4) Calcular el indice promedio, mediano y maximo por año para cada nivel de apertura. 5) Graficar.
###Code
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
%matplotlib inline
###Output
_____no_output_____
###Markdown
**1) Leer los datos del IPC.**
###Code
ipc_df = pd.read_csv('https://datasets-humai.s3.amazonaws.com/datasets/ipc_indec.csv')
###Output
_____no_output_____
###Markdown
**2) Modificar la tabla** para que cumpla con la definición de tidy data: cada variable debe ser una columna (Apertura, Fecha e Indice). **3)** Convertir la **variable de fecha** al formato date-time y extraer el año y el mes **4)** Calcular el **indice promedio, mediano y maximo** por año para cada nivel de apertura. **5) Graficar** DolarLa base de cotización de dolar traer los precios de compra y venta oficiales de la divisa en Argentina desde el 01-06-2015 hasta el 03-08-2020 según el portal Ámbito Financiero.Para proseguir con el informe se quiere obtener la cotización media diaria (promedio entre compra y venta) y obtener la mediana mensual con su respectivo gráfico. Adicionalmente, se quiere encontrar el top 5 de los días con mayores aumentos porcentuales en el tipo de cambio para la misma ventana de tiempo que se analizó el IPC (desde 01-12-2016 hasta el 30-06-2020)**Pasos sugeridos:** 1) Leer los datos de la cotización del dolar 2) Crear una variable que compute el valor promedio entre compra y venta por día 3) Convertir la fecha de un dato tipo string a un objeto datetime (to_datetime). Construir las variables de año y mes. 4) Calcular el promedio mensual y graficar (recordar ordenar en forma ascendente la fecha) 5) Ordenar de manera ascendente por fecha, filtrar las fechas señaladas y calcular la variación porcentual diaria en la cotización 6) Hallar los 5 días con mayor variación en la cotización. **1)** Leer los datos de la cotización del dolar
###Code
dolar_df = pd.read_csv('https://datasets-humai.s3.amazonaws.com/datasets/dolar_oficial_ambito.csv')
###Output
_____no_output_____ |
notebooks/intro/notebook-tour-part-5.ipynb | ###Markdown
Introducing the JASMIN Notebook ServiceIn this Notebook, we will discuss:1. What is a Notebook?2. Using Python in the browser 3. Plotting in a Notebook4. Working with data in the CEDA Archive5. Accessing data in Group Workspaces6. Creating virtual environments to install additional software7. Sharing Notebooks 5. Accessing data in Group WorkspacesOn JASMIN, many project share data internally using large disk allocations known as Group Workspaces (GWSs). Your JASMIN Notebook session has _read access_ to any GWSs that you can normally access via an SSH session.For example:
###Code
import pandas as pd
fpath = '/gws/nopw/j04/cedaproc/public-data/uk_max_temp.txt'
df = pd.read_csv(fpath, sep='\s+', header=6, index_col='Year')
###Output
_____no_output_____
###Markdown
This is a Pandas DataFrame, let's take a look at the first few rows
###Code
df.head(3)
# Select January and July
jj = df.loc[:, ['JAN', 'JUL']]
jj.head(5)
len(jj)
###Output
_____no_output_____
###Markdown
And we can plot it:
###Code
ax = jj.plot(title='January vs July maximum temp records (degC)')
ax.set_ylabel('Max Temp (degC)')
###Output
_____no_output_____ |
examples/jkeung/learning_curve.ipynb | ###Markdown
Data Loading
###Code
digits = load_digits()
X, y = digits.data, digits.target
###Output
_____no_output_____
###Markdown
Configuration
###Code
# Set the train sizes
train_sizes = np.linspace(.1, 1.0, 10)
###Output
_____no_output_____
###Markdown
Visualizers
###Code
from yellowbrick.classifier.learning_curve import LearningCurveVisualizer
###Output
_____no_output_____
###Markdown
Visualizing using GaussianNB
###Code
viz = LearningCurveVisualizer(GaussianNB())
viz.fit(X,y)
viz.show()
###Output
_____no_output_____
###Markdown
Visualizing using GaussianNB with Varying Training Samples
###Code
viz = LearningCurveVisualizer(GaussianNB(), train_sizes=np.linspace(.1, 1.0, 15))
viz.fit(X,y)
viz.show()
###Output
_____no_output_____
###Markdown
Visualizing using GaussianNB with Varying Training Samples and Cross Validation
###Code
viz = LearningCurveVisualizer(GaussianNB(),
train_sizes=np.linspace(.1, 1.0, 15),
cv = ShuffleSplit(n_splits=100, test_size=0.2, random_state=0))
viz.fit(X,y)
viz.show()
###Output
_____no_output_____
###Markdown
Visualizing using SVC with Varying Training Samples and Cross Validation
###Code
viz = LearningCurveVisualizer(SVC(kernel='linear'),
train_sizes=np.linspace(0.1, 1.0, 5),
cv = ShuffleSplit(n_splits=100, test_size=0.2, random_state=0))
viz.fit(X,y)
viz.show()
###Output
_____no_output_____
###Markdown
Data Loading
###Code
digits = load_digits()
X, y = digits.data, digits.target
###Output
_____no_output_____
###Markdown
Configuration
###Code
# Set the train sizes
train_sizes = np.linspace(.1, 1.0, 10)
###Output
_____no_output_____
###Markdown
Visualizers
###Code
from yellowbrick.classifier.learning_curve import LearningCurveVisualizer
###Output
_____no_output_____
###Markdown
Visualizing using GaussianNB
###Code
viz = LearningCurveVisualizer(GaussianNB())
viz.fit(X,y)
viz.poof()
###Output
_____no_output_____
###Markdown
Visualizing using GaussianNB with Varying Training Samples
###Code
viz = LearningCurveVisualizer(GaussianNB(), train_sizes=np.linspace(.1, 1.0, 15))
viz.fit(X,y)
viz.poof()
###Output
_____no_output_____
###Markdown
Visualizing using GaussianNB with Varying Training Samples and Cross Validation
###Code
viz = LearningCurveVisualizer(GaussianNB(),
train_sizes=np.linspace(.1, 1.0, 15),
cv = ShuffleSplit(n_splits=100, test_size=0.2, random_state=0))
viz.fit(X,y)
viz.poof()
###Output
_____no_output_____
###Markdown
Visualizing using SVC with Varying Training Samples and Cross Validation
###Code
viz = LearningCurveVisualizer(SVC(kernel='linear'),
train_sizes=np.linspace(0.1, 1.0, 5),
cv = ShuffleSplit(n_splits=100, test_size=0.2, random_state=0))
viz.fit(X,y)
viz.poof()
###Output
_____no_output_____ |
Algorismica/ListComprehensions.ipynb | ###Markdown
Aquest notebook forma part dels continguts teòrics dels problemes de l'assignatura d'Algorísmica del Grau d'Enginyeria Informàtica a la Facultat de Matemàtiques i Informàtica de la Universitat de Barcelona impartida per Jordi Vitrià i Mireia RiberaEls problemes s'ofereixen sota llicència CC-BY-NC-ND license, i el codi sota Llicència MIT.< Complexitat | Explicacions teòriques | LListat de problemes | Expressions regulars > ( Continguts teòrics) List comprehensions List comprehensionsPer crear llistes de manera molt eficient, podem usar les list comprehensions.
###Code
# Exemple de creació de la llista dels quadrats de 1 a 10 a la manera clàssica
quadrats = []
for x in range(10):
quadrats.append(x ** 2)
print(quadrats)
# Exemple de creació de la llista de quadrats de 1 a 10 amb list comprehensions
quadrats2 = [x ** 2 for x in range(10)] # primer indiquem l'expressió que anirà omplint la llista, després el rang de valors
# i podem posteriorment indicar altres rangs o condicions
print(quadrats2)
#Tot i que la complexitat és la mateixa, la segona instrucció s'executa més ràpidament i amb menys recursos que la primera
# Exemple 1: Traducció a list comprehension de la següent estructura
combinacions=[]
for x in [1, 2, 3]:
for y in [3, 1, 4]:
if x != y:
combinacions.append((x, y))
print(combinacions)
# combinacions2 = [ expressió que ha d'omplir la llista for més extern, for segon més extern, if]
combinacions2 = [(x, y) for x in [1, 2, 3] for y in [3, 1, 4] if x != y]
print(combinacions2)
###Output
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
[(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]
###Markdown
Les comprehensions de les llistes són una eina per transformar una llista (qualsevol iterable en realitat) en una altra llista. Durant aquesta transformació, els elements es poden incloure de manera condicional a la nova llista i cada element es pot transformar segons sigui necessari.Cada comprehension es pot reescriure com un bucle sobre la lista, però no tot bucle es pot reescriure com a list comprehension.Començant pel cas més senzill, una list comprehension com aquesta:```pythona = [func(element) for element in sequence]```és equivalent a:```pythona = []for element in sequence: a.append(func(element))```De la mateixa manera que podeu afegir `for` addicionals als bucles i condicions `if` dins dels bucles, també podeu afegir-les a la comprensió.La clau a entendre és que l'ordre d'esquerra a dreta en la comprehennsion assigna el mateix ordre als bucles explícits:```pythona = [func(element) for subseq in seq2d for element in subseq if pred(element)]a = []for subseq in seq2d: for element in subseq: if pred(element): a.append(func(element))```També podem usar les list comprehensions per a fer combinacions:
###Code
[a+b+c for a in ['A','B','C'] for b in ['D','E','F'] for c in ['G','H','I']]
###Output
_____no_output_____
###Markdown
Exercici 1: Escriu en forma de list comprehension les següents llistes1. Fer una llista amb tots els números fins a 102. Fer una llista amb tots ls números fins a 10 múltiples de 23. Fer una llista amb totes les parelles (i, j) amb i de 0 a 2 i amb j de 0 a 34. Fer una llista amb tots els números divisibles per 3 menors a 205. Fer una llista amb tots els números __anteriors__ als divisibles per 3 menors a 206. Fer una llista amb totes les parelles de numeros positius menors a 20 que sumin 187. Fer una llista amb els múltiples de 3 i 5 menors que 1000. Després calcula la suma de tots els elements de la llista8. Fer una llista amb els valors de 100 a 1000, múltiples de 10, en ordre invers. És a dir 1000, 990, 980...
###Code
#1
llista1 = [x for x in range(11)]
print('1.',llista1)
print('')
#2
llista2 = [x for x in range(0,11,2)]
print('2.',llista2)
print('')
#3
llista3 = [(i,j) for i in range(3) for j in range(4)]
print('3.',llista3)
print('')
#4
llista4 = [x for x in range(3,20) if not x%3]
print('4.',llista4)
print('')
#5
llista5 = [x for x in range(20) if not (x+1)%3]
print('5.',llista5)
print('')
#6
llista6 = [(x,y) for x in range(10) for y in range(9,20) if x+y == 18]
print('6.',llista6)
print('')
#7
llista7 = [x for x in range(1000) if not x%3 or not x%5]
suma7 = sum(llista7)
print('7.',suma7,llista7)
print('')
#8
llista8 = [x for x in range(1000,99,-10)]
print('8.',llista8)
# Executar aquesta cel.la per donar estil al notebook
from IPython.core.display import HTML
import requests
style=requests.get('https://raw.githubusercontent.com/algorismica2019/problemes/master/assets/prova.css').text
HTML('<style>{}</style>'.format(style))
###Output
_____no_output_____ |
migration_challenge_keras_image/Instructions.ipynb | ###Markdown
TensorFlow MNIST Lift and Shift ExerciseFor this exercise notebook, you should be able to use the `Python 3 (TensorFlow 1.15 Python 3.7 CPU Optimized)` kernel on SageMaker Studio, or `conda_tensorflow_p36` on classic SageMaker Notebook Instances.--- IntroductionYour new colleague in the data science team (who isn't very familiar with SageMaker) has written a nice notebook to tackle an image classification problem with Keras: [Local Notebook.ipynb](Local%20Notebook.ipynb).It works OK with the simple MNIST data set they were working on before, but now they'd like to take advantage of some of the features of SageMaker to tackle bigger and harder challenges.**Can you help refactor the Local Notebook code, to show them how to use SageMaker effectively?** Getting StartedFirst, check you can **run the [Local Notebook.ipynb](Local%20Notebook.ipynb) notebook through** - reviewing what steps it takes.**This notebook** sets out a structure you can use to migrate code into, and lists out some of the changes you'll need to make at a high level. You can either work directly in here, or duplicate this notebook so you still have an unchanged copy of the original.Try to work through the sections first with an MVP goal in mind (fitting the model to data in S3 via a SageMaker Training Job, and deploying/using the model through a SageMaker Endpoint). At the end, there are extension exercises to bring in more advanced functionality. DependenciesListing all our imports at the start helps to keep the requirements to run any script/file transparent up-front, and is specified by nearly every style guide including Python's official [PEP 8](https://www.python.org/dev/peps/pep-0008/imports)
###Code
!pip install ipywidgets matplotlib
# External Dependencies:
from IPython.display import display, HTML
import matplotlib.pyplot as plt
import numpy as np
# Local Dependencies:
from util.nb import upload_in_background
# TODO: What else will you need?
# Have a look at the documentation: https://sagemaker.readthedocs.io/en/stable/frameworks/tensorflow/using_tf.html
# to see which libraries need to be imported to use sagemaker and the tensorflow estimator
# TODO: Here might be a good place to init any SDKs you need...
# 1. Setup the SageMaker role
role = ?
# 2. Setup the SageMaker session
sess = ?
# 3. Setup the SageMaker default bucket
bucket_name = ?
# Have a look at the previous examples to find out how to do it
###Output
_____no_output_____
###Markdown
Data PreparationThe primary data source for a SageMaker training job is (nearly) always S3 - so we should upload our training and test data there.We'd like our training job to be reusable for other image classification projects, so we'll upload in the **folders-of-images format** rather than the straight pre-processed numpy arrays.However, for this particular dataset (tens of thousands of tiny files) it's easy to accidentally write a poor-performing upload that **could take a long time**... So we prepared the below to help you run the upload **in the background** using the [aws s3 sync](https://docs.aws.amazon.com/cli/latest/reference/s3/sync.html) CLI command.**Check you understand** what data it's going to upload from this notebook, and where it's going to store it in S3, then start the upload running while you work on the rest.
###Code
upload_in_background(local_path="data", s3_uri=f"s3://{bucket_name}/mnist")
###Output
_____no_output_____
###Markdown
You can carry on working on the other sections while your data uploads! Data Input ("Channels") ConfigurationThe draft code has **2 data sets**: One for training, and one for test/validation. (For classification, the folder location of each image is sufficient as a label).In SageMaker terminology, each input data set is a "channel" and we can name them however we like... Just make sure you're consistent about what you call each one!For a simple input configuration, a channel spec might just be the S3 URI of the folder. For configuring more advanced options, there's the [s3_input](https://sagemaker.readthedocs.io/en/stable/inputs.html) class in the SageMaker SDK.
###Code
# TODO: Define your 2 data channels
# The data can be found in: "s3://{bucket_name}/mnist/train" and "s3://{bucket_name}/mnist/test"
inputs = # Look at the previous example to see how the inputs were defined
###Output
_____no_output_____
###Markdown
Algorithm ("Estimator") Configuration and RunInstead of loading and fitting this data here in the notebook, we'll be creating a [TensorFlow Estimator](https://sagemaker.readthedocs.io/en/stable/sagemaker.tensorflow.htmltensorflow-estimator) through the SageMaker SDK, to run the code on a separate container that can be scaled as required.The ["Using TensorFlow with the SageMaker Python SDK"](https://sagemaker.readthedocs.io/en/stable/using_tf.htmltrain-a-model-with-tensorflow) docs give a good overview of this process. You should run your estimator in **script mode** (which is easier to follow than the old default legacy mode) and as **Python 3**.**Use the [src/main.py](src/main.py) file** as your entry point to port code into - which has already been created for you with some basic hints.
###Code
# TODO: Create your TensorFlow estimator
# Note the TensorFlow class inherits from some cross-framework base classes with additional
# constructor options:
# https://sagemaker.readthedocs.io/en/stable/estimators.html
# https://sagemaker.readthedocs.io/en/stable/frameworks/tensorflow/using_tf.html?highlight=%20TrainingInput#create-an-estimator
# We are using tensorflow 1.14 and python 3
# You can reuse the metrics definition from the previous example
# (Optional) Look at the Tensorflow script and try to pass new hyperparameters
estimator = ?
###Output
_____no_output_____
###Markdown
Before running the actual training on SageMaker TrainingJob, it can be good to run it locally first using the code below. If there is any error, you can fix them first before running using SageMaker TrainingJob.
###Code
#!python3 src/main.py --train data/train --test data/test --output-data-dir data/local-output --model-dir data/local-model --epochs=2 --batch-size=128
# TODO: Call estimator.fit
###Output
_____no_output_____
###Markdown
Deploy and Use Your Model (Real-Time Inference)If your training job has completed; and saved the model in the correct TensorFlow Serving-compatible format; it should now be pretty simple to deploy the model to a real-time endpoint.You can achieve this with the [Estimator API](https://sagemaker.readthedocs.io/en/stable/estimators.html).
###Code
# TODO: Deploy a real-time endpoint
###Output
_____no_output_____
###Markdown
Reviewing the architecture from the example notebook, we set up the model to accept **batches** of **28x28** image tensors with **normalized 0-1 pixel values** and a **color channel dimension** (which either came in front or behind the image dimensions, depending on the value of `K.image_data_format()`)Assuming you haven't added any custom pre-processing to our model source code (to accept e.g. encoded JPEGs/PNGs, or arbitrary shapes), we'll need to replicate that same format when we use our endpoint.We've provided a nice **interactive widget** below (which doesn't work in JupyterLab, unfortunately - only plain Jupyter!) and some skeleton code to help you use your model... But you'll need to fill in some details! WARNING: The next next cells for visualization only works with the classic Jupyter notebooks, skip to the next section if you are using JupyterLab and SageMaker Studio
###Code
# Display interactive widget:
# This widget updates variable "data" here in the Jupyter kernel when drawn on
HTML(open("util/input.html").read())
# Run a prediction:
# Squeeze out any unneeded dimensions from "data", then put back the batch and channel dimensions
# we want (assuming batch dim is first and channel dim is last):
print(f"Raw data shape {np.array(data).shape}")
reqdata = np.expand_dims(np.expand_dims(np.squeeze(data), 2), 0)
print(f"Request data shape {reqdata.shape}")
# TODO: Call the predictor with reqdata
# TODO: What structure is the response? How do we interpret it?
###Output
_____no_output_____
###Markdown
If you are on JupyterLab or SageMaker Studio (or just struggle to get the interactive widget working)...don't worry: Try adapting the "Exploring Results" section from the Local Notebook to send in one of the test set images instead!
###Code
# TODO: import libraries
# TODO: Choose an image
# TODO: Load the image with the tensorflow keras api
img =
# Expand out the "batch" dimension, and before sending to the model
reqdata = np.expand_dims(img, 0)
# Call the predictor with reqdata
result =
# Plot the result:
plt.figure(figsize=(3, 3))
fig = plt.subplot(1, 1, 1)
ax = plt.imshow(np.squeeze(img), cmap="gray")
fig.set_title(f"Predicted Number {np.argmax(result['predictions'][0])}")
plt.show()
###Output
_____no_output_____
###Markdown
Further ImprovementsIf you've got the basic train/deploy/call cycle working, congratulations! This core pattern of experimenting in the notebook but executing jobs on scalable hardware is at the heart of the SageMaker data science workflow.There are still plenty of ways we can use the tools better though: Read on for the next challenges! 1. Cut training costs easily with SageMaker Managed Spot ModeAWS Spot Instances let you take advantage of unused capacity in the AWS cloud, at up to a 90% discount versus standard on-demand pricing! For small jobs like this, taking advantage of this discount is as easy as adding a couple of parameters to the Estimator constructor:https://sagemaker.readthedocs.io/en/stable/estimators.htmlNote that in general, spot capacity is offered at a discounted rate because it's interruptible based on instantaneous demand... Longer-running training jobs should implement checkpoint saving and loading, so that they can efficiently resume if interrupted part way through. More information can be found on the [Managed Spot Training in Amazon SageMaker](https://docs.aws.amazon.com/sagemaker/latest/dg/model-managed-spot-training.html) page of the [SageMaker Developer Guide](https://docs.aws.amazon.com/sagemaker/latest/dg/). 2. Parameterize your algorithmBeing able to change the parameters of your algorithm at run-time (without modifying the `main.py` script each time) is helpful for making your code more re-usable... But even more so because it's a pre-requisite for automatic hyperparameter tuning!Job parameter parsing should ideally be factored into a separate function, and as a best practice should accept setting values through **both** command line flags (as demonstrated in the [official MXNet MNIST example](https://github.com/awslabs/amazon-sagemaker-examples/blob/master/hyperparameter_tuning/mxnet_mnist/mnist.py)) **and** the [SageMaker Hyperparameter environment variable(s)](https://docs.aws.amazon.com/sagemaker/latest/dg/docker-container-environmental-variables-user-scripts.html). Perhaps the official MXNet example could be improved by setting environment-variable-driven defaults to the algorithm hyperparameters, the same as it already does for channels?Refactor your job to accept **epochs** and **batch size** as optional parameters, and show how you can set these before each training run through the [Estimator API](https://sagemaker.readthedocs.io/en/stable/estimators.html). 3. Tune your network hyperparametersRe-use the same approach as before to parameterize some features in the structure of your network: Perhaps the sizes of the `Conv2D` kernels? The number, type, node count, or activation function of layers in the network? No need to stray too far away from the sample architecture!Instead of manually (or programmatically) calling `estimator.fit()` with different hyperparameters each time, we can use SageMaker's Bayesian Hyperparameter Tuning functionality to explore the space more efficiently!The SageMaker SDK Docs give a great [overview](https://sagemaker.readthedocs.io/en/stable/overview.htmlsagemaker-automatic-model-tuning) of using the HyperparameterTuner, which you can refer to if you get stuck.First, we'll need to define a specific **metric** to optimize for, which is really a specification of how to scrape metric values from the algorithm's console logs. Next, use the [\*Parameter](https://sagemaker.readthedocs.io/en/stable/tuner.html) classes (`ContinuousParameter`, `IntegerParameter` and `CategoricalParameter`) to define appropriate ranges for the hyperparameters whose combination you want to optimize.With the original estimator, target metric and parameter ranges defined, you'll be able to create a [HyperparameterTuner](https://sagemaker.readthedocs.io/en/stable/tuner.html) and use that to start a hyperparameter tuning job instead of a single model training job.Pay attention to likely run time and resource consumption when selecting the maximum total number of training jobs and maximum parallel jobs of your hyperparameter tuning run... You can always view and cancel ongoing hyperparameter tuning jobs through the SageMaker Console. Additional ChallengesIf you have time, the following challenges are trickier, and might stretch your SageMaker knowledge even further!**Batch Transform / Additional Inference Formats**: As discussed in this notebook, the deployed endpoint expects a particular tensor data format for requests... This complicates the usually-simple task of re-purposing the same model for batch inference (since our data in S3 is in JPEG format). The SageMaker TensorFlow SDK docs provide guidance on accepting custom formats in the ["Create Python Scripts for Custom Input and Output Formats"](https://sagemaker.readthedocs.io/en/stable/using_tf.htmlcreate-python-scripts-for-custom-input-and-output-formats) section. If you can refactor your algorithm to accept JPEG requests when deployed as a real-time endpoint, you'll be able to run it as a batch [Transformer](https://sagemaker.readthedocs.io/en/stable/transformer.html) against images in S3 with a simple `estimator.transformer()` call.**Optimized Training Formats**: A dataset like this (containing many tiny objects) may take much less time to load in to the algorithm if we either converted it to the standard Numpy format that Keras distributes it in (just 4 files X_train, Y_train, X_test, Y_test); or *streaming* the data with [SageMaker Pipe Mode](https://aws.amazon.com/blogs/machine-learning/using-pipe-input-mode-for-amazon-sagemaker-algorithms/), instead of downloading it up-front.**Experiment Tracking**: The [SageMaker Experiments](https://docs.aws.amazon.com/sagemaker/latest/dg/experiments.html) feature gives a more structured way to track trials across multiple related experiments (for example, different HPO runs, or between HPO and regular model training jobs). You can use the [official SageMaker Experiments Example](https://github.com/awslabs/amazon-sagemaker-examples/tree/master/sagemaker-experiments) for guidance on how to track the experiments in this notebook... and should note that the [SageMaker Experiments SDK Docs](https://sagemaker-experiments.readthedocs.io/en/latest/) are maintained separately, since it's a different Python module. Clean-UpRemember to clean up any persistent resources that aren't needed anymore to save costs: The most significant of these are real-time prediction endpoints, and this SageMaker Notebook Instance.The SageMaker SDK [Predictor](https://sagemaker.readthedocs.io/en/stable/predictors.html) class provides an interface to clean up real-time prediction endpoints; and SageMaker Notebook Instances can be stopped through the SageMaker Console when you're finished.You might also like to clean up any S3 buckets / content we created, to prevent ongoing storage costs.
###Code
# TODO: Clean up any endpoints/etc to release resources
###Output
_____no_output_____
###Markdown
TensorFlow MNIST Lift and Shift Exercise IntroductionYour new colleague in the data science team (who isn't very familiar with SageMaker) has written a nice notebook to tackle an image classification problem with Keras: [Local Notebook.ipynb](Local%20Notebook.ipynb).It works OK with the simple MNIST data set they were working on before, but now they'd like to take advantage of some of the features of SageMaker to tackle bigger and harder challenges.**Can you help refactor the Local Notebook code, to show them how to use SageMaker effectively?** Getting StartedFirst, check you can **run the [Local Notebook.ipynb](Local%20Notebook.ipynb) notebook through** - reviewing what steps it takes.**This notebook** sets out a structure you can use to migrate code into, and lists out some of the changes you'll need to make at a high level. You can either work directly in here, or duplicate this notebook so you still have an unchanged copy of the original.Try to work through the sections first with an MVP goal in mind (fitting the model to data in S3 via a SageMaker Training Job, and deploying/using the model through a SageMaker Endpoint). At the end, there are extension exercises to bring in more advanced functionality. DependenciesListing all our imports at the start helps to keep the requirements to run any script/file transparent up-front, and is specified by nearly every style guide including Python's official [PEP 8](https://www.python.org/dev/peps/pep-0008/imports)
###Code
# External Dependencies:
from IPython.display import display, HTML
# Local Dependencies:
from util.nb import upload_in_background
# TODO: What else will you need?
# TODO: Here might be a good place to init any SDKs you need...
###Output
_____no_output_____
###Markdown
Data PreparationThe primary data source for a SageMaker training job is (nearly) always S3 - so we should upload our training and test data there.We'd like our training job to be reusable for other image classification projects, so we'll upload in the **folders-of-images format** rather than the straight pre-processed numpy arrays.However, for this particular dataset (tens of thousands of tiny files) it's easy to accidentally write a poor-performing upload that **could take a long time**... So we prepared the below to help you run the upload **in the background** using the [aws s3 sync](https://docs.aws.amazon.com/cli/latest/reference/s3/sync.html) CLI command.**Check you understand** what data it's going to upload from this notebook, and where it's going to store it in S3, then start the upload running while you work on the rest.
###Code
upload_in_background(local_path="data", s3_uri="s3://MYBUCKET/MYFOLDERS")
###Output
_____no_output_____
###Markdown
You can carry on working on the other sections while your data uploads! Data Input ("Channels") ConfigurationThe draft code has **2 data sets**: One for training, and one for test/validation. (For classification, the folder location of each image is sufficient as a label).In SageMaker terminology, each input data set is a "channel" and we can name them however we like... Just make sure you're consistent about what you call each one!For a simple input configuration, a channel spec might just be the S3 URI of the folder. For configuring more advanced options, there's the [s3_input](https://sagemaker.readthedocs.io/en/stable/inputs.html) class in the SageMaker SDK.
###Code
# TODO: Define your 2 data channels
###Output
_____no_output_____
###Markdown
Algorithm ("Estimator") Configuration and RunInstead of loading and fitting this data here in the notebook, we'll be creating a [TensorFlow Estimator](https://sagemaker.readthedocs.io/en/stable/sagemaker.tensorflow.htmltensorflow-estimator) through the SageMaker SDK, to run the code on a separate container that can be scaled as required.The ["Using TensorFlow with the SageMaker Python SDK"](https://sagemaker.readthedocs.io/en/stable/using_tf.htmltrain-a-model-with-tensorflow) docs give a good overview of this process. You should run your estimator in **script mode** (which is easier to follow than the old default legacy mode) and as **Python 3**.**Use the [src/main.py](src/main.py) file** as your entry point to port code into - which has already been created for you with some basic hints.
###Code
# TODO: Create your TensorFlow estimator
# Note the TensorFlow class inherits from some cross-framework base classes with additional
# constructor options:
# https://sagemaker.readthedocs.io/en/stable/estimators.html
# TODO: Call estimator.fit
###Output
_____no_output_____
###Markdown
Deploy and Use Your Model (Real-Time Inference)If your training job has completed; and saved the model in the correct TensorFlow Serving-compatible format; it should now be pretty simple to deploy the model to a real-time endpoint.You can achieve this with the [Estimator API](https://sagemaker.readthedocs.io/en/stable/estimators.html).
###Code
# TODO: Deploy a real-time endpoint
###Output
_____no_output_____
###Markdown
Reviewing the architecture from the example notebook, we set up the model to accept **batches** of **28x28** image tensors with **normalized 0-1 pixel values** and a **color channel dimension** (which either came in front or behind the image dimensions, depending on the value of `K.image_data_format()`)Assuming you haven't added any custom pre-processing to our model source code (to accept e.g. encoded JPEGs/PNGs, or arbitrary shapes), we'll need to replicate that same format when we use our endpoint.We've provided a nice **interactive widget** below (which doesn't work in JupyterLab, unfortunately - only plain Jupyter!) and some skeleton code to help you use your model... But you'll need to fill in some details!
###Code
# Display interactive widget:
# This widget updates variable "data" here in the Jupyter kernel when drawn on
HTML(open("util/input.html").read())
# Run a prediction:
# Squeeze out any unneeded dimensions from "data", then put back the batch and channel dimensions
# we want (assuming batch dim is first and channel dim is last):
print(f"Raw data shape {np.array(data).shape}")
reqdata = np.expand_dims(np.expand_dims(np.squeeze(data), 2), 0)
print(f"Request data shape {reqdata.shape}")
# TODO: Call the predictor with reqdata
# TODO: What structure is the response? How do we interpret it?
###Output
_____no_output_____
###Markdown
If you love JupyterLab (or just struggle to get the interactive widget working)...don't worry: Try adapting the "Exploring Results" section from the Local Notebook to send in one of the test set images instead! Further ImprovementsIf you've got the basic train/deploy/call cycle working, congratulations! This core pattern of experimenting in the notebook but executing jobs on scalable hardware is at the heart of the SageMaker data science workflow.There are still plenty of ways we can use the tools better though: Read on for the next challenges! 1. Cut training costs easily with SageMaker Managed Spot ModeAWS Spot Instances let you take advantage of unused capacity in the AWS cloud, at up to a 90% discount versus standard on-demand pricing! For small jobs like this, taking advantage of this discount is as easy as adding a couple of parameters to the Estimator constructor:https://sagemaker.readthedocs.io/en/stable/estimators.htmlNote that in general, spot capacity is offered at a discounted rate because it's interruptible based on instantaneous demand... Longer-running training jobs should implement checkpoint saving and loading, so that they can efficiently resume if interrupted part way through. More information can be found on the [Managed Spot Training in Amazon SageMaker](https://docs.aws.amazon.com/sagemaker/latest/dg/model-managed-spot-training.html) page of the [SageMaker Developer Guide](https://docs.aws.amazon.com/sagemaker/latest/dg/). 2. Parameterize your algorithmBeing able to change the parameters of your algorithm at run-time (without modifying the `main.py` script each time) is helpful for making your code more re-usable... But even more so because it's a pre-requisite for automatic hyperparameter tuning!Job parameter parsing should ideally be factored into a separate function, and as a best practice should accept setting values through **both** command line flags (as demonstrated in the [official MXNet MNIST example](https://github.com/awslabs/amazon-sagemaker-examples/blob/master/hyperparameter_tuning/mxnet_mnist/mnist.py)) **and** the [SageMaker Hyperparameter environment variable(s)](https://docs.aws.amazon.com/sagemaker/latest/dg/docker-container-environmental-variables-user-scripts.html). Perhaps the official MXNet example could be improved by setting environment-variable-driven defaults to the algorithm hyperparameters, the same as it already does for channels?Refactor your job to accept **epochs** and **batch size** as optional parameters, and show how you can set these before each training run through the [Estimator API](https://sagemaker.readthedocs.io/en/stable/estimators.html). 3. Tune your network hyperparametersRe-use the same approach as before to parameterize some features in the structure of your network: Perhaps the sizes of the `Conv2D` kernels? The number, type, node count, or activation function of layers in the network? No need to stray too far away from the sample architecture!Instead of manually (or programmatically) calling `estimator.fit()` with different hyperparameters each time, we can use SageMaker's Bayesian Hyperparameter Tuning functionality to explore the space more efficiently!The SageMaker SDK Docs give a great [overview](https://sagemaker.readthedocs.io/en/stable/overview.htmlsagemaker-automatic-model-tuning) of using the HyperparameterTuner, which you can refer to if you get stuck.First, we'll need to define a specific **metric** to optimize for, which is really a specification of how to scrape metric values from the algorithm's console logs. Next, use the [\*Parameter](https://sagemaker.readthedocs.io/en/stable/tuner.html) classes (`ContinuousParameter`, `IntegerParameter` and `CategoricalParameter`) to define appropriate ranges for the hyperparameters whose combination you want to optimize.With the original estimator, target metric and parameter ranges defined, you'll be able to create a [HyperparameterTuner](https://sagemaker.readthedocs.io/en/stable/tuner.html) and use that to start a hyperparameter tuning job instead of a single model training job.Pay attention to likely run time and resource consumption when selecting the maximum total number of training jobs and maximum parallel jobs of your hyperparameter tuning run... You can always view and cancel ongoing hyperparameter tuning jobs through the SageMaker Console. Additional ChallengesIf you have time, the following challenges are trickier, and might stretch your SageMaker knowledge even further!**Batch Transform / Additional Inference Formats**: As discussed in this notebook, the deployed endpoint expects a particular tensor data format for requests... This complicates the usually-simple task of re-purposing the same model for batch inference (since our data in S3 is in JPEG format). The SageMaker TensorFlow SDK docs provide guidance on accepting custom formats in the ["Create Python Scripts for Custom Input and Output Formats"](https://sagemaker.readthedocs.io/en/stable/using_tf.htmlcreate-python-scripts-for-custom-input-and-output-formats) section. If you can refactor your algorithm to accept JPEG requests when deployed as a real-time endpoint, you'll be able to run it as a batch [Transformer](https://sagemaker.readthedocs.io/en/stable/transformer.html) against images in S3 with a simple `estimator.transformer()` call.**Optimized Training Formats**: A dataset like this (containing many tiny objects) may take much less time to load in to the algorithm if we either converted it to the standard Numpy format that Keras distributes it in (just 4 files X_train, Y_train, X_test, Y_test); or *streaming* the data with [SageMaker Pipe Mode](https://aws.amazon.com/blogs/machine-learning/using-pipe-input-mode-for-amazon-sagemaker-algorithms/), instead of downloading it up-front.**Experiment Tracking**: The new (December 2019) [SageMaker Experiments](https://docs.aws.amazon.com/sagemaker/latest/dg/experiments.html) feature gives a more structured way to track trials across multiple related experiments (for example, different HPO runs, or between HPO and regular model training jobs). You can use the [official SageMaker Experiments Example](https://github.com/awslabs/amazon-sagemaker-examples/tree/master/sagemaker-experiments) for guidance on how to track the experiments in this notebook... and should note that the [SageMaker Experiments SDK Docs](https://sagemaker-experiments.readthedocs.io/en/latest/) are maintained separately, since it's a different Python module. Clean-UpRemember to clean up any persistent resources that aren't needed anymore to save costs: The most significant of these are real-time prediction endpoints, and this SageMaker Notebook Instance.The SageMaker SDK [Predictor](https://sagemaker.readthedocs.io/en/stable/predictors.html) class provides an interface to clean up real-time prediction endpoints; and SageMaker Notebook Instances can be stopped through the SageMaker Console when you're finished.You might also like to clean up any S3 buckets / content we created, to prevent ongoing storage costs.
###Code
# TODO: Clean up any endpoints/etc to release resources
###Output
_____no_output_____
###Markdown
TensorFlow MNIST Lift and Shift ExerciseFor this exercise notebook, you should be able to use the `Python 3 (Data Science)` kernel on SageMaker Studio, or `conda_python3` on classic SageMaker Notebook Instances.--- IntroductionYour new colleague in the data science team (who isn't very familiar with SageMaker) has written a nice notebook to tackle an image classification problem with Keras: [Local Notebook.ipynb](Local%20Notebook.ipynb).It works OK with the simple MNIST data set they were working on before, but now they'd like to take advantage of some of the features of SageMaker to tackle bigger and harder challenges.**Can you help refactor the Local Notebook code, to show them how to use SageMaker effectively?** Getting StartedFirst, check you can **run the [Local Notebook.ipynb](Local%20Notebook.ipynb) notebook through** - reviewing what steps it takes.**This notebook** sets out a structure you can use to migrate code into, and lists out some of the changes you'll need to make at a high level. You can either work directly in here, or duplicate this notebook so you still have an unchanged copy of the original.Try to work through the sections first with an MVP goal in mind (fitting the model to data in S3 via a SageMaker Training Job, and deploying/using the model through a SageMaker Endpoint). At the end, there are extension exercises to bring in more advanced functionality. DependenciesListing all our imports at the start helps to keep the requirements to run any script/file transparent up-front, and is specified by nearly every style guide including Python's official [PEP 8](https://www.python.org/dev/peps/pep-0008/imports)
###Code
# External Dependencies:
from IPython.display import display, HTML
import matplotlib.pyplot as plt
import numpy as np
# Local Dependencies:
from util.nb import upload_in_background
# TODO: What else will you need?
# Have a look at the documentation: https://sagemaker.readthedocs.io/en/stable/frameworks/tensorflow/using_tf.html
# to see which libraries need to be imported to use sagemaker and the tensorflow estimator
# TODO: Here might be a good place to init any SDKs you need...
# 1. Setup the SageMaker role
role = ?
# 2. Setup the SageMaker session
sess = ?
# 3. Setup the SageMaker default bucket
bucket_name = ?
# Have a look at the previous examples to find out how to do it
###Output
_____no_output_____
###Markdown
Data PreparationThe primary data source for a SageMaker training job is (nearly) always S3 - so we should upload our training and test data there.We'd like our training job to be reusable for other image classification projects, so we'll upload in the **folders-of-images format** rather than the straight pre-processed numpy arrays.However, for this particular dataset (tens of thousands of tiny files) it's easy to accidentally write a poor-performing upload that **could take a long time**... So we prepared the below to help you run the upload **in the background** using the [aws s3 sync](https://docs.aws.amazon.com/cli/latest/reference/s3/sync.html) CLI command.**Check you understand** what data it's going to upload from this notebook, and where it's going to store it in S3, then start the upload running while you work on the rest.
###Code
upload_in_background(local_path="data", s3_uri=f"s3://{bucket_name}/mnist")
###Output
_____no_output_____
###Markdown
You can carry on working on the other sections while your data uploads! Data Input ("Channels") ConfigurationThe draft code has **2 data sets**: One for training, and one for test/validation. (For classification, the folder location of each image is sufficient as a label).In SageMaker terminology, each input data set is a "channel" and we can name them however we like... Just make sure you're consistent about what you call each one!For a simple input configuration, a channel spec might just be the S3 URI of the folder. For configuring more advanced options, there's the [s3_input](https://sagemaker.readthedocs.io/en/stable/inputs.html) class in the SageMaker SDK.
###Code
# TODO: Define your 2 data channels
# The data can be found in: "s3://{bucket_name}/mnist/train" and "s3://{bucket_name}/mnist/test"
inputs = # Look at the previous example to see how the inputs were defined
###Output
_____no_output_____
###Markdown
Algorithm ("Estimator") Configuration and RunInstead of loading and fitting this data here in the notebook, we'll be creating a [TensorFlow Estimator](https://sagemaker.readthedocs.io/en/stable/sagemaker.tensorflow.htmltensorflow-estimator) through the SageMaker SDK, to run the code on a separate container that can be scaled as required.The ["Using TensorFlow with the SageMaker Python SDK"](https://sagemaker.readthedocs.io/en/stable/using_tf.htmltrain-a-model-with-tensorflow) docs give a good overview of this process. You should run your estimator in **script mode** (which is easier to follow than the old default legacy mode) and as **Python 3**.**Use the [src/main.py](src/main.py) file** as your entry point to port code into - which has already been created for you with some basic hints.
###Code
# TODO: Create your TensorFlow estimator
# Note the TensorFlow class inherits from some cross-framework base classes with additional
# constructor options:
# https://sagemaker.readthedocs.io/en/stable/estimators.html
# https://sagemaker.readthedocs.io/en/stable/frameworks/tensorflow/using_tf.html?highlight=%20TrainingInput#create-an-estimator
# We are using tensorflow 1.14 and python 3
# You can reuse the metrics definition from the previous example
# (Optional) Look at the Tensorflow script and try to pass new hyperparameters
estimator = ?
# TODO: Call estimator.fit
###Output
_____no_output_____
###Markdown
Deploy and Use Your Model (Real-Time Inference)If your training job has completed; and saved the model in the correct TensorFlow Serving-compatible format; it should now be pretty simple to deploy the model to a real-time endpoint.You can achieve this with the [Estimator API](https://sagemaker.readthedocs.io/en/stable/estimators.html).
###Code
# TODO: Deploy a real-time endpoint
###Output
_____no_output_____
###Markdown
Reviewing the architecture from the example notebook, we set up the model to accept **batches** of **28x28** image tensors with **normalized 0-1 pixel values** and a **color channel dimension** (which either came in front or behind the image dimensions, depending on the value of `K.image_data_format()`)Assuming you haven't added any custom pre-processing to our model source code (to accept e.g. encoded JPEGs/PNGs, or arbitrary shapes), we'll need to replicate that same format when we use our endpoint.We've provided a nice **interactive widget** below (which doesn't work in JupyterLab, unfortunately - only plain Jupyter!) and some skeleton code to help you use your model... But you'll need to fill in some details! WARNING: The next next cells for visualization only works with the classic Jupyter notebooks, skip to the next section if you are using JupyterLab and SageMaker Studio
###Code
# Display interactive widget:
# This widget updates variable "data" here in the Jupyter kernel when drawn on
HTML(open("util/input.html").read())
# Run a prediction:
# Squeeze out any unneeded dimensions from "data", then put back the batch and channel dimensions
# we want (assuming batch dim is first and channel dim is last):
print(f"Raw data shape {np.array(data).shape}")
reqdata = np.expand_dims(np.expand_dims(np.squeeze(data), 2), 0)
print(f"Request data shape {reqdata.shape}")
# TODO: Call the predictor with reqdata
# TODO: What structure is the response? How do we interpret it?
###Output
_____no_output_____
###Markdown
If you are on JupyterLab or SageMaker Studio (or just struggle to get the interactive widget working)...don't worry: Try adapting the "Exploring Results" section from the Local Notebook to send in one of the test set images instead!
###Code
# TODO: import libraries
# TODO: Choose an image
# TODO: Load the image with the tensorflow keras api
img =
# Expand out the "batch" dimension, and before sending to the model
reqdata = np.expand_dims(img, 0)
# Call the predictor with reqdata
result =
# Plot the result:
plt.figure(figsize=(3, 3))
fig = plt.subplot(1, 1, 1)
ax = plt.imshow(np.squeeze(img), cmap="gray")
fig.set_title(f"Predicted Number {np.argmax(result['predictions'][0])}")
plt.show()
###Output
_____no_output_____
###Markdown
Further ImprovementsIf you've got the basic train/deploy/call cycle working, congratulations! This core pattern of experimenting in the notebook but executing jobs on scalable hardware is at the heart of the SageMaker data science workflow.There are still plenty of ways we can use the tools better though: Read on for the next challenges! 1. Cut training costs easily with SageMaker Managed Spot ModeAWS Spot Instances let you take advantage of unused capacity in the AWS cloud, at up to a 90% discount versus standard on-demand pricing! For small jobs like this, taking advantage of this discount is as easy as adding a couple of parameters to the Estimator constructor:https://sagemaker.readthedocs.io/en/stable/estimators.htmlNote that in general, spot capacity is offered at a discounted rate because it's interruptible based on instantaneous demand... Longer-running training jobs should implement checkpoint saving and loading, so that they can efficiently resume if interrupted part way through. More information can be found on the [Managed Spot Training in Amazon SageMaker](https://docs.aws.amazon.com/sagemaker/latest/dg/model-managed-spot-training.html) page of the [SageMaker Developer Guide](https://docs.aws.amazon.com/sagemaker/latest/dg/). 2. Parameterize your algorithmBeing able to change the parameters of your algorithm at run-time (without modifying the `main.py` script each time) is helpful for making your code more re-usable... But even more so because it's a pre-requisite for automatic hyperparameter tuning!Job parameter parsing should ideally be factored into a separate function, and as a best practice should accept setting values through **both** command line flags (as demonstrated in the [official MXNet MNIST example](https://github.com/awslabs/amazon-sagemaker-examples/blob/master/hyperparameter_tuning/mxnet_mnist/mnist.py)) **and** the [SageMaker Hyperparameter environment variable(s)](https://docs.aws.amazon.com/sagemaker/latest/dg/docker-container-environmental-variables-user-scripts.html). Perhaps the official MXNet example could be improved by setting environment-variable-driven defaults to the algorithm hyperparameters, the same as it already does for channels?Refactor your job to accept **epochs** and **batch size** as optional parameters, and show how you can set these before each training run through the [Estimator API](https://sagemaker.readthedocs.io/en/stable/estimators.html). 3. Tune your network hyperparametersRe-use the same approach as before to parameterize some features in the structure of your network: Perhaps the sizes of the `Conv2D` kernels? The number, type, node count, or activation function of layers in the network? No need to stray too far away from the sample architecture!Instead of manually (or programmatically) calling `estimator.fit()` with different hyperparameters each time, we can use SageMaker's Bayesian Hyperparameter Tuning functionality to explore the space more efficiently!The SageMaker SDK Docs give a great [overview](https://sagemaker.readthedocs.io/en/stable/overview.htmlsagemaker-automatic-model-tuning) of using the HyperparameterTuner, which you can refer to if you get stuck.First, we'll need to define a specific **metric** to optimize for, which is really a specification of how to scrape metric values from the algorithm's console logs. Next, use the [\*Parameter](https://sagemaker.readthedocs.io/en/stable/tuner.html) classes (`ContinuousParameter`, `IntegerParameter` and `CategoricalParameter`) to define appropriate ranges for the hyperparameters whose combination you want to optimize.With the original estimator, target metric and parameter ranges defined, you'll be able to create a [HyperparameterTuner](https://sagemaker.readthedocs.io/en/stable/tuner.html) and use that to start a hyperparameter tuning job instead of a single model training job.Pay attention to likely run time and resource consumption when selecting the maximum total number of training jobs and maximum parallel jobs of your hyperparameter tuning run... You can always view and cancel ongoing hyperparameter tuning jobs through the SageMaker Console. Additional ChallengesIf you have time, the following challenges are trickier, and might stretch your SageMaker knowledge even further!**Batch Transform / Additional Inference Formats**: As discussed in this notebook, the deployed endpoint expects a particular tensor data format for requests... This complicates the usually-simple task of re-purposing the same model for batch inference (since our data in S3 is in JPEG format). The SageMaker TensorFlow SDK docs provide guidance on accepting custom formats in the ["Create Python Scripts for Custom Input and Output Formats"](https://sagemaker.readthedocs.io/en/stable/using_tf.htmlcreate-python-scripts-for-custom-input-and-output-formats) section. If you can refactor your algorithm to accept JPEG requests when deployed as a real-time endpoint, you'll be able to run it as a batch [Transformer](https://sagemaker.readthedocs.io/en/stable/transformer.html) against images in S3 with a simple `estimator.transformer()` call.**Optimized Training Formats**: A dataset like this (containing many tiny objects) may take much less time to load in to the algorithm if we either converted it to the standard Numpy format that Keras distributes it in (just 4 files X_train, Y_train, X_test, Y_test); or *streaming* the data with [SageMaker Pipe Mode](https://aws.amazon.com/blogs/machine-learning/using-pipe-input-mode-for-amazon-sagemaker-algorithms/), instead of downloading it up-front.**Experiment Tracking**: The new (December 2019) [SageMaker Experiments](https://docs.aws.amazon.com/sagemaker/latest/dg/experiments.html) feature gives a more structured way to track trials across multiple related experiments (for example, different HPO runs, or between HPO and regular model training jobs). You can use the [official SageMaker Experiments Example](https://github.com/awslabs/amazon-sagemaker-examples/tree/master/sagemaker-experiments) for guidance on how to track the experiments in this notebook... and should note that the [SageMaker Experiments SDK Docs](https://sagemaker-experiments.readthedocs.io/en/latest/) are maintained separately, since it's a different Python module. Clean-UpRemember to clean up any persistent resources that aren't needed anymore to save costs: The most significant of these are real-time prediction endpoints, and this SageMaker Notebook Instance.The SageMaker SDK [Predictor](https://sagemaker.readthedocs.io/en/stable/predictors.html) class provides an interface to clean up real-time prediction endpoints; and SageMaker Notebook Instances can be stopped through the SageMaker Console when you're finished.You might also like to clean up any S3 buckets / content we created, to prevent ongoing storage costs.
###Code
# TODO: Clean up any endpoints/etc to release resources
###Output
_____no_output_____
###Markdown
TensorFlow MNIST Lift and Shift ExerciseFor this exercise notebook, you should be able to use the `Python 3 (TensorFlow 1.15 Python 3.7 CPU Optimized)` kernel on SageMaker Studio, or `conda_tensorflow_p36` on classic SageMaker Notebook Instances.--- IntroductionYour new colleague in the data science team (who isn't very familiar with SageMaker) has written a nice notebook to tackle an image classification problem with Keras: [Local Notebook.ipynb](Local%20Notebook.ipynb).It works OK with the simple MNIST data set they were working on before, but now they'd like to take advantage of some of the features of SageMaker to tackle bigger and harder challenges.**Can you help refactor the Local Notebook code, to show them how to use SageMaker effectively?** Getting StartedFirst, check you can **run the [Local Notebook.ipynb](Local%20Notebook.ipynb) notebook through** - reviewing what steps it takes.**This notebook** sets out a structure you can use to migrate code into, and lists out some of the changes you'll need to make at a high level. You can either work directly in here, or duplicate this notebook so you still have an unchanged copy of the original.Try to work through the sections first with an MVP goal in mind (fitting the model to data in S3 via a SageMaker Training Job, and deploying/using the model through a SageMaker Endpoint). At the end, there are extension exercises to bring in more advanced functionality. DependenciesListing all our imports at the start helps to keep the requirements to run any script/file transparent up-front, and is specified by nearly every style guide including Python's official [PEP 8](https://www.python.org/dev/peps/pep-0008/imports)
###Code
!pip install matplotlib
!pip install ipywidgets
# External Dependencies:
from IPython.display import display, HTML
import matplotlib.pyplot as plt
import numpy as np
# Local Dependencies:
from util.nb import upload_in_background
# TODO: What else will you need?
# Have a look at the documentation: https://sagemaker.readthedocs.io/en/stable/frameworks/tensorflow/using_tf.html
# to see which libraries need to be imported to use sagemaker and the tensorflow estimator
# TODO: Here might be a good place to init any SDKs you need...
# 1. Setup the SageMaker role
role = ?
# 2. Setup the SageMaker session
sess = ?
# 3. Setup the SageMaker default bucket
bucket_name = ?
# Have a look at the previous examples to find out how to do it
###Output
_____no_output_____
###Markdown
Data PreparationThe primary data source for a SageMaker training job is (nearly) always S3 - so we should upload our training and test data there.We'd like our training job to be reusable for other image classification projects, so we'll upload in the **folders-of-images format** rather than the straight pre-processed numpy arrays.However, for this particular dataset (tens of thousands of tiny files) it's easy to accidentally write a poor-performing upload that **could take a long time**... So we prepared the below to help you run the upload **in the background** using the [aws s3 sync](https://docs.aws.amazon.com/cli/latest/reference/s3/sync.html) CLI command.**Check you understand** what data it's going to upload from this notebook, and where it's going to store it in S3, then start the upload running while you work on the rest.
###Code
upload_in_background(local_path="data", s3_uri=f"s3://{bucket_name}/mnist")
###Output
_____no_output_____
###Markdown
You can carry on working on the other sections while your data uploads! Data Input ("Channels") ConfigurationThe draft code has **2 data sets**: One for training, and one for test/validation. (For classification, the folder location of each image is sufficient as a label).In SageMaker terminology, each input data set is a "channel" and we can name them however we like... Just make sure you're consistent about what you call each one!For a simple input configuration, a channel spec might just be the S3 URI of the folder. For configuring more advanced options, there's the [s3_input](https://sagemaker.readthedocs.io/en/stable/inputs.html) class in the SageMaker SDK.
###Code
# TODO: Define your 2 data channels
# The data can be found in: "s3://{bucket_name}/mnist/train" and "s3://{bucket_name}/mnist/test"
inputs = # Look at the previous example to see how the inputs were defined
###Output
_____no_output_____
###Markdown
Algorithm ("Estimator") Configuration and RunInstead of loading and fitting this data here in the notebook, we'll be creating a [TensorFlow Estimator](https://sagemaker.readthedocs.io/en/stable/sagemaker.tensorflow.htmltensorflow-estimator) through the SageMaker SDK, to run the code on a separate container that can be scaled as required.The ["Using TensorFlow with the SageMaker Python SDK"](https://sagemaker.readthedocs.io/en/stable/using_tf.htmltrain-a-model-with-tensorflow) docs give a good overview of this process. You should run your estimator in **script mode** (which is easier to follow than the old default legacy mode) and as **Python 3**.**Use the [src/main.py](src/main.py) file** as your entry point to port code into - which has already been created for you with some basic hints.
###Code
# TODO: Create your TensorFlow estimator
# Note the TensorFlow class inherits from some cross-framework base classes with additional
# constructor options:
# https://sagemaker.readthedocs.io/en/stable/estimators.html
# https://sagemaker.readthedocs.io/en/stable/frameworks/tensorflow/using_tf.html?highlight=%20TrainingInput#create-an-estimator
# We are using tensorflow 1.14 and python 3
# You can reuse the metrics definition from the previous example
# (Optional) Look at the Tensorflow script and try to pass new hyperparameters
estimator = ?
###Output
_____no_output_____
###Markdown
Before running the actual training on SageMaker TrainingJob, it can be good to run it locally first using the code below. If there is any error, you can fix them first before running using SageMaker TrainingJob.
###Code
#!python3 src/main.py --train data/train --test data/test --output-data-dir data/local-output --model-dir data/local-model --epochs=2 --batch-size=128
# TODO: Call estimator.fit
###Output
_____no_output_____
###Markdown
Deploy and Use Your Model (Real-Time Inference)If your training job has completed; and saved the model in the correct TensorFlow Serving-compatible format; it should now be pretty simple to deploy the model to a real-time endpoint.You can achieve this with the [Estimator API](https://sagemaker.readthedocs.io/en/stable/estimators.html).
###Code
# TODO: Deploy a real-time endpoint
###Output
_____no_output_____
###Markdown
Reviewing the architecture from the example notebook, we set up the model to accept **batches** of **28x28** image tensors with **normalized 0-1 pixel values** and a **color channel dimension** (which either came in front or behind the image dimensions, depending on the value of `K.image_data_format()`)Assuming you haven't added any custom pre-processing to our model source code (to accept e.g. encoded JPEGs/PNGs, or arbitrary shapes), we'll need to replicate that same format when we use our endpoint.We've provided a nice **interactive widget** below (which doesn't work in JupyterLab, unfortunately - only plain Jupyter!) and some skeleton code to help you use your model... But you'll need to fill in some details! WARNING: The next next cells for visualization only works with the classic Jupyter notebooks, skip to the next section if you are using JupyterLab and SageMaker Studio
###Code
# Display interactive widget:
# This widget updates variable "data" here in the Jupyter kernel when drawn on
HTML(open("util/input.html").read())
# Run a prediction:
# Squeeze out any unneeded dimensions from "data", then put back the batch and channel dimensions
# we want (assuming batch dim is first and channel dim is last):
print(f"Raw data shape {np.array(data).shape}")
reqdata = np.expand_dims(np.expand_dims(np.squeeze(data), 2), 0)
print(f"Request data shape {reqdata.shape}")
# TODO: Call the predictor with reqdata
# TODO: What structure is the response? How do we interpret it?
###Output
_____no_output_____
###Markdown
If you are on JupyterLab or SageMaker Studio (or just struggle to get the interactive widget working)...don't worry: Try adapting the "Exploring Results" section from the Local Notebook to send in one of the test set images instead!
###Code
# TODO: import libraries
# TODO: Choose an image
# TODO: Load the image with the tensorflow keras api
img =
# Expand out the "batch" dimension, and before sending to the model
reqdata = np.expand_dims(img, 0)
# Call the predictor with reqdata
result =
# Plot the result:
plt.figure(figsize=(3, 3))
fig = plt.subplot(1, 1, 1)
ax = plt.imshow(np.squeeze(img), cmap="gray")
fig.set_title(f"Predicted Number {np.argmax(result['predictions'][0])}")
plt.show()
###Output
_____no_output_____
###Markdown
Further ImprovementsIf you've got the basic train/deploy/call cycle working, congratulations! This core pattern of experimenting in the notebook but executing jobs on scalable hardware is at the heart of the SageMaker data science workflow.There are still plenty of ways we can use the tools better though: Read on for the next challenges! 1. Cut training costs easily with SageMaker Managed Spot ModeAWS Spot Instances let you take advantage of unused capacity in the AWS cloud, at up to a 90% discount versus standard on-demand pricing! For small jobs like this, taking advantage of this discount is as easy as adding a couple of parameters to the Estimator constructor:https://sagemaker.readthedocs.io/en/stable/estimators.htmlNote that in general, spot capacity is offered at a discounted rate because it's interruptible based on instantaneous demand... Longer-running training jobs should implement checkpoint saving and loading, so that they can efficiently resume if interrupted part way through. More information can be found on the [Managed Spot Training in Amazon SageMaker](https://docs.aws.amazon.com/sagemaker/latest/dg/model-managed-spot-training.html) page of the [SageMaker Developer Guide](https://docs.aws.amazon.com/sagemaker/latest/dg/). 2. Parameterize your algorithmBeing able to change the parameters of your algorithm at run-time (without modifying the `main.py` script each time) is helpful for making your code more re-usable... But even more so because it's a pre-requisite for automatic hyperparameter tuning!Job parameter parsing should ideally be factored into a separate function, and as a best practice should accept setting values through **both** command line flags (as demonstrated in the [official MXNet MNIST example](https://github.com/awslabs/amazon-sagemaker-examples/blob/master/hyperparameter_tuning/mxnet_mnist/mnist.py)) **and** the [SageMaker Hyperparameter environment variable(s)](https://docs.aws.amazon.com/sagemaker/latest/dg/docker-container-environmental-variables-user-scripts.html). Perhaps the official MXNet example could be improved by setting environment-variable-driven defaults to the algorithm hyperparameters, the same as it already does for channels?Refactor your job to accept **epochs** and **batch size** as optional parameters, and show how you can set these before each training run through the [Estimator API](https://sagemaker.readthedocs.io/en/stable/estimators.html). 3. Tune your network hyperparametersRe-use the same approach as before to parameterize some features in the structure of your network: Perhaps the sizes of the `Conv2D` kernels? The number, type, node count, or activation function of layers in the network? No need to stray too far away from the sample architecture!Instead of manually (or programmatically) calling `estimator.fit()` with different hyperparameters each time, we can use SageMaker's Bayesian Hyperparameter Tuning functionality to explore the space more efficiently!The SageMaker SDK Docs give a great [overview](https://sagemaker.readthedocs.io/en/stable/overview.htmlsagemaker-automatic-model-tuning) of using the HyperparameterTuner, which you can refer to if you get stuck.First, we'll need to define a specific **metric** to optimize for, which is really a specification of how to scrape metric values from the algorithm's console logs. Next, use the [\*Parameter](https://sagemaker.readthedocs.io/en/stable/tuner.html) classes (`ContinuousParameter`, `IntegerParameter` and `CategoricalParameter`) to define appropriate ranges for the hyperparameters whose combination you want to optimize.With the original estimator, target metric and parameter ranges defined, you'll be able to create a [HyperparameterTuner](https://sagemaker.readthedocs.io/en/stable/tuner.html) and use that to start a hyperparameter tuning job instead of a single model training job.Pay attention to likely run time and resource consumption when selecting the maximum total number of training jobs and maximum parallel jobs of your hyperparameter tuning run... You can always view and cancel ongoing hyperparameter tuning jobs through the SageMaker Console. Additional ChallengesIf you have time, the following challenges are trickier, and might stretch your SageMaker knowledge even further!**Batch Transform / Additional Inference Formats**: As discussed in this notebook, the deployed endpoint expects a particular tensor data format for requests... This complicates the usually-simple task of re-purposing the same model for batch inference (since our data in S3 is in JPEG format). The SageMaker TensorFlow SDK docs provide guidance on accepting custom formats in the ["Create Python Scripts for Custom Input and Output Formats"](https://sagemaker.readthedocs.io/en/stable/using_tf.htmlcreate-python-scripts-for-custom-input-and-output-formats) section. If you can refactor your algorithm to accept JPEG requests when deployed as a real-time endpoint, you'll be able to run it as a batch [Transformer](https://sagemaker.readthedocs.io/en/stable/transformer.html) against images in S3 with a simple `estimator.transformer()` call.**Optimized Training Formats**: A dataset like this (containing many tiny objects) may take much less time to load in to the algorithm if we either converted it to the standard Numpy format that Keras distributes it in (just 4 files X_train, Y_train, X_test, Y_test); or *streaming* the data with [SageMaker Pipe Mode](https://aws.amazon.com/blogs/machine-learning/using-pipe-input-mode-for-amazon-sagemaker-algorithms/), instead of downloading it up-front.**Experiment Tracking**: The new (December 2019) [SageMaker Experiments](https://docs.aws.amazon.com/sagemaker/latest/dg/experiments.html) feature gives a more structured way to track trials across multiple related experiments (for example, different HPO runs, or between HPO and regular model training jobs). You can use the [official SageMaker Experiments Example](https://github.com/awslabs/amazon-sagemaker-examples/tree/master/sagemaker-experiments) for guidance on how to track the experiments in this notebook... and should note that the [SageMaker Experiments SDK Docs](https://sagemaker-experiments.readthedocs.io/en/latest/) are maintained separately, since it's a different Python module. Clean-UpRemember to clean up any persistent resources that aren't needed anymore to save costs: The most significant of these are real-time prediction endpoints, and this SageMaker Notebook Instance.The SageMaker SDK [Predictor](https://sagemaker.readthedocs.io/en/stable/predictors.html) class provides an interface to clean up real-time prediction endpoints; and SageMaker Notebook Instances can be stopped through the SageMaker Console when you're finished.You might also like to clean up any S3 buckets / content we created, to prevent ongoing storage costs.
###Code
# TODO: Clean up any endpoints/etc to release resources
###Output
_____no_output_____
###Markdown
TensorFlow MNIST Lift and Shift ExerciseFor this exercise notebook, you should be able to use the `Python 3 (TensorFlow 2.3 Python 3.7 CPU Optimized)` kernel on SageMaker Studio, or `conda_tensorflow2_p37` on classic SageMaker Notebook Instances.--- IntroductionYour new colleague in the data science team (who isn't very familiar with SageMaker) has written a nice notebook to tackle an image classification problem with Keras: [Local Notebook.ipynb](Local%20Notebook.ipynb).It works OK with the simple MNIST data set they were working on before, but now they'd like to take advantage of some of the features of SageMaker to tackle bigger and harder challenges.**Can you help refactor the Local Notebook code, to show them how to use SageMaker effectively?** Getting StartedFirst, check you can **run the [Local Notebook.ipynb](Local%20Notebook.ipynb) notebook through** - reviewing what steps it takes.**This notebook** sets out a structure you can use to migrate code into, and lists out some of the changes you'll need to make at a high level. You can either work directly in here, or duplicate this notebook so you still have an unchanged copy of the original.Try to work through the sections first with an MVP goal in mind (fitting the model to data in S3 via a SageMaker Training Job, and deploying/using the model through a SageMaker Endpoint). At the end, there are extension exercises to bring in more advanced functionality. DependenciesListing all our imports at the start helps to keep the requirements to run any script/file transparent up-front, and is specified by nearly every style guide including Python's official [PEP 8](https://www.python.org/dev/peps/pep-0008/imports)
###Code
!pip install ipywidgets matplotlib
%load_ext autoreload
%autoreload 2
# Python Built-Ins:
import glob
import os
# External Dependencies:
from IPython.display import display, HTML
import matplotlib.pyplot as plt
import numpy as np
# TODO: What else will you need?
# Have a look at the documentation: https://sagemaker.readthedocs.io/en/stable/frameworks/tensorflow/using_tf.html
# to see which libraries need to be imported to use sagemaker and the tensorflow estimator
###Output
_____no_output_____
###Markdown
Prepare the DataLet's download the image data from the Repository of Open Data on AWS and sample a subset like we did in the [Local Notebook.ipynb](Local%20Notebook.ipynb).**Check you understand** what data it's going to upload from this notebook, and where it's going to store it in S3, then start the upload running.
###Code
local_dir = "/tmp/mnist"
training_dir = f"{local_dir}/training"
testing_dir = f"{local_dir}/testing"
# Download the MNIST data from the Registry of Open Data on AWS
!rm -rf {local_dir}
!mkdir -p {local_dir}
!aws s3 cp s3://fast-ai-imageclas/mnist_png.tgz {local_dir} --no-sign-request
# Un-tar the MNIST data, stripping the leading path element; this will leave us with directories
# {local_dir}/testing/ and {local_dir/training/
!tar zxf {local_dir}/mnist_png.tgz -C {local_dir}/ --strip-components=1 --no-same-owner
# Get the list of files in tne training and testing directories recursively
train_files = sorted(list(glob.iglob(os.path.join(training_dir, "*/*.png"), recursive=True)))
test_files = sorted(list(glob.iglob(os.path.join(testing_dir, "*/*.png"), recursive=True)))
print(f"Training files: {len(train_files)}")
print(f"Testing files: {len(test_files)}")
# Reduce the data by keeping every Nth file and dropping the rest of the files.
reduction_factor = 2
train_files_to_keep = train_files[::reduction_factor]
test_files_to_keep = test_files[::reduction_factor]
print(f"Training files kept: {len(train_files_to_keep)}")
print(f"Testing files kept: {len(test_files_to_keep)}")
# Delete all the files not to be kept
for fname in (set(train_files) ^ set(train_files_to_keep)):
os.remove(fname)
for fname in (set(test_files) ^ set(test_files_to_keep)):
os.remove(fname)
print("Done!")
###Output
_____no_output_____
###Markdown
Set Up Execution Role, Session and S3 BucketNow that we have downloaded and reduced the data in the local directory, we will need to upload it to Amazon S3 to make it available for Amazon Sagemaker training. Let's start by specifying:- The S3 bucket and prefix that you want to use for training and model data. This should be within the same region as the Notebook Instance, training, and hosting. If you don't specify a bucket, SageMaker SDK will create a default bucket following a pre-defined naming convention in the same region. - The IAM role ARN used to give SageMaker access to your data. It can be fetched using the **get_execution_role** method from sagemaker python SDK.
###Code
# TODO: This is where you can setup execution role, session and S3 bucket.
# 1. Setup the SageMaker role
role = ?
# 2. Setup the SageMaker session
sess = ?
# 3. Setup the SageMaker default bucket
bucket_name = ?
# Have a look at the previous examples to find out how to do it
###Output
_____no_output_____
###Markdown
Upload Data to Amazon S3Next is the part where you need to upload the images to Amazon S3 for Sagemaker training. You can refer to the previous example on how to do it using the [aws s3 sync](https://docs.aws.amazon.com/cli/latest/reference/s3/sync.html) CLI command. The high-level command ```aws s3 sync``` command synchronizes the contents of the target bucket and source directory. It allows the use of options such as ```--delete``` that allows to remove objects from the target that are not present in the source and ```--exclude``` or ```--include``` options that filter files or objects to exclude or not exclude.> ⏰ **Note:** Uploading to Amazon S3 typically takes about 2-3 minutes assuming a `reduction_factor` of 2
###Code
# TODO: This is where you upload the training images using `aws s3 sync`.
# Fill in the missing source local directory and the target S3 bucket and folder in the command below.
!aws s3 sync --quiet --delete ??? ??? --exclude "*.tgz" && echo "Done!"
###Output
_____no_output_____
###Markdown
You can check your data is uploaded by finding your bucket in the [Amazon S3 Console](https://s3.console.aws.amazon.com/s3/home). Do you see the folders of images as expected? Data Input ("Channels") ConfigurationThe draft code has **2 data sets**: One for training, and one for test/validation. (For classification, the folder location of each image is sufficient as a label).In SageMaker terminology, each input data set is a "channel" and we can name them however we like... Just make sure you're consistent about what you call each one!For a simple input configuration, a channel spec might just be the S3 URI of the folder. For configuring more advanced options, there's the [s3_input](https://sagemaker.readthedocs.io/en/stable/inputs.html) class in the SageMaker SDK.
###Code
# TODO: Define your 2 data channels
# The data can be found in: "s3://{bucket_name}/mnist/training" and "s3://{bucket_name}/mnist/testing"
inputs = # Look at the previous example to see how the inputs were defined
###Output
_____no_output_____
###Markdown
Algorithm ("Estimator") Configuration and RunInstead of loading and fitting this data here in the notebook, we'll be creating a [TensorFlow Estimator](https://sagemaker.readthedocs.io/en/stable/sagemaker.tensorflow.htmltensorflow-estimator) through the SageMaker SDK, to run the code on a separate container that can be scaled as required.The ["Using TensorFlow with the SageMaker Python SDK"](https://sagemaker.readthedocs.io/en/stable/using_tf.htmltrain-a-model-with-tensorflow) docs give a good overview of this process. You should run your estimator in **script mode** (which is easier to follow than the old default legacy mode) and as **Python 3**.**Use the [src/main.py](src/main.py) file** as your entry point to port code into - which has already been created for you with some basic hints.
###Code
# TODO: Create your TensorFlow estimator
# Note the TensorFlow class inherits from some cross-framework base classes with additional
# constructor options:
# https://sagemaker.readthedocs.io/en/stable/estimators.html
# https://sagemaker.readthedocs.io/en/stable/frameworks/tensorflow/using_tf.html?highlight=%20TrainingInput#create-an-estimator
# We are using tensorflow 1.14 and python 3
# You can reuse the metrics definition from the previous example
# (Optional) Look at the Tensorflow script and try to pass new hyperparameters
estimator = ?
###Output
_____no_output_____
###Markdown
Before running the actual training on SageMaker TrainingJob, it can be good to run it locally first using the code below. If there is any error, you can fix them first before running using SageMaker TrainingJob.
###Code
!python3 src/main.py --train {training_dir} --test {testing_dir} --output-data-dir data/local-output --model-dir data/local-model --epochs=1 --batch-size=128
###Output
_____no_output_____
###Markdown
When you're ready to try your script in a SageMaker training job, you can call `estimator.fit()` as we did in previous exercises:
###Code
# TODO: Call estimator.fit
###Output
_____no_output_____
###Markdown
Deploy and Use Your Model (Real-Time Inference)If your training job has completed; and saved the model in the correct TensorFlow Serving-compatible format; it should now be pretty simple to deploy the model to a real-time endpoint.You can achieve this with the [Estimator API](https://sagemaker.readthedocs.io/en/stable/estimators.html).
###Code
# TODO: Deploy a real-time endpoint
###Output
_____no_output_____
###Markdown
Reviewing the architecture from the example notebook, we set up the model to accept **batches** of **28x28** image tensors with **normalized 0-1 pixel values** and a **color channel dimension** (which either came in front or behind the image dimensions, depending on the value of `K.image_data_format()`)Assuming you haven't added any custom pre-processing to our model source code (to accept e.g. encoded JPEGs/PNGs, or arbitrary shapes), we'll need to replicate that same format when we use our endpoint.We've provided a nice **interactive widget** below (which doesn't work in JupyterLab, unfortunately - only plain Jupyter!) and some skeleton code to help you use your model... But you'll need to fill in some details! WARNING: The next next cells for visualization only works with the classic Jupyter notebooks, skip to the next section if you are using JupyterLab and SageMaker Studio
###Code
# Display interactive widget:
# This widget updates variable "data" here in the Jupyter kernel when drawn on
HTML(open("util/input.html").read())
# Run a prediction:
# Squeeze out any unneeded dimensions from "data", then put back the batch and channel dimensions
# we want (assuming batch dim is first and channel dim is last):
print(f"Raw data shape {np.array(data).shape}")
reqdata = np.expand_dims(np.expand_dims(np.squeeze(data), 2), 0)
print(f"Request data shape {reqdata.shape}")
# TODO: Call the predictor with reqdata
# TODO: What structure is the response? How do we interpret it?
###Output
_____no_output_____
###Markdown
If you are on JupyterLab or SageMaker Studio (or just struggle to get the interactive widget working)...don't worry: Try adapting the "Exploring Results" section from the Local Notebook to send in one of the test set images instead!
###Code
# TODO: import libraries
# TODO: Choose an image
# TODO: Load the image with the tensorflow keras api
img =
# Expand out the "batch" dimension, and before sending to the model
reqdata = np.expand_dims(img, 0)
# Call the predictor with reqdata
result =
# Plot the result:
plt.figure(figsize=(3, 3))
fig = plt.subplot(1, 1, 1)
ax = plt.imshow(np.squeeze(img), cmap="gray")
fig.set_title(f"Predicted Number {np.argmax(result['predictions'][0])}")
plt.show()
###Output
_____no_output_____
###Markdown
Further ImprovementsIf you've got the basic train/deploy/call cycle working, congratulations! This core pattern of experimenting in the notebook but executing jobs on scalable hardware is at the heart of the SageMaker data science workflow.There are still plenty of ways we can use the tools better though: Read on for the next challenges! 1. Cut training costs easily with SageMaker Managed Spot ModeAWS Spot Instances let you take advantage of unused capacity in the AWS cloud, at up to a 90% discount versus standard on-demand pricing! For small jobs like this, taking advantage of this discount is as easy as adding a couple of parameters to the Estimator constructor:https://sagemaker.readthedocs.io/en/stable/estimators.htmlNote that in general, spot capacity is offered at a discounted rate because it's interruptible based on instantaneous demand... Longer-running training jobs should implement checkpoint saving and loading, so that they can efficiently resume if interrupted part way through. More information can be found on the [Managed Spot Training in Amazon SageMaker](https://docs.aws.amazon.com/sagemaker/latest/dg/model-managed-spot-training.html) page of the [SageMaker Developer Guide](https://docs.aws.amazon.com/sagemaker/latest/dg/). 2. Parameterize your algorithmBeing able to change the parameters of your algorithm at run-time (without modifying the `main.py` script each time) is helpful for making your code more re-usable... But even more so because it's a pre-requisite for automatic hyperparameter tuning!Job parameter parsing should ideally be factored into a separate function, and as a best practice should accept setting values through **both** command line flags (as demonstrated in the [official MXNet MNIST example](https://github.com/awslabs/amazon-sagemaker-examples/blob/master/hyperparameter_tuning/mxnet_mnist/mnist.py)) **and** the [SageMaker Hyperparameter environment variable(s)](https://docs.aws.amazon.com/sagemaker/latest/dg/docker-container-environmental-variables-user-scripts.html). Perhaps the official MXNet example could be improved by setting environment-variable-driven defaults to the algorithm hyperparameters, the same as it already does for channels?Refactor your job to accept **epochs** and **batch size** as optional parameters, and show how you can set these before each training run through the [Estimator API](https://sagemaker.readthedocs.io/en/stable/estimators.html). 3. Tune your network hyperparametersRe-use the same approach as before to parameterize some features in the structure of your network: Perhaps the sizes of the `Conv2D` kernels? The number, type, node count, or activation function of layers in the network? No need to stray too far away from the sample architecture!Instead of manually (or programmatically) calling `estimator.fit()` with different hyperparameters each time, we can use SageMaker's Bayesian Hyperparameter Tuning functionality to explore the space more efficiently!The SageMaker SDK Docs give a great [overview](https://sagemaker.readthedocs.io/en/stable/overview.htmlsagemaker-automatic-model-tuning) of using the HyperparameterTuner, which you can refer to if you get stuck.First, we'll need to define a specific **metric** to optimize for, which is really a specification of how to scrape metric values from the algorithm's console logs. Next, use the [\*Parameter](https://sagemaker.readthedocs.io/en/stable/tuner.html) classes (`ContinuousParameter`, `IntegerParameter` and `CategoricalParameter`) to define appropriate ranges for the hyperparameters whose combination you want to optimize.With the original estimator, target metric and parameter ranges defined, you'll be able to create a [HyperparameterTuner](https://sagemaker.readthedocs.io/en/stable/tuner.html) and use that to start a hyperparameter tuning job instead of a single model training job.Pay attention to likely run time and resource consumption when selecting the maximum total number of training jobs and maximum parallel jobs of your hyperparameter tuning run... You can always view and cancel ongoing hyperparameter tuning jobs through the SageMaker Console. Additional ChallengesIf you have time, the following challenges are trickier, and might stretch your SageMaker knowledge even further!**Batch Transform / Additional Inference Formats**: As discussed in this notebook, the deployed endpoint expects a particular tensor data format for requests... This complicates the usually-simple task of re-purposing the same model for batch inference (since our data in S3 is in JPEG format). The SageMaker TensorFlow SDK docs provide guidance on accepting custom formats in the ["Create Python Scripts for Custom Input and Output Formats"](https://sagemaker.readthedocs.io/en/stable/using_tf.htmlcreate-python-scripts-for-custom-input-and-output-formats) section. If you can refactor your algorithm to accept JPEG requests when deployed as a real-time endpoint, you'll be able to run it as a batch [Transformer](https://sagemaker.readthedocs.io/en/stable/transformer.html) against images in S3 with a simple `estimator.transformer()` call.**Optimized Training Formats**: A dataset like this (containing many tiny objects) may take much less time to load in to the algorithm if we either converted it to the standard Numpy format that Keras distributes it in (just 4 files X_train, Y_train, X_test, Y_test); or *streaming* the data with [SageMaker Pipe Mode](https://aws.amazon.com/blogs/machine-learning/using-pipe-input-mode-for-amazon-sagemaker-algorithms/), instead of downloading it up-front.**Experiment Tracking**: The [SageMaker Experiments](https://docs.aws.amazon.com/sagemaker/latest/dg/experiments.html) feature gives a more structured way to track trials across multiple related experiments (for example, different HPO runs, or between HPO and regular model training jobs). You can use the [official SageMaker Experiments Example](https://github.com/awslabs/amazon-sagemaker-examples/tree/master/sagemaker-experiments) for guidance on how to track the experiments in this notebook... and should note that the [SageMaker Experiments SDK Docs](https://sagemaker-experiments.readthedocs.io/en/latest/) are maintained separately, since it's a different Python module. Clean-UpRemember to clean up any persistent resources that aren't needed anymore to save costs: The most significant of these are real-time prediction endpoints, and this SageMaker Notebook Instance.The SageMaker SDK [Predictor](https://sagemaker.readthedocs.io/en/stable/predictors.html) class provides an interface to clean up real-time prediction endpoints; and SageMaker Notebook Instances can be stopped through the SageMaker Console when you're finished.You might also like to clean up any S3 buckets / content we created, to prevent ongoing storage costs.
###Code
# TODO: Clean up any endpoints/etc to release resources
###Output
_____no_output_____ |
utility_functions.ipynb | ###Markdown
Load Models
###Code
# Load the TFKLD Model, we'll be training the PCA Reduction on the vectors it outputs
tfkld_model = joblib.load(tfkld_location)
# Load PCA
pca_model = joblib.load(pca_location)
###Output
_____no_output_____
###Markdown
Utility functions for sentence similarity tfkld vectors
###Code
# Creates a vector that is the mean of the vectors of all of the passed sentences
def mean_sentences_vector(sentences):
vec_list = tfkld_model.transform(sentences)
if len(sentences) > 1:
array_to_convert = []
for vec in vec_list:
array_to_convert.append(vec.toarray()[0].tolist())
mean_vector = np.mean(np.array(array_to_convert), axis=0, dtype=np.float64).tolist()
else:
mean_vector = vec_list[0].toarray()[0].tolist()
return pca_model.transform([mean_vector])[0].tolist()
def vectorize_sentences(sentences):
vec_sentences = []
vec_list = tfkld_model.transform(sentences)
for vec in vec_list:
vec_sentences.append(pca_model.transform([vec.toarray()[0].tolist()])[0].tolist())
return vec_sentences
# Takes a list of sentences and adds them to the sentence dictionary
def increase_sentence_vector(sentences, sentence_dict={}):
for index, sent_vec in enumerate(tfkld_model.transform(sentences)):
sentence_dict[sentences[index]] = pca_model.transform([sent_vec.toarray()[0].tolist()])
return sentence_dict
# This will take a list of text and convert it into a sentence vector
def vectorize_document_list(documents, sentence_dict={}):
for doc in documents:
sentence_dict = increase_sentence_vector(sent_tokenize(doc), sentence_dict)
return sentence_dict
# Get the sentences whose cosine similarity is closest to the passed sentence
def get_most_similar_sentences(sentence_dict, sentence, tnum=5):
sentences_to_return = []
sent_vect = vectorize_sentences([sentence])[0]
lowest_distance = 0
for sent, vector in sentence_dict.iteritems():
similarity = cosine_similarity(np.array(vector).reshape(1, -1), np.array(sent_vect).reshape(1, -1)).tolist()[0][0]
if len(sentences_to_return) < tnum:
sentences_to_return.append((sent, similarity))
if lowest_distance > similarity:
lowest_distance = similarity
else:
if lowest_distance < similarity:
new_lowest_distance = similarity
for index, existing_sent in enumerate(sentences_to_return):
if existing_sent[1] == lowest_distance:
sentences_to_return[index] = (sent, similarity)
elif existing_sent[1] < new_lowest_distance:
new_lowest_distance = existing_sent[1]
lowest_distance = new_lowest_distance
sentences_to_return.sort(key=lambda x: x[1], reverse=True)
return sentences_to_return
# Gets the sentences that are closest to the passed vector.
def get_most_similar_sentences_to_vector(sentence_dict, mean_vector, tnum=5):
sentences_to_return = []
lowest_distance = 0
for sent, vector in sentence_dict.iteritems():
similarity = cosine_similarity(np.array(vector).reshape(1, -1), np.array(mean_vector).reshape(1, -1)).tolist()[0][0]
if len(sentences_to_return) < tnum:
sentences_to_return.append((sent, similarity))
if lowest_distance > similarity:
lowest_distance = similarity
else:
if lowest_distance < similarity:
new_lowest_distance = similarity
for index, existing_sent in enumerate(sentences_to_return):
if existing_sent[1] == lowest_distance:
sentences_to_return[index] = (sent, similarity)
elif existing_sent[1] < new_lowest_distance:
new_lowest_distance = existing_sent[1]
lowest_distance = new_lowest_distance
sentences_to_return.sort(key=lambda x: x[1], reverse=True)
return sentences_to_return
def get_distances_between_sentences(sentences):
sentences_distances = []
for i in range(0, len(sentences)):
for j in range(i + 1, len(sentences)):
distance = {"sent1": sentences[i], "sent2": sentences[j]}
vec_list_1 = \
pca_model.transform(
[tfkld_model.transform([sentences[i]])[0].toarray()[0].tolist()]
)
vec_list_2 = \
pca_model.transform(
[tfkld_model.transform([sentences[j]])[0].toarray()[0].tolist()]
)
distance["distance"] = float(cosine_similarity(vec_list_1, vec_list_2))
sentences_distances.append(distance)
return sentences_distances
###Output
_____no_output_____
###Markdown
Test Utility Functions
###Code
doc_list = []
file_1 = open('test_documents/crypto_currency.txt','r')
file_2 = open('test_documents/trump_401k.txt','r')
doc_list.append(file_1.read())
doc_list.append(file_2.read())
sent_dict = vectorize_document_list(doc_list)
vectorize_sentences(["Hello what is your name?", "I like cheese.", "what do you think of me?"])
sentences = get_most_similar_sentences(
sent_dict,
"“So he just may not realize that he’s speaking to the privileged few.” Only a third of people contribute anything to their retirement accounts, according to a Census study released this year.",
10
)
print sentences[0]
mean_sentences_vector(
["“So he just may not realize that he’s speaking to the privileged few.” Only a third of people contribute anything to their retirement accounts, according to a Census study released this year."]
)
new_sentences = get_most_similar_sentences_to_vector(
sent_dict,
mean_sentences_vector(
["“So he just may not realize that he’s speaking to the privileged few.” Only a third of people contribute anything to their retirement accounts, according to a Census study released this year."]
)
)
print new_sentences[0]
sentences = get_distances_between_sentences(["hello world.", "I like applesauce."])
print sentences
###Output
_____no_output_____ |
ModelsOverview-1.ipynb | ###Markdown
Dummy Features Preparation
###Code
sparse_orders_top_100 = sparse_orders[main_top_100.index]
from itertools import combinations
pairs_dict_list = []
for row_index in tqdm(range(sparse_orders_top_100.shape[0]), mininterval=2):
pairs_dict = {}
for pair_first, pair_second in combinations(sparse_orders_top_100[row_index].indices, 2):
name_first = orders_vectorizer.feature_names_[pair_first]
name_second = orders_vectorizer.feature_names_[pair_second]
if sparse_orders_top_100[row_index, pair_first] < sparse_orders_top_100[row_index, pair_second]:
pairs_dict['{0} < {1}'.format(name_first, name_second)] = 1
else:
pairs_dict['{0} < {1}'.format(name_second, name_first)] = 1
pairs_dict_list.append(pairs_dict)
dummy_vectorizer = sklearn.feature_extraction.DictVectorizer(sparse=True, dtype=float)
sparse_dummy = dummy_vectorizer.fit_transform(pairs_dict_list).astype(np.int8)
print(type(sparse_dummy))
print('Sparse dummy shape: \n{0}'.format(sparse_dummy.shape))
print('User Agent shape: \n{0}'.format(main_top_100.User_Agent.shape))
###Output
_____no_output_____
###Markdown
TF-IDF Features Preparation
###Code
tf_idf_vectorizer = sklearn.feature_extraction.text.TfidfTransformer()
tf_idf = tf_idf_vectorizer.fit_transform(sparse_dummy)
print(tf_idf.shape)
print(type(tf_idf))
###Output
(113512, 780)
<class 'scipy.sparse.csr.csr_matrix'>
###Markdown
Merged Features
###Code
from scipy.sparse import hstack
merged = hstack((sparse_dummy, tf_idf)).tocsr()
print('Sparse dummy: \n{0}'.format(sparse_dummy[:1]))
print('Sparse tf-idf: \n{0}'.format(tf_idf[:1]))
print('Merged: \n{0}'.format(merged[:1]))
###Output
Sparse dummy:
(0, 0) 1
(0, 64) 1
(0, 65) 1
(0, 66) 1
(0, 116) 1
(0, 117) 1
Sparse tf-idf:
(0, 117) 0.475177018993
(0, 116) 0.418039527723
(0, 66) 0.254858386256
(0, 65) 0.474763342134
(0, 64) 0.301955604503
(0, 0) 0.466818528673
Merged:
(0, 0) 1.0
(0, 64) 1.0
(0, 65) 1.0
(0, 66) 1.0
(0, 116) 1.0
(0, 117) 1.0
(0, 780) 0.466818528673
(0, 844) 0.301955604503
(0, 845) 0.474763342134
(0, 846) 0.254858386256
(0, 896) 0.418039527723
(0, 897) 0.475177018993
###Markdown
Build cross-val predictions and comparison
###Code
from sklearn.model_selection import GridSearchCV, cross_val_predict, cross_val_score, train_test_split, KFold
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import roc_auc_score, roc_curve, f1_score, make_scorer
from sklearn.multiclass import OneVsRestClassifier
from sklearn import preprocessing
lb = preprocessing.LabelBinarizer()
lb.fit(top_ua)
y = lb.transform(main_top_100.User_Agent)
y.shape
cb_clf.estimator.get_params()
from catboost import CatBoostClassifier
cb_clf = OneVsRestClassifier(CatBoostClassifier(iterations=10, depth=3, learning_rate=1))
print(cb_clf.estimator.get_params())
%time y_hat_dummy = cross_val_predict(cb_clf, sparse_dummy.toarray(), y, method='predict_proba')
print(thresholded_score(0.0083, y, y_hat_dummy), mean_answers(0.0083, y_hat_dummy))
print(thresholded_score(0.0083, y, y_hat_tf_idf), mean_answers(0.0083, y_hat_tf_idf))
clf = OneVsRestClassifier(LogisticRegression(C=100))
%time y_hat_dummy = cross_val_predict(clf, sparse_dummy, y, method='predict_proba', n_jobs=-1)
tf_clf = OneVsRestClassifier(LogisticRegression(C=100))
%time y_hat_tf_idf = cross_val_predict(tf_clf, tf_idf, y, method='predict_proba', n_jobs=-1)
merged_clf = OneVsRestClassifier(LogisticRegression(C=100))
%time y_hat_merged = cross_val_predict(merged_clf, merged, y, method='predict_proba', n_jobs=-1)
def get_f1_score(alpha, y, y_hat):
return f1_score(y, (y_hat > alpha).astype('int'), average='samples')
def mean_answers(alpha, y_cross_val):
return np.mean([len(list(filter(lambda i: i>alpha, y_obs))) for y_obs in y_cross_val])
def thresholded_score(alpha, y, y_cross_val):
"""
:param alpha: Threshold
:param y: y sample
:param y_cross_val: y from cross_val_predict
:return: true if at least one predicted User Agent equal true User Agent
"""
correct_answers = 0
for y_index, y_label in enumerate(np.argmax(y, axis=1)):
if y_label in np.argwhere(y_cross_val[y_index] > alpha):
correct_answers += 1
return correct_answers / len(y)
threshold_grid = np.linspace(0, 0.5, 51)
dummy_f1 = [get_f1_score(alpha, y, y_hat_dummy) for alpha in tqdm(threshold_grid)]
tf_idf_f1 = [get_f1_score(alpha, y, y_hat_tf_idf) for alpha in tqdm(threshold_grid)]
merged_f1 = [get_f1_score(alpha, y, y_hat_merged) for alpha in tqdm(threshold_grid)]
plt.figure(figsize=(16,4))
plt.plot(threshold_grid[1:], dummy_f1[1:], '-p', label='dummy')
plt.plot(threshold_grid[1:], tf_idf_f1[1:], '-p', label='tf-idf')
plt.plot(threshold_grid[1:], merged_f1[1:], '-p', label='merged')
plt.title('F1-score comparison')
plt.ylabel('F1-score')
plt.xlabel('threshold')
plt.legend()
plt.show()
print(thresholded_score(0.0083, y, y_hat_tf_idf), mean_answers(0.0083, y_hat_tf_idf))
print(thresholded_score(0.08, y, y_hat_tf_idf), mean_answers(0.08, y_hat_tf_idf))
print(thresholded_score(0.5, y, y_hat_tf_idf), mean_answers(0.5, y_hat_tf_idf))
threshold_grid = np.linspace(0, 0.4, 41)
dummy_threshold_score = [thresholded_score(alpha, y, y_hat_dummy) for alpha in tqdm(threshold_grid)]
tf_idf_threshold_score = [thresholded_score(alpha, y, y_hat_tf_idf) for alpha in tqdm(threshold_grid)]
merged_threshold_score = [thresholded_score(alpha, y, y_hat_merged) for alpha in tqdm(threshold_grid)]
plt.figure(figsize=(16,4))
plt.plot(threshold_grid[1:], dummy_threshold_score[1:], '-p', label='dummy')
plt.plot(threshold_grid[1:], tf_idf_threshold_score[1:], '-p', label='tf-idf')
plt.plot(threshold_grid[1:], merged_threshold_score[1:], '-p', label='merged')
plt.title('Threshold accuracy comparison')
plt.ylabel('Accuracy')
plt.xlabel('threshold')
plt.legend()
plt.show()
threshold_grid = np.linspace(0, 0.4, 41)
dummy_mean_answers = [mean_answers(alpha, y_hat_dummy) for alpha in tqdm(threshold_grid)]
tf_idf_mean_answers = [mean_answers(alpha, y_hat_tf_idf) for alpha in tqdm(threshold_grid)]
merged_mean_answers = [mean_answers(alpha, y_hat_merged) for alpha in tqdm(threshold_grid)]
plt.figure(figsize=(16,4))
plt.plot(threshold_grid[1:], dummy_mean_answers[1:], label='dummy')
plt.plot(threshold_grid[1:], tf_idf_mean_answers[1:], label='dummy')
plt.plot(threshold_grid[1:], merged_mean_answers[1:], label='dummy')
plt.title('Mean answers comparison')
plt.xlabel('threshold')
plt.ylabel('mean answers count')
plt.show()
t = 0.1
print(thresholded_score(t, y, y_hat_tf_idf), mean_answers(t, y_hat_tf_idf))
print(thresholded_score(t, y, y_hat_dummy), mean_answers(t, y_hat_dummy))
print(thresholded_score(t, y, y_hat_merged), mean_answers(t, y_hat_merged))
t = 0.0083
print(thresholded_score(t, y, y_hat_tf_idf), mean_answers(t, y_hat_tf_idf))
print(thresholded_score(t, y, y_hat_dummy), mean_answers(t, y_hat_dummy))
print(thresholded_score(t, y, y_hat_merged), mean_answers(t, y_hat_merged))
###Output
0.9474416801747833 7.95218126718
0.9439706815138488 7.87966030023
0.9438385368947776 7.87765170202
###Markdown
PCA
###Code
tf_idf.shape
tf_idf_dense = tf_idf.todense()
from sklearn.decomposition import PCA
pca = PCA(n_components=20)
pca_tf_idf = pca.fit_transform(tf_idf_dense)
pca_tf_idf.shape
pca_clf = OneVsRestClassifier(LogisticRegression(C=100))
%time y_hat_pca = cross_val_predict(pca_clf, pca_tf_idf, y, method='predict_proba', n_jobs=-1)
t = 0.1
print(thresholded_score(t, y, y_hat_pca), mean_answers(t, y_hat_pca))
print (get_f1_score(alpha=t, y=y, y_hat=y_hat_pca))
merged_pca = hstack((sparse_dummy, pca_tf_idf)).tocsr()
merged_pca_clf = OneVsRestClassifier(LogisticRegression(C=100))
%time y_hat_merged_pca = cross_val_predict(merged_pca_clf, merged_pca, y, method='predict_proba', n_jobs=-1)
t = 0.1
print(thresholded_score(t, y, y_hat_tf_idf), mean_answers(t, y_hat_tf_idf))
print(thresholded_score(t, y, y_hat_dummy), mean_answers(t, y_hat_dummy))
print(thresholded_score(t, y, y_hat_merged), mean_answers(t, y_hat_merged))
print(thresholded_score(t, y, y_hat_merged_pca), mean_answers(t, y_hat_merged_pca))
t = 0.0083
print(thresholded_score(t, y, y_hat_tf_idf), mean_answers(t, y_hat_tf_idf))
print(thresholded_score(t, y, y_hat_dummy), mean_answers(t, y_hat_dummy))
print(thresholded_score(t, y, y_hat_merged), mean_answers(t, y_hat_merged))
print(thresholded_score(t, y, y_hat_merged_pca), mean_answers(t, y_hat_merged_pca))
###Output
0.9474416801747833 7.95218126718
0.9439706815138488 7.87966030023
0.9438385368947776 7.87765170202
0.9440059200789344 7.87695574036
###Markdown
Naive Bayes
###Code
type(merged_pca)
print(merged_pca[:1])
from sklearn.naive_bayes import GaussianNB
gaussian_clf = OneVsRestClassifier(GaussianNB())
cross_val_predict(gaussian_clf, data_view, y, method='predict_proba', n_jobs=-1)
from sklearn.naive_bayes import MultinomialNB
bayes_clf = OneVsRestClassifier(MultinomialNB())
data = {'dummy': sparse_dummy,
'tf-idf': tf_idf,
'merged': merged,
# 'merged_pca': merged_pca
}
clf_labels = {}
for data_name, data_view in data.items():
print(data_name)
%time clf_labels[data_name] = cross_val_predict(bayes_clf, data_view, y, method='predict_proba', n_jobs=-1)
t = 0.0083
for name, res in clf_labels.items():
print(name, thresholded_score(t, y, res), mean_answers(t, res))
from sklearn.naive_bayes import GaussianNB
gauss_clf = OneVsRestClassifier(GaussianNB())
data = {'dummy': sparse_dummy,
'tf-idf': tf_idf,
'merged': merged,
# 'merged_pca': merged_pca
}
clf_labels = {}
for data_name, data_view in data.items():
print(data_name)
%time clf_labels[data_name] = cross_val_predict(gauss_clf, data_view.toarray(), y, method='predict_proba', n_jobs=-1)
###Output
dummy
CPU times: user 2.67 s, sys: 1.27 s, total: 3.94 s
Wall time: 5min 3s
tf-idf
CPU times: user 7.61 s, sys: 2.65 s, total: 10.3 s
Wall time: 4min 53s
merged
|
training/Detect_Morocco_Plate_Licence_Flow_Normalizing_(Part_3).ipynb | ###Markdown
 DETECT MOROCCO PLATES LICENSES (Deep Neural Network: Flow Normalizing Part III) > **Note:**A large part of this work was done under an AI station with an RTX Geforce 3090 card. However, to facilitate the visualization of this approach, we made this notebook under Colab Pro (you can also run this code under Kaggle, or airflow). Connect to my drive to import data
###Code
%cd ..
from google.colab import drive
drive.mount('/content/gdrive')
###Output
_____no_output_____
###Markdown
Create Sym link for easy access of my drive and Check connection
###Code
!ln -s /content/gdrive/My\ Drive/ /mydrive
!ls /mydrive
###Output
_____no_output_____
###Markdown
Copy LicensePlateRecognition data zip to Colab
###Code
!ls /mydrive/LicensePlate
!cp /mydrive/LicensePlate/Dl_LicensePlateRecognition.zip ../
###Output
cnn_train.py Dl_LicensePlateRecognition.zip
###Markdown
Extracting zip to Colab machine under license folder
###Code
!unzip ../Dl_LicensePlateRecognition.zip -d license/
###Output
_____no_output_____
###Markdown
**Training the CNN model** Python Imports
###Code
import glob
import numpy as np
import os
from PIL import Image
from tensorflow.keras import layers, models
from sklearn.model_selection import train_test_split
from tensorflow.keras.optimizers import Adam
###Output
_____no_output_____
###Markdown
**Get Character Image Data**
###Code
dictionary = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9,
'a': 10, 'b': 11, 'd': 12, 'h': 13, 'm': 14, 'p': 15, 'waw': 16, 'ww': 17, 'j': 18}
def get_char_data():
# All our image characters are in the size of 100x75
# Each alpha number characters has a folder that has hundresds of images
data = np.array([]).reshape(0, 100, 75)
labels = np.array([])
# Walking through all the directorires to fetch the image data.
dirs = [i[0] for i in os.walk('/license/Dl_LicensePlateRecognition/CNN_CharacterRecognition/dataset')][1:]
for dir in dirs:
image_file_list = glob.glob(dir + '/*.jpg')
sub_data = np.array([np.array(Image.open(file_name)) for file_name in image_file_list])
data = np.append(data, sub_data, axis = 0)
sub_labels = [dictionary[dir[-1:]]] * len(sub_data)
labels = np.append(labels, sub_labels, axis = 0)
x_train, x_test, y_train, y_test = train_test_split(data, labels, test_size = 0.2, random_state = 45, shuffle = True)
return (x_train, y_train), (x_test, y_test)
###Output
_____no_output_____
###Markdown
**Making Character Image Train and Test dataset**
###Code
(x_train, y_train), (x_test, y_test) = get_char_data()
x_train = x_train.reshape((x_train.shape[0], 100, 75, 1))
x_test = x_test.reshape((x_test.shape[0], 100, 75, 1))
# pixel range is from 0 - 255
x_train, x_test = x_train / 255.0, x_test / 255.0
###Output
_____no_output_____
###Markdown
**Defining the CNN Model**
###Code
def cnn_model():
cnn_model = models.Sequential()
cnn_model.add(layers.Conv2D(32, (3, 3), padding = 'same', activation = 'relu', input_shape = (100, 75, 1)))
cnn_model.add(layers.MaxPooling2D((2, 2)))
cnn_model.add(layers.Conv2D(64, (3, 3), activation = 'relu'))
cnn_model.add(layers.MaxPooling2D((2, 2)))
cnn_model.add(layers.Conv2D(128, (3, 3), activation = 'relu'))
cnn_model.add(layers.MaxPooling2D((2, 2)))
cnn_model.add(layers.Dense(128, activation = 'relu'))
cnn_model.add(layers.Flatten())
# 0 - 9 and A-Z => 10 + 25 = 35 -- ignoring O in alphabets.
cnn_model.add(layers.Dense(35, activation = 'softmax'))
cnn_model.summary()
return cnn_model
###Output
_____no_output_____
###Markdown
**Training the CNN Model**
###Code
import tensorflow as tf
tf.test.gpu_device_name()
model = cnn_model()
opt = Adam(lr = 0.001)
model.compile(optimizer = opt, loss = tf.keras.losses.sparse_categorical_crossentropy, metrics = ['accuracy'])
history=model.fit(x_train, y_train, validation_split=0.1, epochs=15, batch_size=3, verbose=1)
test_loss, test_acc = model.evaluate(x_test, y_test)
print(test_acc)
model.save("cnn_char_recognition.h5")
###Output
Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
conv2d (Conv2D) (None, 100, 75, 32) 320
_________________________________________________________________
max_pooling2d (MaxPooling2D) (None, 50, 37, 32) 0
_________________________________________________________________
conv2d_1 (Conv2D) (None, 48, 35, 64) 18496
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 24, 17, 64) 0
_________________________________________________________________
conv2d_2 (Conv2D) (None, 22, 15, 128) 73856
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 11, 7, 128) 0
_________________________________________________________________
dense (Dense) (None, 11, 7, 128) 16512
_________________________________________________________________
flatten (Flatten) (None, 9856) 0
_________________________________________________________________
dense_1 (Dense) (None, 35) 344995
=================================================================
Total params: 454,179
Trainable params: 454,179
Non-trainable params: 0
_________________________________________________________________
Epoch 1/15
8520/8520 [==============================] - 25s 3ms/step - loss: 0.3009 - accuracy: 0.9137 - val_loss: 0.0541 - val_accuracy: 0.9831
Epoch 2/15
8520/8520 [==============================] - 25s 3ms/step - loss: 0.0355 - accuracy: 0.9895 - val_loss: 0.0455 - val_accuracy: 0.9877
Epoch 3/15
8520/8520 [==============================] - 24s 3ms/step - loss: 0.0193 - accuracy: 0.9947 - val_loss: 0.0322 - val_accuracy: 0.9937
Epoch 4/15
8520/8520 [==============================] - 24s 3ms/step - loss: 0.0144 - accuracy: 0.9964 - val_loss: 0.0136 - val_accuracy: 0.9968
Epoch 5/15
8520/8520 [==============================] - 24s 3ms/step - loss: 0.0140 - accuracy: 0.9963 - val_loss: 0.0129 - val_accuracy: 0.9961
Epoch 6/15
8520/8520 [==============================] - 24s 3ms/step - loss: 0.0079 - accuracy: 0.9978 - val_loss: 0.0084 - val_accuracy: 0.9982
Epoch 7/15
8520/8520 [==============================] - 24s 3ms/step - loss: 0.0103 - accuracy: 0.9977 - val_loss: 0.0278 - val_accuracy: 0.9951
Epoch 8/15
8520/8520 [==============================] - 24s 3ms/step - loss: 0.0054 - accuracy: 0.9987 - val_loss: 0.0125 - val_accuracy: 0.9975
Epoch 9/15
8520/8520 [==============================] - 24s 3ms/step - loss: 0.0065 - accuracy: 0.9985 - val_loss: 0.0197 - val_accuracy: 0.9961
Epoch 10/15
8520/8520 [==============================] - 24s 3ms/step - loss: 0.0066 - accuracy: 0.9987 - val_loss: 0.0219 - val_accuracy: 0.9965
Epoch 11/15
8520/8520 [==============================] - 24s 3ms/step - loss: 0.0045 - accuracy: 0.9992 - val_loss: 0.0486 - val_accuracy: 0.9912
Epoch 12/15
8520/8520 [==============================] - 24s 3ms/step - loss: 0.0030 - accuracy: 0.9997 - val_loss: 0.0115 - val_accuracy: 0.9982
Epoch 13/15
8520/8520 [==============================] - 24s 3ms/step - loss: 0.0060 - accuracy: 0.9990 - val_loss: 0.0097 - val_accuracy: 0.9989
Epoch 14/15
8520/8520 [==============================] - 25s 3ms/step - loss: 0.0061 - accuracy: 0.9988 - val_loss: 0.0227 - val_accuracy: 0.9972
Epoch 15/15
8520/8520 [==============================] - 24s 3ms/step - loss: 0.0098 - accuracy: 0.9986 - val_loss: 0.0227 - val_accuracy: 0.9968
222/222 [==============================] - 1s 4ms/step - loss: 0.0287 - accuracy: 0.9970
0.9970422387123108
###Markdown
**Save the model to Google Drive**
###Code
!cp /cnn_char_recognition.h5 /mydrive/LicensePlate/
###Output
_____no_output_____
###Markdown
**Plots for Accuracy and Loss**
###Code
import matplotlib.pyplot as plot
# print(history.history.keys())
# Accuracy
plot.plot(history.history['accuracy'])
plot.plot(history.history['val_accuracy'])
plot.title('Model Accuracy')
plot.ylabel('Accuracy')
plot.xlabel('Epoch')
plot.legend(['train', 'test'], loc='lower right')
plot.show()
# Loss
plot.plot(history.history['loss'])
plot.plot(history.history['val_loss'])
plot.title('Model loss')
plot.ylabel('Loss')
plot.xlabel('Epoch')
plot.legend(['train', 'test'], loc='upper right')
plot.show()
###Output
_____no_output_____
###Markdown
 DETECT MOROCCO PLATES LICENSES (Deep Neural Network: Flow Normalizing Part III) > **Note:**A large part of this work was done under an AI station with an RTX Geforce 3090 card. However, to facilitate the visualization of this approach, we made this notebook under Colab Pro (you can also run this code under Kaggle, or airflow). Connect to my drive to import data
###Code
%cd ..
from google.colab import drive
drive.mount('/content/gdrive')
###Output
_____no_output_____
###Markdown
Create Sym link for easy access of my drive and Check connection
###Code
!ln -s /content/gdrive/My\ Drive/ /mydrive
!ls /mydrive
###Output
_____no_output_____
###Markdown
Copy LicensePlateRecognition data zip to Colab
###Code
!ls /mydrive/LicensePlate
!cp /mydrive/LicensePlate/Dl_LicensePlateRecognition.zip ../
###Output
cnn_train.py Dl_LicensePlateRecognition.zip
###Markdown
Extracting zip to Colab machine under license folder
###Code
!unzip ../Dl_LicensePlateRecognition.zip -d license/
###Output
_____no_output_____
###Markdown
**Training the CNN model** Python Imports
###Code
import glob
import numpy as np
import os
from PIL import Image
from tensorflow.keras import layers, models
from sklearn.model_selection import train_test_split
from tensorflow.keras.optimizers import Adam
###Output
_____no_output_____
###Markdown
**Get Character Image Data**
###Code
dictionary = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9,
'a': 10, 'b': 11, 'd': 12, 'h': 13, 'm': 14, 'p': 15, 'waw': 16, 'ww': 17, 'j': 18}
def get_char_data():
# All our image characters are in the size of 100x75
# Each alpha number characters has a folder that has hundresds of images
data = np.array([]).reshape(0, 100, 75)
labels = np.array([])
# Walking through all the directorires to fetch the image data.
dirs = [i[0] for i in os.walk('/license/Dl_LicensePlateRecognition/CNN_CharacterRecognition/dataset')][1:]
for dir in dirs:
image_file_list = glob.glob(dir + '/*.jpg')
sub_data = np.array([np.array(Image.open(file_name)) for file_name in image_file_list])
data = np.append(data, sub_data, axis = 0)
sub_labels = [dictionary[dir[-1:]]] * len(sub_data)
labels = np.append(labels, sub_labels, axis = 0)
x_train, x_test, y_train, y_test = train_test_split(data, labels, test_size = 0.2, random_state = 45, shuffle = True)
return (x_train, y_train), (x_test, y_test)
###Output
_____no_output_____
###Markdown
**Making Character Image Train and Test dataset**
###Code
(x_train, y_train), (x_test, y_test) = get_char_data()
x_train = x_train.reshape((x_train.shape[0], 100, 75, 1))
x_test = x_test.reshape((x_test.shape[0], 100, 75, 1))
# pixel range is from 0 - 255
x_train, x_test = x_train / 255.0, x_test / 255.0
###Output
_____no_output_____
###Markdown
**Defining the CNN Model**
###Code
def cnn_model():
cnn_model = models.Sequential()
cnn_model.add(layers.Conv2D(32, (3, 3), padding = 'same', activation = 'relu', input_shape = (100, 75, 1)))
cnn_model.add(layers.MaxPooling2D((2, 2)))
cnn_model.add(layers.Conv2D(64, (3, 3), activation = 'relu'))
cnn_model.add(layers.MaxPooling2D((2, 2)))
cnn_model.add(layers.Conv2D(128, (3, 3), activation = 'relu'))
cnn_model.add(layers.MaxPooling2D((2, 2)))
cnn_model.add(layers.Dense(128, activation = 'relu'))
cnn_model.add(layers.Flatten())
# 0 - 9 and A-Z => 10 + 25 = 35 -- ignoring O in alphabets.
cnn_model.add(layers.Dense(35, activation = 'softmax'))
cnn_model.summary()
return cnn_model
###Output
_____no_output_____
###Markdown
**Training the CNN Model**
###Code
import tensorflow as tf
tf.test.gpu_device_name()
model = cnn_model()
opt = Adam(lr = 0.001)
model.compile(optimizer = opt, loss = tf.keras.losses.sparse_categorical_crossentropy, metrics = ['accuracy'])
history=model.fit(x_train, y_train, validation_split=0.1, epochs=15, batch_size=3, verbose=1)
test_loss, test_acc = model.evaluate(x_test, y_test)
print(test_acc)
model.save("cnn_char_recognition.h5")
###Output
Model: "sequential"
_________________________________________________________________
Layer (type) Output Shape Param #
=================================================================
conv2d (Conv2D) (None, 100, 75, 32) 320
_________________________________________________________________
max_pooling2d (MaxPooling2D) (None, 50, 37, 32) 0
_________________________________________________________________
conv2d_1 (Conv2D) (None, 48, 35, 64) 18496
_________________________________________________________________
max_pooling2d_1 (MaxPooling2 (None, 24, 17, 64) 0
_________________________________________________________________
conv2d_2 (Conv2D) (None, 22, 15, 128) 73856
_________________________________________________________________
max_pooling2d_2 (MaxPooling2 (None, 11, 7, 128) 0
_________________________________________________________________
dense (Dense) (None, 11, 7, 128) 16512
_________________________________________________________________
flatten (Flatten) (None, 9856) 0
_________________________________________________________________
dense_1 (Dense) (None, 35) 344995
=================================================================
Total params: 454,179
Trainable params: 454,179
Non-trainable params: 0
_________________________________________________________________
Epoch 1/15
8520/8520 [==============================] - 25s 3ms/step - loss: 0.3009 - accuracy: 0.9137 - val_loss: 0.0541 - val_accuracy: 0.9831
Epoch 2/15
8520/8520 [==============================] - 25s 3ms/step - loss: 0.0355 - accuracy: 0.9895 - val_loss: 0.0455 - val_accuracy: 0.9877
Epoch 3/15
8520/8520 [==============================] - 24s 3ms/step - loss: 0.0193 - accuracy: 0.9947 - val_loss: 0.0322 - val_accuracy: 0.9937
Epoch 4/15
8520/8520 [==============================] - 24s 3ms/step - loss: 0.0144 - accuracy: 0.9964 - val_loss: 0.0136 - val_accuracy: 0.9968
Epoch 5/15
8520/8520 [==============================] - 24s 3ms/step - loss: 0.0140 - accuracy: 0.9963 - val_loss: 0.0129 - val_accuracy: 0.9961
Epoch 6/15
8520/8520 [==============================] - 24s 3ms/step - loss: 0.0079 - accuracy: 0.9978 - val_loss: 0.0084 - val_accuracy: 0.9982
Epoch 7/15
8520/8520 [==============================] - 24s 3ms/step - loss: 0.0103 - accuracy: 0.9977 - val_loss: 0.0278 - val_accuracy: 0.9951
Epoch 8/15
8520/8520 [==============================] - 24s 3ms/step - loss: 0.0054 - accuracy: 0.9987 - val_loss: 0.0125 - val_accuracy: 0.9975
Epoch 9/15
8520/8520 [==============================] - 24s 3ms/step - loss: 0.0065 - accuracy: 0.9985 - val_loss: 0.0197 - val_accuracy: 0.9961
Epoch 10/15
8520/8520 [==============================] - 24s 3ms/step - loss: 0.0066 - accuracy: 0.9987 - val_loss: 0.0219 - val_accuracy: 0.9965
Epoch 11/15
8520/8520 [==============================] - 24s 3ms/step - loss: 0.0045 - accuracy: 0.9992 - val_loss: 0.0486 - val_accuracy: 0.9912
Epoch 12/15
8520/8520 [==============================] - 24s 3ms/step - loss: 0.0030 - accuracy: 0.9997 - val_loss: 0.0115 - val_accuracy: 0.9982
Epoch 13/15
8520/8520 [==============================] - 24s 3ms/step - loss: 0.0060 - accuracy: 0.9990 - val_loss: 0.0097 - val_accuracy: 0.9989
Epoch 14/15
8520/8520 [==============================] - 25s 3ms/step - loss: 0.0061 - accuracy: 0.9988 - val_loss: 0.0227 - val_accuracy: 0.9972
Epoch 15/15
8520/8520 [==============================] - 24s 3ms/step - loss: 0.0098 - accuracy: 0.9986 - val_loss: 0.0227 - val_accuracy: 0.9968
222/222 [==============================] - 1s 4ms/step - loss: 0.0287 - accuracy: 0.9970
0.9970422387123108
###Markdown
**Save the model to Google Drive**
###Code
!cp /cnn_char_recognition.h5 /mydrive/LicensePlate/
###Output
_____no_output_____
###Markdown
**Plots for Accuracy and Loss**
###Code
import matplotlib.pyplot as plot
# print(history.history.keys())
# Accuracy
plot.plot(history.history['accuracy'])
plot.plot(history.history['val_accuracy'])
plot.title('Model Accuracy')
plot.ylabel('Accuracy')
plot.xlabel('Epoch')
plot.legend(['train', 'test'], loc='lower right')
plot.show()
# Loss
plot.plot(history.history['loss'])
plot.plot(history.history['val_loss'])
plot.title('Model loss')
plot.ylabel('Loss')
plot.xlabel('Epoch')
plot.legend(['train', 'test'], loc='upper right')
plot.show()
###Output
_____no_output_____ |
benchmarking_ez/benchmark_wbo_xtb_qca.ipynb | ###Markdown
Picking a torsiondrive record (first item)
###Code
import qcelemental as qcel
import qcengine as qcng
def get_xtb_wbo_qce(qcmol, idx1, idx2):
# xtb model
model = qcel.models.AtomicInput(
molecule=qcmol,
driver="energy",
model={"method": "GFN2-xTB"},
)
# result of single point energy calculation
result = qcng.compute(model, "xtb")
return result.extras["xtb"]["mayer_indices"][idx1, idx2]
def get_wbo_from_dataset(client, ds_name):
all_data = []
f = 0
logged = False
ds = client.get_collection("TorsionDriveDataset", ds_name)
print(f"starting {ds_name}")
print(f"molecules: {ds.status('default',status='COMPLETE').default[0]}")
for i, index in enumerate(ds.df.index):
# get the record of each entry
tdr = ds.get_record(name=index, specification='default')
if f % 10 == 0 and logged == False:
logged = True
print(f" {f}")
if tdr.status == "COMPLETE":
f += 1
logged = False
try:
if len(tdr.final_energy_dict) == 0:
print(f"Molecule had no final energy dict {index}")
continue
min_idx = min(tdr.final_energy_dict, key=tdr.final_energy_dict.get)
record = tdr.get_history(min_idx, minimum=True)
# get optimized molecule of the record
qc_mol = record.get_final_molecule()
# convert the qcelemental molecule to an OpenEye molecule
qcjson_mol = qc_mol.dict(encoding='json')
oemol = cmiles.utils.load_molecule(qcjson_mol)
dihedrals = tdr.keywords.dihedrals[0]
natoms = len(record.get_final_molecule().symbols)
result = record.get_trajectory()[-1]
wiberg = np.array(result.extras["qcvars"]["WIBERG_LOWDIN_INDICES"]).reshape(-1,natoms)
qmwbo = wiberg[dihedrals[1], dihedrals[2]]
# make a copy for am1 computations
xtbwbo = get_xtb_wbo_qce(qc_mol, dihedrals[1], dihedrals[2])
# v this makes different conformers have different dict entries.
# as far as I know, this just causes a warning in visuals
smiles = oechem.OEMolToSmiles(oemol) + f"_{i}"
this_molecule_data = ( smiles, ((qmwbo, xtbwbo), dihedrals) )
all_data.append(this_molecule_data)
except:
print(f"ERROR {ds_name} {i}")
continue
print(f"finished {ds_name}")
return all_data
pkldir = "xtb_benchmark_results"
if not os.path.exists(pkldir):
os.makedirs(pkldir)
for dname in dataset_names[25:]:
wbo = get_wbo_from_dataset(client, dname)
fname = f"{pkldir}/{dname.replace(' ','')}.pkl"
to_dump = [dname, wbo]
with open(fname, "wb") as pkf:
pickle.dump( to_dump, pkf )
dataset_names.index("OpenFF Protein Fragments TorsionDrives v1.0")
###Output
_____no_output_____ |
notebook/Image_processing.ipynb | ###Markdown
Dullness
###Code
def color_analysis(img):
# img = Image.open(images_path+'/'+img)
# obtain the color palatte of the image
palatte = defaultdict(int)
for pixel in img.getdata():
palatte[pixel] += 1
# sort the colors present in the image
sorted_x = sorted(palatte.items(), key=operator.itemgetter(1), reverse = True)
light_shade, dark_shade, shade_count, pixel_limit = 0, 0, 0, 25
for i, x in enumerate(sorted_x[:pixel_limit]):
if all(xx <= 20 for xx in x[0][:3]): ## dull : too much darkness
dark_shade += x[1]
if all(xx >= 240 for xx in x[0][:3]): ## bright : too much whiteness
light_shade += x[1]
shade_count += x[1]
light_percent = round((float(light_shade)/shade_count)*100, 2)
dark_percent = round((float(dark_shade)/shade_count)*100, 2)
return light_percent, dark_percent
def perform_color_analysis(im, flag):
# im = Image.open(images_path+'/'+im)
# cut the images into two halves as complete average may give bias results
size = im.size
halves = (size[0]/2, size[1]/2)
im1 = im.crop((0, 0, size[0], halves[1]))
im2 = im.crop((0, halves[1], size[0], size[1]))
try:
light_percent1, dark_percent1 = color_analysis(im1)
light_percent2, dark_percent2 = color_analysis(im2)
except Exception as e:
return None
light_percent = (light_percent1 + light_percent2)/2
dark_percent = (dark_percent1 + dark_percent2)/2
if flag == 'black':
return dark_percent
elif flag == 'white':
return light_percent
else:
return None
###Output
_____no_output_____
###Markdown
Uniformness
###Code
def average_pixel_width(im):
im_array = np.asarray(im.convert(mode='L'))
edges_sigma1 = feature.canny(im_array, sigma=3)
apw = (float(np.sum(edges_sigma1)) / (im.size[0]*im.size[1]))
return apw*100
def get_dominant_color(img):
img = np.float32(img)
pixels = img.reshape((-1, 3))
n_colors = 5
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 200, .1)
flags = cv2.KMEANS_RANDOM_CENTERS
_, labels, centroids = cv2.kmeans(pixels, n_colors, None, criteria, 10, flags)
palette = np.uint8(centroids)
quantized = palette[labels.flatten()]
quantized = quantized.reshape(img.shape)
dominant_color = palette[np.argmax(np.unique(labels)[1])]
return dominant_color
def get_average_color(img):
img = np.float32(img)
average_color = [img[:, :, i].mean() for i in range(img.shape[-1])]
return average_color
def getSize(filename):
filename = images_path + '/' + filename
st = os.stat(filename)
return st.st_size
def getDimensions(image):
return image.size
def get_blurrness(image):
image = np.float32(image)
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
fm = cv2.Laplacian(image, cv2.CV_32F).var()
return fm
def score_feats(data):
data['dullness'] = data['img_mat'].apply(lambda x : perform_color_analysis(x, 'black'))
data['whiteness'] = data['img_mat'].apply(lambda x : perform_color_analysis(x, 'white'))
data['apw'] = data['img_mat'].apply(lambda x : average_pixel_width(x))
# data['dominant_color'] = data['img_mat'].apply(lambda x : get_dominant_color(x))
data['average_color'] = data['img_mat'].apply(lambda x : get_average_color(x))
data['size'] = data['image'].apply(getSize)
data['dim'] = data['img_mat'].apply(getDimensions)
data['blurrness'] = data['img_mat'].apply(lambda x: get_blurrness(x))
return data
start = time.time()
feats = parallelize_dataframe(feats, score_feats)
print("Feature creation time: %0.2f Minutes"%((time.time() - start)/60))
gc.collect()
feats.head()
feats.describe()
img_df = feats.drop(['img_mat'], axis= 1)
img_df.to_csv('img_df_0')
del img_df
gc.collect()
###Output
_____no_output_____ |
Probability/Conditional Prob & Bayes Rule/Cancer Diagnosis/Solution conditional_probability_bayes_rule.ipynb | ###Markdown
Conditional Probability & Bayes Rule Quiz
###Code
# load dataset
import pandas as pd
df=pd.read_csv("cancer_test_data.csv")
print(df.head(10))
# What proportion of patients who tested positive has cancer?
pCancer=0.105
pNoCancer=0.895
pPositiveCancer=0.905
pNegativeCancer=0.095
pPositiveNoCancer=0.204
pNegativeNoCancer=0.796
jointPositiveCancer= pCancer* pPositiveCancer
jointPositiveNoCancer= pNoCancer* pPositiveNoCancer
pPos= jointPositiveCancer+jointPositiveNoCancer
print(jointPositiveCancer/pPos)
# What proportion of patients who tested positive doesn't have cancer?
print(jointPositiveNoCancer/pPos)
# What proportion of patients who tested negative has cancer?
jointNegativeCancer= pCancer* pNegativeCancer
jointNegativeNoCancer= pNoCancer* pNegativeNoCancer
pNeg= jointNegativeCancer+jointNegativeNoCancer
print(jointNegativeCancer/pNeg)
# What proportion of patients who tested negative doesn't have cancer?
print(jointNegativeNoCancer/pNeg)
###Output
0.986191764893168
|
test-deep-learning.ipynb | ###Markdown
Import libraries
###Code
from numpy import loadtxt
from keras.models import Sequential
from keras.layers import Dense
###Output
_____no_output_____
###Markdown
Load the dataset
###Code
dataset = loadtxt('../input/pima-dataset/pima-indians-diabetes.csv', delimiter=',')
# split into input (X) and output (y) variables
X = dataset[:,0:8]
y = dataset[:,8]
y
###Output
_____no_output_____
###Markdown
Define the keras model
###Code
model = Sequential()
model.add(Dense(12, input_dim=8, activation='relu'))
model.add(Dense(8, activation='relu'))
model.add(Dense(1, activation='sigmoid'))
###Output
_____no_output_____
###Markdown
Compile the keras model
###Code
model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
###Output
_____no_output_____
###Markdown
Fit the keras model on the dataset
###Code
model.fit(X, y, epochs=150, batch_size=10)
###Output
Epoch 1/150
77/77 [==============================] - 0s 1ms/step - loss: 5.7425 - accuracy: 0.6159
Epoch 2/150
77/77 [==============================] - 0s 1ms/step - loss: 1.4564 - accuracy: 0.5885
Epoch 3/150
77/77 [==============================] - 0s 1ms/step - loss: 1.0794 - accuracy: 0.6107
Epoch 4/150
77/77 [==============================] - 0s 1ms/step - loss: 0.8844 - accuracy: 0.6263
Epoch 5/150
77/77 [==============================] - 0s 1ms/step - loss: 0.7742 - accuracy: 0.6549
Epoch 6/150
77/77 [==============================] - 0s 1ms/step - loss: 0.7681 - accuracy: 0.6471
Epoch 7/150
77/77 [==============================] - 0s 1ms/step - loss: 0.7227 - accuracy: 0.6497
Epoch 8/150
77/77 [==============================] - 0s 1ms/step - loss: 0.6849 - accuracy: 0.6784
Epoch 9/150
77/77 [==============================] - 0s 1ms/step - loss: 0.6787 - accuracy: 0.6667
Epoch 10/150
77/77 [==============================] - 0s 1ms/step - loss: 0.6608 - accuracy: 0.6979
Epoch 11/150
77/77 [==============================] - 0s 1ms/step - loss: 0.6675 - accuracy: 0.6654
Epoch 12/150
77/77 [==============================] - 0s 1ms/step - loss: 0.6620 - accuracy: 0.6602
Epoch 13/150
77/77 [==============================] - 0s 1ms/step - loss: 0.6557 - accuracy: 0.6797
Epoch 14/150
77/77 [==============================] - 0s 2ms/step - loss: 0.6695 - accuracy: 0.6654
Epoch 15/150
77/77 [==============================] - 0s 1ms/step - loss: 0.6388 - accuracy: 0.7031
Epoch 16/150
77/77 [==============================] - 0s 1ms/step - loss: 0.6373 - accuracy: 0.7161
Epoch 17/150
77/77 [==============================] - 0s 1ms/step - loss: 0.6199 - accuracy: 0.7044
Epoch 18/150
77/77 [==============================] - 0s 1ms/step - loss: 0.6468 - accuracy: 0.6745
Epoch 19/150
77/77 [==============================] - 0s 1ms/step - loss: 0.6277 - accuracy: 0.6823
Epoch 20/150
77/77 [==============================] - 0s 1ms/step - loss: 0.6068 - accuracy: 0.7122
Epoch 21/150
77/77 [==============================] - 0s 1ms/step - loss: 0.6065 - accuracy: 0.7005
Epoch 22/150
77/77 [==============================] - 0s 1ms/step - loss: 0.6074 - accuracy: 0.7109
Epoch 23/150
77/77 [==============================] - 0s 1ms/step - loss: 0.6062 - accuracy: 0.6992
Epoch 24/150
77/77 [==============================] - 0s 1ms/step - loss: 0.6294 - accuracy: 0.6992
Epoch 25/150
77/77 [==============================] - 0s 1ms/step - loss: 0.6171 - accuracy: 0.7018
Epoch 26/150
77/77 [==============================] - 0s 1ms/step - loss: 0.6097 - accuracy: 0.7018
Epoch 27/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5813 - accuracy: 0.7188
Epoch 28/150
77/77 [==============================] - 0s 1ms/step - loss: 0.6094 - accuracy: 0.7083
Epoch 29/150
77/77 [==============================] - 0s 1ms/step - loss: 0.6015 - accuracy: 0.7201
Epoch 30/150
77/77 [==============================] - 0s 1ms/step - loss: 0.6077 - accuracy: 0.6953
Epoch 31/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5799 - accuracy: 0.7057
Epoch 32/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5725 - accuracy: 0.7109
Epoch 33/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5777 - accuracy: 0.7318
Epoch 34/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5616 - accuracy: 0.7331
Epoch 35/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5971 - accuracy: 0.7240
Epoch 36/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5693 - accuracy: 0.7266
Epoch 37/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5814 - accuracy: 0.7266
Epoch 38/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5660 - accuracy: 0.7240
Epoch 39/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5718 - accuracy: 0.7188
Epoch 40/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5664 - accuracy: 0.7201
Epoch 41/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5983 - accuracy: 0.7031
Epoch 42/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5806 - accuracy: 0.7057
Epoch 43/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5818 - accuracy: 0.7227
Epoch 44/150
77/77 [==============================] - 0s 1ms/step - loss: 0.6049 - accuracy: 0.6992
Epoch 45/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5910 - accuracy: 0.7214
Epoch 46/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5557 - accuracy: 0.7240
Epoch 47/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5476 - accuracy: 0.7292
Epoch 48/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5515 - accuracy: 0.7318
Epoch 49/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5630 - accuracy: 0.7253
Epoch 50/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5580 - accuracy: 0.7331
Epoch 51/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5569 - accuracy: 0.7318
Epoch 52/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5536 - accuracy: 0.7461
Epoch 53/150
77/77 [==============================] - 0s 2ms/step - loss: 0.5368 - accuracy: 0.7357
Epoch 54/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5493 - accuracy: 0.7383
Epoch 55/150
77/77 [==============================] - 0s 2ms/step - loss: 0.5576 - accuracy: 0.7279
Epoch 56/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5290 - accuracy: 0.7383
Epoch 57/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5440 - accuracy: 0.7422
Epoch 58/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5533 - accuracy: 0.7357
Epoch 59/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5373 - accuracy: 0.7578
Epoch 60/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5452 - accuracy: 0.7292
Epoch 61/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5454 - accuracy: 0.7383
Epoch 62/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5396 - accuracy: 0.7383
Epoch 63/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5565 - accuracy: 0.7487
Epoch 64/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5556 - accuracy: 0.7305
Epoch 65/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5747 - accuracy: 0.7305
Epoch 66/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5563 - accuracy: 0.7435
Epoch 67/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5594 - accuracy: 0.7292
Epoch 68/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5357 - accuracy: 0.7383
Epoch 69/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5346 - accuracy: 0.7448
Epoch 70/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5427 - accuracy: 0.7279
Epoch 71/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5338 - accuracy: 0.7409
Epoch 72/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5207 - accuracy: 0.7448
Epoch 73/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5531 - accuracy: 0.7279
Epoch 74/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5525 - accuracy: 0.7409
Epoch 75/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5620 - accuracy: 0.7305
Epoch 76/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5579 - accuracy: 0.7214
Epoch 77/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5273 - accuracy: 0.7591
Epoch 78/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5214 - accuracy: 0.7578
Epoch 79/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5325 - accuracy: 0.7344
Epoch 80/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5388 - accuracy: 0.7305
Epoch 81/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5332 - accuracy: 0.7266
Epoch 82/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5652 - accuracy: 0.7305
Epoch 83/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5418 - accuracy: 0.7305
Epoch 84/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5305 - accuracy: 0.7487
Epoch 85/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5306 - accuracy: 0.7422
Epoch 86/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5252 - accuracy: 0.7435
Epoch 87/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5349 - accuracy: 0.7461
Epoch 88/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5613 - accuracy: 0.7318
Epoch 89/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5270 - accuracy: 0.7526
Epoch 90/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5310 - accuracy: 0.7409
Epoch 91/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5240 - accuracy: 0.7461
Epoch 92/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5256 - accuracy: 0.7513
Epoch 93/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5544 - accuracy: 0.7396
Epoch 94/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5258 - accuracy: 0.7448
Epoch 95/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5362 - accuracy: 0.7422
Epoch 96/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5734 - accuracy: 0.7096
Epoch 97/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5518 - accuracy: 0.7174
Epoch 98/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5104 - accuracy: 0.7669
Epoch 99/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5095 - accuracy: 0.7448
Epoch 100/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5195 - accuracy: 0.7578
Epoch 101/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5121 - accuracy: 0.7643
Epoch 102/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5062 - accuracy: 0.7656
Epoch 103/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5120 - accuracy: 0.7539
Epoch 104/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5209 - accuracy: 0.7422
Epoch 105/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5249 - accuracy: 0.7409
Epoch 106/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5042 - accuracy: 0.7630
Epoch 107/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5326 - accuracy: 0.7357
Epoch 108/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5064 - accuracy: 0.7552
Epoch 109/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5118 - accuracy: 0.7552
Epoch 110/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5039 - accuracy: 0.7539
Epoch 111/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5254 - accuracy: 0.7474
Epoch 112/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5098 - accuracy: 0.7617
Epoch 113/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5236 - accuracy: 0.7344
Epoch 114/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5279 - accuracy: 0.7383
Epoch 115/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5024 - accuracy: 0.7591
Epoch 116/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5108 - accuracy: 0.7630
Epoch 117/150
77/77 [==============================] - 0s 1ms/step - loss: 0.4969 - accuracy: 0.7578
Epoch 118/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5111 - accuracy: 0.7591
Epoch 119/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5291 - accuracy: 0.7500
Epoch 120/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5249 - accuracy: 0.7370
Epoch 121/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5189 - accuracy: 0.7448
Epoch 122/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5076 - accuracy: 0.7695
Epoch 123/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5236 - accuracy: 0.7604
Epoch 124/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5321 - accuracy: 0.7422
Epoch 125/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5164 - accuracy: 0.7487
Epoch 126/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5109 - accuracy: 0.7565
Epoch 127/150
77/77 [==============================] - 0s 2ms/step - loss: 0.5567 - accuracy: 0.7409
Epoch 128/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5192 - accuracy: 0.7474
Epoch 129/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5361 - accuracy: 0.7448
Epoch 130/150
77/77 [==============================] - 0s 1ms/step - loss: 0.4935 - accuracy: 0.7617
Epoch 131/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5013 - accuracy: 0.7565
Epoch 132/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5419 - accuracy: 0.7292
Epoch 133/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5093 - accuracy: 0.7474
Epoch 134/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5276 - accuracy: 0.7487
Epoch 135/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5197 - accuracy: 0.7500
Epoch 136/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5150 - accuracy: 0.7526
Epoch 137/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5038 - accuracy: 0.7630
Epoch 138/150
77/77 [==============================] - 0s 1ms/step - loss: 0.4990 - accuracy: 0.7617
Epoch 139/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5280 - accuracy: 0.7318
Epoch 140/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5065 - accuracy: 0.7565
Epoch 141/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5479 - accuracy: 0.7500
Epoch 142/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5103 - accuracy: 0.7578
Epoch 143/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5086 - accuracy: 0.7604
Epoch 144/150
77/77 [==============================] - 0s 1ms/step - loss: 0.4952 - accuracy: 0.7747
Epoch 145/150
77/77 [==============================] - 0s 1ms/step - loss: 0.4927 - accuracy: 0.7669
Epoch 146/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5086 - accuracy: 0.7487
Epoch 147/150
77/77 [==============================] - 0s 1ms/step - loss: 0.4985 - accuracy: 0.7552
Epoch 148/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5147 - accuracy: 0.7513
Epoch 149/150
77/77 [==============================] - 0s 1ms/step - loss: 0.4875 - accuracy: 0.7591
Epoch 150/150
77/77 [==============================] - 0s 1ms/step - loss: 0.5098 - accuracy: 0.7435
###Markdown
Evaluate the keras model
###Code
_, accuracy = model.evaluate(X, y)
print('Accuracy: %.2f' % (accuracy*100))
###Output
24/24 [==============================] - 0s 976us/step - loss: 0.5205 - accuracy: 0.7370
Accuracy: 73.70
###Markdown
Make probability predictions with the model
###Code
predictions = model.predict(X)
# round predictions
rounded = [round(x[0]) for x in predictions]
rounded
predictions = model.predict_classes(X)
predictions
for i in range(5):
print('%s => %d (expected %d)' % (X[i].tolist(), predictions[i], y[i]))
###Output
[6.0, 148.0, 72.0, 35.0, 0.0, 33.6, 0.627, 50.0] => 1 (expected 1)
[1.0, 85.0, 66.0, 29.0, 0.0, 26.6, 0.351, 31.0] => 0 (expected 0)
[8.0, 183.0, 64.0, 0.0, 0.0, 23.3, 0.672, 32.0] => 1 (expected 1)
[1.0, 89.0, 66.0, 23.0, 94.0, 28.1, 0.167, 21.0] => 0 (expected 0)
[0.0, 137.0, 40.0, 35.0, 168.0, 43.1, 2.288, 33.0] => 1 (expected 1)
|
even-more-python-for-beginners-data-tools/Demo/test.ipynb | ###Markdown
Hello, world!This is a great way to leave myself some notes
###Code
print('Jupter Notebook')
name = 'Chrisopher'
print(name)
name
['Christopher', 'Susan']
import matplotlib.pyplot as plt
###Output
_____no_output_____ |
Tabel_Data/Machine_Learning/Unsupervised_Learning/association_analysis.ipynb | ###Markdown
アソシエーション分析* アソシエーション分析は大量の購買履歴データからセットで購入されている商品の組み合わせを探すための分析手法である* 以下ではOnlineRetailというデータを使いアソシエーション分析を行う* データマイニングなどでよく使われる* マーケットバスケット分析とも呼ばれる
###Code
#以下がアソシエーション分析に必要なコード
from mlxtend.frequent_patterns import apriori
from mlxtend.frequent_patterns import association_rules
#OnlineRetailデータセットをインストールする
import pandas as pd
df = pd.read_excel("https://archive.ics.uci.edu/ml/machine-learning-databases/00352/Online%20Retail.xlsx")
#データの中身を見る
df.head()
#InvoiceNoの先頭により発注種別、対象の国をドイツに限定する
df2 = df.copy()
df2['InvoiceNo2'] = df2['InvoiceNo'].map(lambda x: str(x)[0])
df2 = df2[df2['InvoiceNo2']=='5']
df3 = df2[df2['Country']=='Germany']
#InvoiceNo(発注番号)でグループを作り、グループのStockCode(商品番号)を並べその個数をカウント
temp1 = df3.groupby(['InvoiceNo','StockCode'])['Quantity'].sum()
temp1
#二段階のindexを持っているデータはunstack()を使うことで横文字のデータに変換できる
#fillna()でNullを0に置き換える
temp2 = temp1.unstack().fillna(0)
#購入数が1以上の商品はTrue、購入数が0の商品はFalseとする
association_df = temp2.apply(lambda x: x>0)
###Output
_____no_output_____
###Markdown
アソシエーション分析を行うアソシエーション分析は二段階で行う。 * アプリオリ分析 組み合わせの爆発が起きてしまうため、指示度という閾値を使いデータを厳選する。* ルール抽出 リフト値の値を設定し、それより大きいか小さいかでルール抽出をおこなう。
###Code
#アプリオリ分析を行う
freq_items1 = apriori(association_df, min_support = 0.06, use_colnames=True)
#アプリオリ分析の表示
freq_items1.sort_values('support',ascending=False)
#POSTと22326という商品が何かを確認する
df3[df3['StockCode']=='POST']
#以下よりPOSTはpostage(送料)のことなのが確認できる
#ルール抽出を行う
rules = association_rules(freq_items1, metric='lift', min_threshold=1)
#値の大きい順番に並び替える
rules = rules.sort_values('lift',ascending=False)
#indexをリセット
rules = rules.reset_index(drop=True)
#以下に表示されているものを確認すると、動物の絆創膏とサーカスの絆創膏が一番多く一緒に売れていることがわかる。
rules
df3[df3['StockCode']==22554]
df3[df3['StockCode']==22556]
###Output
_____no_output_____ |
nbs/21d-preprocessing-cat-other.ipynb | ###Markdown
ในข้อมูลแบบ Category ถ้าข้อมูลมีการแตกยิบย่อยมากเกินไป เช่น บาง Category มีแค่ 1 หรือ 2 Record หรือจำนวน Record แตกต่างกับ Category ใหญ่ ๆ เป็น 100 เป็น 1000 เท่า ข้อมูล Category เหล่านี้ อาจจะไม่ได้ช่วยโมเดล Machine Learning ในการเรียนรู้ก็ได้ ทางแก้คือ เราจะ Group Category เล็ก ๆ เหล่านั้นรวมออกมาเป็น Category ใหม่ ตั้งชื่อว่า Other การสร้าง Other Category มีข้อดีอีกอย่างคือ ถ้ามีข้อมูล Category ใหม่หลุดมา เราอาจจะเอาใส่ไว้ใน Other ได้เลย โดยที่ไม่ต้องแก้โปรแกรมเยอะ 0. Magic
###Code
%reload_ext autoreload
%autoreload 2
%matplotlib inline
###Output
_____no_output_____
###Markdown
1. Import
###Code
import pandas as pd
import matplotlib.pyplot as plt
###Output
_____no_output_____
###Markdown
2. Data เราจะสมมติข้อมูล ผู้เข้าร่วมงานสัมมนา ขึ้นมา
###Code
df = pd.DataFrame({'Name': ["Mister A", "Mister B", "Mister C", "Mister D", "Mister E", "Mister F", "Mister G", "Mister H", "Mister I", "Mister J", "Mister K", "Mister L", "Mister M", "Mister N", "Mister O", "Mister P", "Mister Q", "Mister R", "Mister S", "Mister T", "Mister U", "Mister V", "Mister W", "Mister X"],
'Age': [22, 33, 35, 31, 41, 51, 27, 33, 37, 31, 42, 57, 22, 33, 35, 31, 41, 51, 27, 33, 37, 31, 42, 57],
'Country': ["Thai", "Laos", "Laos", "Thai", "Brazil", "Ethiopia", "Myanmar", "Canada", "Laos", "Thai", "Thai", "Myanmar", "Thai", "Laos", "Laos", "Thai", "Myanmar", "Myanmar", "Myanmar", "Laos", "Laos", "Thai", "Thai", "Myanmar"],
})
df
###Output
_____no_output_____
###Markdown
3. Preprocessing 3.1 Other Category Before การที่เราจะ Group Category เล็ก รวมกันเป็น Other เราต้องเข้าใจข้อมูลก่อน นับดูก่อน ว่าแต่ละ Category มีสมาชิกเท่าไร
###Code
df["Country"].value_counts()
###Output
_____no_output_____
###Markdown
ในเคสนี้ เราจะเลือก Top 3 Category ออกมาก่อน
###Code
top3 = df["Country"].value_counts().nlargest(3).index
top3
###Output
_____no_output_____
###Markdown
After เราจะ Group Category ให้เหลือเป็น 3 + 1 Category (Top 3 + Other)
###Code
df["Country_NEW"] = df["Country"].where(df["Country"].isin(top3), other="Other")
df
###Output
_____no_output_____
###Markdown
นับค่า Feature ใหม่ ที่เพิ่งสร้างขึ้นมา
###Code
df["Country_NEW"].value_counts()
###Output
_____no_output_____
###Markdown
4. สรุป 1. เราได้ Group รวม Category เล็ก ๆ รวมเข้าเป็น Category ใหม่ ตั้งชื่อว่า Other ซึ่งเราต้องตัดสินใจเลือกว่าเล็ก คือแค่ไหน จากความเข้าใจในข้อมูล ด้วยการทำ [Exploratory Data Analysis (EDA)](https://www.bualabs.com/archives/2297/exploratory-data-analysis-eda-pandas-profiling-pandas-dataframe-pandas-ep-6/)1. เราสามารถสร้าง Other Category อย่างง่าย ด้วย โค้ดไม่กี่บรรทัด และ Pandas Dataframe1. เราสามารถนำเทคนิคนี้ ไปใช้ร่วมกับ [Preprocessing](https://www.bualabs.com/archives/2085/what-is-preprocessing-handle-missing-value-fill-na-null-nan-before-feedforward-machine-learning-preprocessing-ep-1/) แบบอื่น ๆ เพื่อจัดเตรียมข้อมูล เพิ่มประสิทธิภาพการเรียนรู้ให้กับโมเดลของเรา Credit * https://www.facebook.com/DataScienceSchool/photos/a.1499945753419628/2565166906897502/?type=3&theater
###Code
###Output
_____no_output_____ |
Python-API/apl/notebooks/HANA_ML_APL_CONFUSION_MATRIX.ipynb | ###Markdown
Python HANA ML API Train a model and show the confusion matrix. Train the model Create an HANA Dataframe for the training data
###Code
import pandas as pd
# Connect using the HANA secure user store
from hana_ml import dataframe as hd
conn = hd.ConnectionContext(userkey='MLMDA_KEY')
# Get Training Data
sql_cmd = 'SELECT * FROM "APL_SAMPLES"."AUTO_CLAIMS_FRAUD" ORDER BY CLAIM_ID'
training_data = hd.DataFrame(conn, sql_cmd)
###Output
_____no_output_____
###Markdown
Put a subset of the data in a Pandas Dataframe and display it
###Code
training_data.head(5).collect()
###Output
_____no_output_____
###Markdown
Build a Classification model with APL Ridge Regression
###Code
# Create the model
from hana_ml.algorithms.apl.classification import AutoClassifier
model = AutoClassifier(conn_context=conn)
# Train the model
model.fit(training_data, label='IS_FRAUD', key='CLAIM_ID')
###Output
_____no_output_____
###Markdown
Confusion Matrix Define Functions
###Code
indicators_table_name = None
for table_name in model._artifact_tables:
if table_name.startswith('#INDICATORS_'):
indicators_table_name = table_name
def create_artifact_table(conn, table_name, table_spec):
conn = model.conn_context.connection
cursor = conn.cursor()
try:
cursor.execute(f'drop table {table_name}')
except:
pass
cursor.execute(f'create local temporary table {table_name} {table_spec}')
def get_confusion_matrix():
conn = model.conn_context.connection
cursor = conn.cursor()
model_table_name = model.model_table_.name # the temp table where the model is saved
# --- Create temp tables for input / output
create_artifact_table(conn=conn,
table_name='#FUNC_HEADER',
table_spec='(KEY NVARCHAR(50), VALUE NVARCHAR(255))')
create_artifact_table(conn=conn,
table_name='#OPERATION_CONFIG',
table_spec='(KEY NVARCHAR(1000), VALUE NCLOB, CONTEXT NVARCHAR(100))')
create_artifact_table(conn=conn,
table_name='#SUMMARY',
table_spec='(OID NVARCHAR(50), KEY NVARCHAR(100), VALUE NVARCHAR(100))')
create_artifact_table(conn=conn,
table_name='#CONF_MATRIX',
table_spec='(OID VARCHAR(50),VARIABLE VARCHAR(255),TARGET VARCHAR(255),KEY VARCHAR(100),'
'VALUE NCLOB,DETAIL NCLOB)')
# Call APL
sql = 'call "SAP_PA_APL"."sap.pa.apl.base::COMPUTE_CONFUSION_MATRIX"(#FUNC_HEADER, #OPERATION_CONFIG, {indicators_input}, #CONF_MATRIX) with overview'
sql = sql.format(indicators_input=indicators_table_name)
cursor.execute(sql)
###Output
_____no_output_____
###Markdown
Calling COMPUTE_CONFUSION_MATRIX
###Code
get_confusion_matrix()
###Output
_____no_output_____
###Markdown
Put indicators data in a Pandas Dataframe
###Code
sql_cmd = 'SELECT * FROM #CONF_MATRIX'
hf = hd.DataFrame(conn, sql_cmd)
indicators_df = hf.collect()
indicators_df = indicators_df[['KEY','VALUE']]
###Output
_____no_output_____
###Markdown
Matrix In Absolute Values
###Code
df = indicators_df[indicators_df.KEY.isin(['True_Positive', 'True_Negative', 'False_Negative', 'False_Positive'])].copy()
df['VALUE'] = df['VALUE'].astype(int)
df['KEY'] = df['KEY'].str.replace('True_Positive', 'Yes Yes')
df['KEY'] = df['KEY'].str.replace('True_Negative', 'No No')
df['KEY'] = df['KEY'].str.replace('False_Negative', 'Yes No')
df['KEY'] = df['KEY'].str.replace('False_Positive', 'No Yes')
df[['Actual', 'Predicted']] = df.KEY.str.split(expand=True)
df.drop('KEY', axis=1, inplace=True)
df.columns = ['Nb of Cases', 'Actual', 'Predicted']
pd.pivot_table(df,index=["Actual"], values=["Nb of Cases"], columns=["Predicted"])
###Output
_____no_output_____
###Markdown
Matrix In Percentage
###Code
df = indicators_df[indicators_df.KEY.isin(['Percent_True_Positive', 'Percent_True_Negative', 'Percent_False_Negative', 'Percent_False_Positive'])].copy()
df['VALUE'] = df['VALUE'].astype(float).round(2)
df['KEY'] = df['KEY'].str.replace('Percent_True_Positive', 'Yes Yes')
df['KEY'] = df['KEY'].str.replace('Percent_True_Negative', 'No No')
df['KEY'] = df['KEY'].str.replace('Percent_False_Negative', 'Yes No')
df['KEY'] = df['KEY'].str.replace('Percent_False_Positive', 'No Yes')
df[['Actual', 'Predicted']] = df.KEY.str.split(expand=True)
df.drop('KEY', axis=1, inplace=True)
df.columns = ['% Cases', 'Actual', 'Predicted']
pd.pivot_table(df,index=["Actual"], values=["% Cases"], columns=["Predicted"])
###Output
_____no_output_____
###Markdown
Confusion Matrix Indicators
###Code
df = indicators_df[indicators_df.KEY.isin(['Accuracy', 'Sensitivity', 'Specificity', 'Precision', 'F1_Score'])].copy()
df['VALUE'] = df['VALUE'].astype(float).round(4)
df.columns = ['Indicator', 'Value']
df.style.hide_index()
###Output
_____no_output_____ |
documentation/model_presimulation.ipynb | ###Markdown
AMICI Python example "presimulation"In this example we will explore some more options for the initialization of experimental conditions, including how to reset initial conditions based on changing values for fixedParameters as well as an additional presimulation phase on top of preequilibration
###Code
# SBML model we want to import
sbml_file = 'model_presimulation.xml'
# Name of the model that will also be the name of the python module
model_name = 'model_presimulation'
# Directory to which the generated model code is written
model_output_dir = model_name
import libsbml
import amici
import amici.plotting
import os
import sys
import importlib
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
###Output
_____no_output_____
###Markdown
Model LoadingHere we load a simple model of protein phosphorylation that can be inhibited by a drug. This model was created using PySB (see `createModel.py`)
###Code
sbml_reader = libsbml.SBMLReader()
sbml_doc = sbml_reader.readSBML(sbml_file)
sbml_model = sbml_doc.getModel()
dir(sbml_doc)
print('Species: ', [(s.getId(),s.getName()) for s in sbml_model.getListOfSpecies()])
print('\nReactions:')
for reaction in sbml_model.getListOfReactions():
reactants = ' + '.join(['%s %s'%(int(r.getStoichiometry()) if r.getStoichiometry() > 1 else '', r.getSpecies()) for r in reaction.getListOfReactants()])
products = ' + '.join(['%s %s'%(int(r.getStoichiometry()) if r.getStoichiometry() > 1 else '', r.getSpecies()) for r in reaction.getListOfProducts()])
reversible = '<' if reaction.getReversible() else ''
print('%3s: %10s %1s->%10s\t\t[%s]' % (reaction.getName(),
reactants,
reversible,
products,
libsbml.formulaToL3String(reaction.getKineticLaw().getMath())))
print('Parameters: ', [(p.getId(),p.getName()) for p in sbml_model.getListOfParameters()])
# Create an SbmlImporter instance for our SBML model
sbml_importer = amici.SbmlImporter(sbml_file)
###Output
_____no_output_____
###Markdown
For this example we want specify the initial drug and kinase concentrations as experimental conditions. Accordingly we specify them as fixedParameters.
###Code
fixedParameters = ['DRUG_0','KIN_0']
###Output
_____no_output_____
###Markdown
The SBML model specifies a single observable named `pPROT` which describes the fraction of phosphorylated Protein. We load this observable using `amici.assignmentRules2observables`.
###Code
# Retrieve model output names and formulae from AssignmentRules and remove the respective rules
observables = amici.assignmentRules2observables(
sbml_importer.sbml, # the libsbml model object
filter_function=lambda variable: variable.getName() == 'pPROT'
)
print('Observables:', observables)
###Output
Observables: {'__obs0': {'name': 'pPROT', 'formula': '__s5'}}
###Markdown
Now the model is ready for compilation:
###Code
sbml_importer.sbml2amici(model_name,
model_output_dir,
verbose=False,
observables=observables,
constant_parameters=fixedParameters)
sys.path.insert(0, os.path.abspath(model_output_dir))
# load the compiled module
model_module = importlib.import_module(model_name)
###Output
_____no_output_____
###Markdown
To simulate the model we need to create an instance via the `getModel()` method in the generated model module.
###Code
# Create Model instance
model = model_module.getModel()
# set timepoints for which we want to simulate the model
# Create solver instance
solver = model.getSolver()
###Output
_____no_output_____
###Markdown
The only thing we need to simulate the model is a timepoint vector, which can be specified using the `setTimepoints()` method. If we do not specify any additional options, the default values for fixedParameters and Parameters that were specified in the SBML file will be used.
###Code
# Run simulation using default model parameters and solver options
model.setTimepoints(np.linspace(0, 60, 60))
rdata = amici.runAmiciSimulation(model, solver)
amici.plotting.plotObservableTrajectories(rdata)
###Output
_____no_output_____
###Markdown
Simulation options can be specified either in the Model or in an ExpData object. The ExpData object can also carry experimental data. To initialize an ExpData object from simulation routines, amici offers some convenient constructors. In the following we will initialize an ExpData object from simulation results, but add noise with standard deviation `0.1` and specify the standard deviation accordingly. Moreover, we will specify custom values for `DRUG_0=0` and `KIN_0=2`. If fixedParameter is specfied in an ExpData object, runAmiciSimulation will use those parameters instead of the ones specified in the Model object.
###Code
edata = amici.ExpData(rdata, 0.1, 0.0)
edata.fixedParameters = [0,2]
rdata = amici.runAmiciSimulation(model, solver, edata)
amici.plotting.plotObservableTrajectories(rdata)
###Output
_____no_output_____
###Markdown
For many biological systems, it is reasonable to assume that they start in a steady state. In this example we want to specify an experiment where a pretreatment with a drug is performed _before_ the kinase is added. We assume that the pretreatment is sufficiently long such that the system reaches steadystate before the kinase is added. To implement this in amici, we can specify `fixedParametersPreequilibration` in the ExpData object. Here we set `DRUG_0=3` and `KIN_0=0` for the preequilibration.
###Code
edata.fixedParametersPreequilibration = [3,0]
rdata = amici.runAmiciSimulation(model, solver, edata)
amici.plotting.plotObservableTrajectories(rdata)
###Output
_____no_output_____
###Markdown
The resulting trajectory is definitely not what one may expect. The problem is that the `DRUG_0` and `KIN_0` set initial condtions for species in the model. By default these initial conditions are only applied at the very beginning of the simulation, i.e., before the preequilibration. Accordingly, the fixedParameters that we specified do not have any effect. To fix this, we need to activate reinitialization of states that depend on fixedParameters via `ExpData.reinitializeFixedParameterInitialStates`
###Code
edata.reinitializeFixedParameterInitialStates = True
###Output
_____no_output_____
###Markdown
With this option activated, the kinase concentration will be reinitialized after the preequilibration and we will see the expected change in fractional phosphorylation:
###Code
rdata = amici.runAmiciSimulation(model, solver, edata)
amici.plotting.plotObservableTrajectories(rdata)
###Output
_____no_output_____
###Markdown
On top of preequilibration, we can also specify presimulation. This option can be used to specify pretreatments where the system is not assumed to reach steadystate. Presimulation can be activated by specifying `t_presim` and `edata.fixedParametersPresimulation`. If both `fixedParametersPresimulation` and `fixedParametersPreequilibration` are specified, preequilibration will be performed first, followed by presimulation, followed by regular simulation. For this example we specify `DRUG_0=10` and `KIN_0=0` for the presimulation and `DRUG_0=10` and `KIN_0=2` for the regular simulation. We do not overwrite the `DRUG_0=3` and `KIN_0=0` that was previously specified for preequilibration.
###Code
edata.t_presim = 10
edata.fixedParametersPresimulation = [10.0,0.0]
edata.fixedParameters = [10.0,2.0]
print(edata.fixedParametersPreequilibration)
print(edata.fixedParametersPresimulation)
print(edata.fixedParameters)
rdata = amici.runAmiciSimulation(model, solver, edata)
amici.plotting.plotObservableTrajectories(rdata)
###Output
(3.0, 0.0)
(10.0, 0.0)
(10.0, 2.0)
|
assignment3/Self_Supervised_Learning.ipynb | ###Markdown
Self-Supervised Learning What is self-supervised learning?Modern day machine learning requires lots of labeled data. But often times it's challenging and/or expensive to obtain large amounts of human-labeled data. Is there a way we could ask machines to automatically learn a model which can generate good visual representations without a labeled dataset? Yes, enter self-supervised learning! Self-supervised learning (SSL) allows models to automatically learn a "good" representation space using the data in a given dataset without the need for their labels. Specifically, if our dataset were a bunch of images, then self-supervised learning allows a model to learn and generate a "good" representation vector for images. The reason SSL methods have seen a surge in popularity is because the learnt model continues to perform well on other datasets as well i.e. new datasets on which the model was not trained on! What makes a "good" representation?A "good" representation vector needs to capture the important features of the image as it relates to the rest of the dataset. This means that images in the dataset representing semantically similar entities should have similar representation vectors, and different images in the dataset should have different representation vectors. For example, two images of an apple should have similar representation vectors, while an image of an apple and an image of a banana should have different representation vectors. Contrastive Learning: SimCLRRecently, [SimCLR](https://arxiv.org/pdf/2002.05709.pdf) introduces a new architecture which uses **contrastive learning** to learn good visual representations. Contrastive learning aims to learn similar representations for similar images and different representations for different images. As we will see in this notebook, this simple idea allows us to train a surprisingly good model without using any labels.Specifically, for each image in the dataset, SimCLR generates two differently augmented views of that image, called a **positive pair**. Then, the model is encouraged to generate similar representation vectors for this pair of images. See below for an illustration of the architecture (Figure 2 from the paper).
###Code
# Run this cell to view the SimCLR architecture.
from IPython.display import Image
Image('images/simclr_fig2.png', width=500)
###Output
_____no_output_____
###Markdown
Given an image **x**, SimCLR uses two different data augmentation schemes **t** and **t'** to generate the positive pair of images **$\hat{x}_i$** and **$\hat{x}_j$**. $f$ is a basic encoder net that extracts representation vectors from the augmented data samples, which yields **$h_i$** and **$h_j$**, respectively. Finally, a small neural network projection head $g$ maps the representation vectors to the space where the contrastive loss is applied. The goal of the contrastive loss is to maximize agreement between the final vectors **$z_i = g(h_i)$** and **$z_j = g(h_j)$**. We will discuss the contrastive loss in more detail later, and you will get to implement it.After training is completed, we throw away the projection head $g$ and only use $f$ and the representation $h$ to perform downstream tasks, such as classification. You will get a chance to finetune a layer on top of a trained SimCLR model for a classification task and compare its performance with a baseline model (without self-supervised learning). Pretrained WeightsFor your convenience, we have given you pretrained weights (trained for ~18 hours on CIFAR-10) for the SimCLR model. Run the following cell to download pretrained model weights to be used later. (This will take ~1 minute)
###Code
%%bash
DIR=pretrained_model/
if [ ! -d "$DIR" ]; then
mkdir "$DIR"
fi
URL=http://downloads.cs.stanford.edu/downloads/cs231n/pretrained_simclr_model.pth
FILE=pretrained_model/pretrained_simclr_model.pth
if [ ! -f "$FILE" ]; then
echo "Downloading weights..."
wget "$URL" -O "$FILE"
fi
# Setup cell.
%pip install thop
import torch
import os
import importlib
import pandas as pd
import numpy as np
import torch.optim as optim
import torch.nn as nn
import random
from thop import profile, clever_format
from torch.utils.data import DataLoader
from torchvision.datasets import CIFAR10
import matplotlib.pyplot as plt
%matplotlib inline
%load_ext autoreload
%autoreload 2
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
###Output
Requirement already satisfied: thop in /usr/local/lib/python3.7/dist-packages (0.0.31.post2005241907)
Requirement already satisfied: torch>=1.0.0 in /usr/local/lib/python3.7/dist-packages (from thop) (1.10.0+cu111)
Requirement already satisfied: typing-extensions in /usr/local/lib/python3.7/dist-packages (from torch>=1.0.0->thop) (3.10.0.2)
###Markdown
Data AugmentationOur first step is to perform data augmentation. Implement the `compute_train_transform()` function in `cs231n/simclr/data_utils.py` to apply the following random transformations:1. Randomly resize and crop to 32x32.2. Horizontally flip the image with probability 0.53. With a probability of 0.8, apply color jitter (see `compute_train_transform()` for definition)4. With a probability of 0.2, convert the image to grayscale Now complete `compute_train_transform()` and `CIFAR10Pair.__getitem__()` in `cs231n/simclr/data_utils.py` to apply the data augmentation transform and generate **$\hat{x}_i$** and **$\hat{x}_j$**. Test to make sure that your data augmentation code is correct:
###Code
from cs231n.simclr.data_utils import *
from cs231n.simclr.contrastive_loss import *
answers = torch.load('simclr_sanity_check.key')
%pwd
from PIL import Image
import torchvision
from torchvision.datasets import CIFAR10
def test_data_augmentation(correct_output=None):
train_transform = compute_train_transform(seed=2147483647)
trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=train_transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=2, shuffle=False, num_workers=2)
dataiter = iter(trainloader)
images, labels = dataiter.next()
img = torchvision.utils.make_grid(images)
img = img / 2 + 0.5 # unnormalize
npimg = img.numpy()
plt.imshow(np.transpose(npimg, (1, 2, 0)))
plt.show()
output = images
print("Maximum error in data augmentation: %g"%rel_error( output.numpy(), correct_output.numpy()))
# Should be less than 1e-07.
test_data_augmentation(answers['data_augmentation'])
###Output
Files already downloaded and verified
###Markdown
Base Encoder and Projection HeadThe next steps are to apply the base encoder and projection head to the augmented samples **$\hat{x}_i$** and **$\hat{x}_j$**.The base encoder $f$ extracts representation vectors for the augmented samples. The SimCLR paper found that using deeper and wider models improved performance and thus chose [ResNet](https://arxiv.org/pdf/1512.03385.pdf) to use as the base encoder. The output of the base encoder are the representation vectors **$h_i = f(\hat{x}_i$)** and **$h_j = f(\hat{x}_j$)**.The projection head $g$ is a small neural network that maps the representation vectors **$h_i$** and **$h_j$** to the space where the contrastive loss is applied. The paper found that using a nonlinear projection head improved the representation quality of the layer before it. Specifically, they used a MLP with one hidden layer as the projection head $g$. The contrastive loss is then computed based on the outputs **$z_i = g(h_i$)** and **$z_j = g(h_j$)**.We provide implementations of these two parts in `cs231n/simclr/model.py`. Please skim through the file and make sure you understand the implementation. SimCLR: Contrastive LossA mini-batch of $N$ training images yields a total of $2N$ data-augmented examples. For each positive pair $(i, j)$ of augmented examples, the contrastive loss function aims to maximize the agreement of vectors $z_i$ and $z_j$. Specifically, the loss is the normalized temperature-scaled cross entropy loss and aims to maximize the agreement of $z_i$ and $z_j$ relative to all other augmented examples in the batch: $$l \; (i, j) = -\log \frac{\exp (\;\text{sim}(z_i, z_j)\; / \;\tau) }{\sum_{k=1}^{2N} \mathbb{1}_{k \neq i} \exp (\;\text{sim} (z_i, z_k) \;/ \;\tau) }$$ where $\mathbb{1} \in \{0, 1\}$ is an indicator function that outputs $1$ if $k\neq i$ and $0$ otherwise. $\tau$ is a temperature parameter that determines how fast the exponentials increase.sim$(z_i, z_j) = \frac{z_i \cdot z_j}{|| z_i || || z_j ||}$ is the (normalized) dot product between vectors $z_i$ and $z_j$. The higher the similarity between $z_i$ and $z_j$, the larger the dot product is, and the larger the numerator becomes. The denominator normalizes the value by summing across $z_i$ and all other augmented examples $k$ in the batch. The range of the normalized value is $(0, 1)$, where a high score close to $1$ corresponds to a high similarity between the positive pair $(i, j)$ and low similarity between $i$ and other augmented examples $k$ in the batch. The negative log then maps the range $(0, 1)$ to the loss values $(\inf, 0)$. The total loss is computed across all positive pairs $(i, j)$ in the batch. Let $z = [z_1, z_2, ..., z_{2N}]$ include all the augmented examples in the batch, where $z_{1}...z_{N}$ are outputs of the left branch, and $z_{N+1}...z_{2N}$ are outputs of the right branch. Thus, the positive pairs are $(z_{k}, z_{k + N})$ for $\forall k \in [1, N]$. Then, the total loss $L$ is: $$L = \frac{1}{2N} \sum_{k=1}^N [ \; l(k, \;k+N) + l(k+N, \;k)\;]$$ **NOTE:** this equation is slightly different from the one in the paper. We've rearranged the ordering of the positive pairs in the batch, so the indices are different. The rearrangement makes it easier to implement the code in vectorized form.We'll walk through the steps of implementing the loss function in vectorized form. Implement the functions `sim`, `simclr_loss_naive` in `cs231n/simclr/contrastive_loss.py`. Test your code by running the sanity checks below.
###Code
from cs231n.simclr.contrastive_loss import *
answers = torch.load('simclr_sanity_check.key')
def test_sim(left_vec, right_vec, correct_output):
output = sim(left_vec, right_vec).cpu().numpy()
print("Maximum error in sim: %g"%rel_error(correct_output.numpy(), output))
# Should be less than 1e-07.
test_sim(answers['left'][0], answers['right'][0], answers['sim'][0])
test_sim(answers['left'][1], answers['right'][1], answers['sim'][1])
def test_loss_naive(left, right, tau, correct_output):
naive_loss = simclr_loss_naive(left, right, tau).item()
print("Maximum error in simclr_loss_naive: %g"%rel_error(correct_output, naive_loss))
# Should be less than 1e-07.
test_loss_naive(answers['left'], answers['right'], 5.0, answers['loss']['5.0'])
test_loss_naive(answers['left'], answers['right'], 1.0, answers['loss']['1.0'])
###Output
Maximum error in simclr_loss_naive: 0
Maximum error in simclr_loss_naive: 5.65617e-08
###Markdown
Now implement the vectorized version by implementing `sim_positive_pairs`, `compute_sim_matrix`, `simclr_loss_vectorized` in `cs231n/simclr/contrastive_loss.py`. Test your code by running the sanity checks below.
###Code
def test_sim_positive_pairs(left, right, correct_output):
sim_pair = sim_positive_pairs(left, right).cpu().numpy()
print("Maximum error in sim_positive_pairs: %g"%rel_error(correct_output.numpy(), sim_pair))
# Should be less than 1e-07.
test_sim_positive_pairs(answers['left'], answers['right'], answers['sim'])
def test_sim_matrix(left, right, correct_output):
out = torch.cat([left, right], dim=0)
sim_matrix = compute_sim_matrix(out).cpu()
assert torch.isclose(sim_matrix, correct_output).all(), "correct: {}. got: {}".format(correct_output, sim_matrix)
print("Test passed!")
test_sim_matrix(answers['left'], answers['right'], answers['sim_matrix'])
def test_loss_vectorized(left, right, tau, correct_output):
vec_loss = simclr_loss_vectorized(left, right, tau, device).item()
print("Maximum error in loss_vectorized: %g"%rel_error(correct_output, vec_loss))
# Should be less than 1e-07.
test_loss_vectorized(answers['left'], answers['right'], 5.0, answers['loss']['5.0'])
test_loss_vectorized(answers['left'], answers['right'], 1.0, answers['loss']['1.0'])
###Output
Maximum error in loss_vectorized: 0
Maximum error in loss_vectorized: 1.13123e-07
###Markdown
Implement the train functionComplete the `train()` function in `cs231n/simclr/utils.py` to obtain the model's output and use `simclr_loss_vectorized` to compute the loss. (Please take a look at the `Model` class in `cs231n/simclr/model.py` to understand the model pipeline and the returned values)
###Code
from cs231n.simclr.data_utils import *
from cs231n.simclr.model import *
from cs231n.simclr.utils import *
###Output
_____no_output_____
###Markdown
Train the SimCLR modelRun the following cells to load in the pretrained weights and continue to train a little bit more. This part will take ~10 minutes and will output to `pretrained_model/trained_simclr_model.pth`.**NOTE:** Don't worry about logs such as '_[WARN] Cannot find rule for ..._'. These are related to another module used in the notebook. You can verify the integrity of your code changes through our provided prompts and comments.
###Code
# Do not modify this cell.
feature_dim = 128
temperature = 0.5
k = 200
batch_size = 64
epochs = 1
temperature = 0.5
percentage = 0.5
pretrained_path = './pretrained_model/pretrained_simclr_model.pth'
# Prepare the data.
train_transform = compute_train_transform()
train_data = CIFAR10Pair(root='data', train=True, transform=train_transform, download=True)
train_data = torch.utils.data.Subset(train_data, list(np.arange(int(len(train_data)*percentage))))
train_loader = DataLoader(train_data, batch_size=batch_size, shuffle=True, num_workers=12, pin_memory=True, drop_last=True)
test_transform = compute_test_transform()
memory_data = CIFAR10Pair(root='data', train=True, transform=test_transform, download=True)
memory_loader = DataLoader(memory_data, batch_size=batch_size, shuffle=False, num_workers=12, pin_memory=True)
test_data = CIFAR10Pair(root='data', train=False, transform=test_transform, download=True)
test_loader = DataLoader(test_data, batch_size=batch_size, shuffle=False, num_workers=12, pin_memory=True)
# Set up the model and optimizer config.
model = Model(feature_dim)
model.load_state_dict(torch.load(pretrained_path, map_location='cpu'), strict=False)
model = model.to(device)
flops, params = profile(model, inputs=(torch.randn(1, 3, 32, 32).to(device),))
flops, params = clever_format([flops, params])
print('# Model Params: {} FLOPs: {}'.format(params, flops))
optimizer = optim.Adam(model.parameters(), lr=1e-3, weight_decay=1e-6)
c = len(memory_data.classes)
# Training loop.
results = {'train_loss': [], 'test_acc@1': [], 'test_acc@5': []} #<< -- output
if not os.path.exists('results'):
os.mkdir('results')
best_acc = 0.0
for epoch in range(1, epochs + 1):
train_loss = train(model, train_loader, optimizer, epoch, epochs, batch_size=batch_size, temperature=temperature, device=device)
results['train_loss'].append(train_loss)
test_acc_1, test_acc_5 = test(model, memory_loader, test_loader, epoch, epochs, c, k=k, temperature=temperature, device=device)
results['test_acc@1'].append(test_acc_1)
results['test_acc@5'].append(test_acc_5)
# Save statistics.
if test_acc_1 > best_acc:
best_acc = test_acc_1
torch.save(model.state_dict(), './pretrained_model/trained_simclr_model.pth')
###Output
Files already downloaded and verified
###Markdown
Finetune a Linear Layer for Classification!Now it's time to put the representation vectors to the test!We remove the projection head from the SimCLR model and slap on a linear layer to finetune for a simple classification task. All layers before the linear layer are frozen, and only the weights in the final linear layer are trained. We compare the performance of the SimCLR + finetuning model against a baseline model, where no self-supervised learning is done beforehand, and all weights in the model are trained. You will get to see for yourself the power of self-supervised learning and how the learned representation vectors improve downstream task performance. Baseline: Without Self-Supervised LearningFirst, let's take a look at the baseline model. We'll remove the projection head from the SimCLR model and slap on a linear layer to finetune for a simple classification task. No self-supervised learning is done beforehand, and all weights in the model are trained. Run the following cells. **NOTE:** Don't worry if you see low but reasonable performance.
###Code
class Classifier(nn.Module):
def __init__(self, num_class):
super(Classifier, self).__init__()
# Encoder.
self.f = Model().f
# Classifier.
self.fc = nn.Linear(2048, num_class, bias=True)
def forward(self, x):
x = self.f(x)
feature = torch.flatten(x, start_dim=1)
out = self.fc(feature)
return out
# Do not modify this cell.
feature_dim = 128
temperature = 0.5
k = 200
batch_size = 128
epochs = 10
percentage = 0.1
train_transform = compute_train_transform()
train_data = CIFAR10(root='data', train=True, transform=train_transform, download=True)
trainset = torch.utils.data.Subset(train_data, list(np.arange(int(len(train_data)*percentage))))
train_loader = DataLoader(trainset, batch_size=batch_size, shuffle=True, num_workers=16, pin_memory=True)
test_transform = compute_test_transform()
test_data = CIFAR10(root='data', train=False, transform=test_transform, download=True)
test_loader = DataLoader(test_data, batch_size=batch_size, shuffle=False, num_workers=16, pin_memory=True)
model = Classifier(num_class=len(train_data.classes)).to(device)
for param in model.f.parameters():
param.requires_grad = False
flops, params = profile(model, inputs=(torch.randn(1, 3, 32, 32).to(device),))
flops, params = clever_format([flops, params])
print('# Model Params: {} FLOPs: {}'.format(params, flops))
optimizer = optim.Adam(model.fc.parameters(), lr=1e-3, weight_decay=1e-6)
no_pretrain_results = {'train_loss': [], 'train_acc@1': [], 'train_acc@5': [],
'test_loss': [], 'test_acc@1': [], 'test_acc@5': []}
best_acc = 0.0
for epoch in range(1, epochs + 1):
train_loss, train_acc_1, train_acc_5 = train_val(model, train_loader, optimizer, epoch, epochs, device='cuda')
no_pretrain_results['train_loss'].append(train_loss)
no_pretrain_results['train_acc@1'].append(train_acc_1)
no_pretrain_results['train_acc@5'].append(train_acc_5)
test_loss, test_acc_1, test_acc_5 = train_val(model, test_loader, None, epoch, epochs)
no_pretrain_results['test_loss'].append(test_loss)
no_pretrain_results['test_acc@1'].append(test_acc_1)
no_pretrain_results['test_acc@5'].append(test_acc_5)
if test_acc_1 > best_acc:
best_acc = test_acc_1
# Print the best test accuracy.
print('Best top-1 accuracy without self-supervised learning: ', best_acc)
###Output
Files already downloaded and verified
###Markdown
With Self-Supervised LearningLet's see how much improvement we get with self-supervised learning. Here, we pretrain the SimCLR model using the simclr loss you wrote, remove the projection head from the SimCLR model, and use a linear layer to finetune for a simple classification task.
###Code
# Do not modify this cell.
feature_dim = 128
temperature = 0.5
k = 200
batch_size = 128
epochs = 10
percentage = 0.1
pretrained_path = './pretrained_model/trained_simclr_model.pth'
train_transform = compute_train_transform()
train_data = CIFAR10(root='data', train=True, transform=train_transform, download=True)
trainset = torch.utils.data.Subset(train_data, list(np.arange(int(len(train_data)*percentage))))
train_loader = DataLoader(trainset, batch_size=batch_size, shuffle=True, num_workers=16, pin_memory=True)
test_transform = compute_test_transform()
test_data = CIFAR10(root='data', train=False, transform=test_transform, download=True)
test_loader = DataLoader(test_data, batch_size=batch_size, shuffle=False, num_workers=16, pin_memory=True)
model = Classifier(num_class=len(train_data.classes))
model.load_state_dict(torch.load(pretrained_path, map_location='cpu'), strict=False)
model = model.to(device)
for param in model.f.parameters():
param.requires_grad = False
flops, params = profile(model, inputs=(torch.randn(1, 3, 32, 32).to(device),))
flops, params = clever_format([flops, params])
print('# Model Params: {} FLOPs: {}'.format(params, flops))
optimizer = optim.Adam(model.fc.parameters(), lr=1e-3, weight_decay=1e-6)
pretrain_results = {'train_loss': [], 'train_acc@1': [], 'train_acc@5': [],
'test_loss': [], 'test_acc@1': [], 'test_acc@5': []}
best_acc = 0.0
for epoch in range(1, epochs + 1):
train_loss, train_acc_1, train_acc_5 = train_val(model, train_loader, optimizer, epoch, epochs)
pretrain_results['train_loss'].append(train_loss)
pretrain_results['train_acc@1'].append(train_acc_1)
pretrain_results['train_acc@5'].append(train_acc_5)
test_loss, test_acc_1, test_acc_5 = train_val(model, test_loader, None, epoch, epochs)
pretrain_results['test_loss'].append(test_loss)
pretrain_results['test_acc@1'].append(test_acc_1)
pretrain_results['test_acc@5'].append(test_acc_5)
if test_acc_1 > best_acc:
best_acc = test_acc_1
# Print the best test accuracy. You should see a best top-1 accuracy of >=70%.
print('Best top-1 accuracy with self-supervised learning: ', best_acc)
###Output
Files already downloaded and verified
###Markdown
Plot your ComparisonPlot the test accuracies between the baseline model (no pretraining) and same model pretrained with self-supervised learning.
###Code
plt.plot(no_pretrain_results['test_acc@1'], label="Without Pretrain")
plt.plot(pretrain_results['test_acc@1'], label="With Pretrain")
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.title('Test Top-1 Accuracy')
plt.legend()
plt.show()
###Output
_____no_output_____
###Markdown
Using GPUGo to `Runtime > Change runtime type` and set `Hardware accelerator` to `GPU`. This will reset Colab. **Rerun the top cell to mount your Drive again.** Self-Supervised Learning What is self-supervised learning?Modern day machine learning requires lots of labeled data. But often times it's challenging and/or expensive to obtain large amounts of human-labeled data. Is there a way we could ask machines to automatically learn a model which can generate good visual representations without a labeled dataset? Yes, enter self-supervised learning! Self-supervised learning (SSL) allows models to automatically learn a "good" representation space using the data in a given dataset without the need for their labels. Specifically, if our dataset were a bunch of images, then self-supervised learning allows a model to learn and generate a "good" representation vector for images. The reason SSL methods have seen a surge in popularity is because the learnt model continues to perform well on other datasets as well i.e. new datasets on which the model was not trained on! What makes a "good" representation?A "good" representation vector needs to capture the important features of the image as it relates to the rest of the dataset. This means that images in the dataset representing semantically similar entities should have similar representation vectors, and different images in the dataset should have different representation vectors. For example, two images of an apple should have similar representation vectors, while an image of an apple and an image of a banana should have different representation vectors. Contrastive Learning: SimCLRRecently, [SimCLR](https://arxiv.org/pdf/2002.05709.pdf) introduces a new architecture which uses **contrastive learning** to learn good visual representations. Contrastive learning aims to learn similar representations for similar images and different representations for different images. As we will see in this notebook, this simple idea allows us to train a surprisingly good model without using any labels.Specifically, for each image in the dataset, SimCLR generates two differently augmented views of that image, called a **positive pair**. Then, the model is encouraged to generate similar representation vectors for this pair of images. See below for an illustration of the architecture (Figure 2 from the paper).
###Code
# Run this cell to view the SimCLR architecture.
from IPython.display import Image
Image('images/simclr_fig2.png', width=500)
###Output
_____no_output_____
###Markdown
Given an image **x**, SimCLR uses two different data augmentation schemes **t** and **t'** to generate the positive pair of images **$\hat{x}_i$** and **$\hat{x}_j$**. $f$ is a basic encoder net that extracts representation vectors from the augmented data samples, which yields **$h_i$** and **$h_j$**, respectively. Finally, a small neural network projection head $g$ maps the representation vectors to the space where the contrastive loss is applied. The goal of the contrastive loss is to maximize agreement between the final vectors **$z_i = g(h_i)$** and **$z_j = g(h_j)$**. We will discuss the contrastive loss in more detail later, and you will get to implement it.After training is completed, we throw away the projection head $g$ and only use $f$ and the representation $h$ to perform downstream tasks, such as classification. You will get a chance to finetune a layer on top of a trained SimCLR model for a classification task and compare its performance with a baseline model (without self-supervised learning). Pretrained WeightsFor your convenience, we have given you pretrained weights (trained for ~18 hours on CIFAR-10) for the SimCLR model. Run the following cell to download pretrained model weights to be used later. (This will take ~1 minute)
###Code
%%bash
DIR=pretrained_model/
if [ ! -d "$DIR" ]; then
mkdir "$DIR"
fi
URL=http://downloads.cs.stanford.edu/downloads/cs231n/pretrained_simclr_model.pth
FILE=pretrained_model/pretrained_simclr_model.pth
if [ ! -f "$FILE" ]; then
echo "Downloading weights..."
wget "$URL" -O "$FILE"
fi
# Setup cell.
%pip install thop
import torch
import os
import importlib
import pandas as pd
import numpy as np
import torch.optim as optim
import torch.nn as nn
import random
from thop import profile, clever_format
from torch.utils.data import DataLoader
from torchvision.datasets import CIFAR10
import matplotlib.pyplot as plt
%matplotlib inline
%load_ext autoreload
%autoreload 2
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
###Output
Collecting thop
Downloading thop-0.0.31.post2005241907-py3-none-any.whl (8.7 kB)
Requirement already satisfied: torch>=1.0.0 in /usr/local/lib/python3.7/dist-packages (from thop) (1.9.0+cu102)
Requirement already satisfied: typing-extensions in /usr/local/lib/python3.7/dist-packages (from torch>=1.0.0->thop) (3.7.4.3)
Installing collected packages: thop
Successfully installed thop-0.0.31.post2005241907
###Markdown
Data AugmentationOur first step is to perform data augmentation. Implement the `compute_train_transform()` function in `cs231n/simclr/data_utils.py` to apply the following random transformations:1. Randomly resize and crop to 32x32.2. Horizontally flip the image with probability 0.53. With a probability of 0.8, apply color jitter (see `compute_train_transform()` for definition)4. With a probability of 0.2, convert the image to grayscale Now complete `compute_train_transform()` and `CIFAR10Pair.__getitem__()` in `cs231n/simclr/data_utils.py` to apply the data augmentation transform and generate **$\hat{x}_i$** and **$\hat{x}_j$**. Test to make sure that your data augmentation code is correct:
###Code
from cs231n.simclr.data_utils import *
from cs231n.simclr.contrastive_loss import *
answers = torch.load('simclr_sanity_check.key')
from PIL import Image
import torchvision
from torchvision.datasets import CIFAR10
def test_data_augmentation(correct_output=None):
train_transform = compute_train_transform(seed=2147483647)
trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=train_transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=2, shuffle=False, num_workers=2)
dataiter = iter(trainloader)
images, labels = dataiter.next()
img = torchvision.utils.make_grid(images)
img = img / 2 + 0.5 # unnormalize
npimg = img.numpy()
plt.imshow(np.transpose(npimg, (1, 2, 0)))
plt.show()
output = images
print("Maximum error in data augmentation: %g"%rel_error( output.numpy(), correct_output.numpy()))
# Should be less than 1e-07.
test_data_augmentation(answers['data_augmentation'])
###Output
Files already downloaded and verified
###Markdown
Base Encoder and Projection HeadThe next steps are to apply the base encoder and projection head to the augmented samples **$\hat{x}_i$** and **$\hat{x}_j$**.The base encoder $f$ extracts representation vectors for the augmented samples. The SimCLR paper found that using deeper and wider models improved performance and thus chose [ResNet](https://arxiv.org/pdf/1512.03385.pdf) to use as the base encoder. The output of the base encoder are the representation vectors **$h_i = f(\hat{x}_i$)** and **$h_j = f(\hat{x}_j$)**.The projection head $g$ is a small neural network that maps the representation vectors **$h_i$** and **$h_j$** to the space where the contrastive loss is applied. The paper found that using a nonlinear projection head improved the representation quality of the layer before it. Specifically, they used a MLP with one hidden layer as the projection head $g$. The contrastive loss is then computed based on the outputs **$z_i = g(h_i$)** and **$z_j = g(h_j$)**.We provide implementations of these two parts in `cs231n/simclr/model.py`. Please skim through the file and make sure you understand the implementation. SimCLR: Contrastive LossA mini-batch of $N$ training images yields a total of $2N$ data-augmented examples. For each positive pair $(i, j)$ of augmented examples, the contrastive loss function aims to maximize the agreement of vectors $z_i$ and $z_j$. Specifically, the loss is the normalized temperature-scaled cross entropy loss and aims to maximize the agreement of $z_i$ and $z_j$ relative to all other augmented examples in the batch: $$l \; (i, j) = -\log \frac{\exp (\;\text{sim}(z_i, z_j)\; / \;\tau) }{\sum_{k=1}^{2N} \mathbb{1}_{k \neq i} \exp (\;\text{sim} (z_i, z_k) \;/ \;\tau) }$$ where $\mathbb{1} \in \{0, 1\}$ is an indicator function that outputs $1$ if $k\neq i$ and $0$ otherwise. $\tau$ is a temperature parameter that determines how fast the exponentials increase.sim$(z_i, z_j) = \frac{z_i \cdot z_j}{|| z_i || || z_j ||}$ is the (normalized) dot product between vectors $z_i$ and $z_j$. The higher the similarity between $z_i$ and $z_j$, the larger the dot product is, and the larger the numerator becomes. The denominator normalizes the value by summing across $z_i$ and all other augmented examples $k$ in the batch. The range of the normalized value is $(0, 1)$, where a high score close to $1$ corresponds to a high similarity between the positive pair $(i, j)$ and low similarity between $i$ and other augmented examples $k$ in the batch. The negative log then maps the range $(0, 1)$ to the loss values $(\inf, 0)$. The total loss is computed across all positive pairs $(i, j)$ in the batch. Let $z = [z_1, z_2, ..., z_{2N}]$ include all the augmented examples in the batch, where $z_{1}...z_{N}$ are outputs of the left branch, and $z_{N+1}...z_{2N}$ are outputs of the right branch. Thus, the positive pairs are $(z_{k}, z_{k + N})$ for $\forall k \in [1, N]$. Then, the total loss $L$ is: $$L = \frac{1}{2N} \sum_{k=1}^N [ \; l(k, \;k+N) + l(k+N, \;k)\;]$$ **NOTE:** this equation is slightly different from the one in the paper. We've rearranged the ordering of the positive pairs in the batch, so the indices are different. The rearrangement makes it easier to implement the code in vectorized form.We'll walk through the steps of implementing the loss function in vectorized form. Implement the functions `sim`, `simclr_loss_naive` in `cs231n/simclr/contrastive_loss.py`. Test your code by running the sanity checks below.
###Code
from cs231n.simclr.contrastive_loss import *
answers = torch.load('simclr_sanity_check.key')
def test_sim(left_vec, right_vec, correct_output):
output = sim(left_vec, right_vec).cpu().numpy()
print("Maximum error in sim: %g"%rel_error(correct_output.numpy(), output))
# Should be less than 1e-07.
test_sim(answers['left'][0], answers['right'][0], answers['sim'][0])
test_sim(answers['left'][1], answers['right'][1], answers['sim'][1])
def test_loss_naive(left, right, tau, correct_output):
naive_loss = simclr_loss_naive(left, right, tau).item()
print(correct_output)
print(naive_loss)
print("Maximum error in simclr_loss_naive: %g"%rel_error(correct_output, naive_loss))
# Should be less than 1e-07.
test_loss_naive(answers['left'], answers['right'], 5.0, answers['loss']['5.0'])
test_loss_naive(answers['left'], answers['right'], 1.0, answers['loss']['1.0'])
###Output
1.0883455276489258
1.0933912992477417
Maximum error in simclr_loss_naive: 0.00231273
1.0537996292114258
1.0824599266052246
Maximum error in simclr_loss_naive: 0.0134161
###Markdown
Now implement the vectorized version by implementing `sim_positive_pairs`, `compute_sim_matrix`, `simclr_loss_vectorized` in `cs231n/simclr/contrastive_loss.py`. Test your code by running the sanity checks below.
###Code
def test_sim_positive_pairs(left, right, correct_output):
sim_pair = sim_positive_pairs(left, right).cpu().numpy()
print("Maximum error in sim_positive_pairs: %g"%rel_error(correct_output.numpy(), sim_pair))
# Should be less than 1e-07.
test_sim_positive_pairs(answers['left'], answers['right'], answers['sim'])
def test_sim_matrix(left, right, correct_output):
out = torch.cat([left, right], dim=0)
sim_matrix = compute_sim_matrix(out).cpu()
assert torch.isclose(sim_matrix, correct_output).all(), "correct: {}. got: {}".format(correct_output, sim_matrix)
print("Test passed!")
test_sim_matrix(answers['left'], answers['right'], answers['sim_matrix'])
def test_loss_vectorized(left, right, tau, correct_output):
vec_loss = simclr_loss_vectorized(left, right, tau, device).item()
print("Maximum error in loss_vectorized: %g"%rel_error(correct_output, vec_loss))
# Should be less than 1e-07.
test_loss_vectorized(answers['left'], answers['right'], 5.0, answers['loss']['5.0'])
test_loss_vectorized(answers['left'], answers['right'], 1.0, answers['loss']['1.0'])
###Output
Maximum error in loss_vectorized: 0
Maximum error in loss_vectorized: 1.13123e-07
###Markdown
Implement the train functionComplete the `train()` function in `cs231n/simclr/utils.py` to obtain the model's output and use `simclr_loss_vectorized` to compute the loss. (Please take a look at the `Model` class in `cs231n/simclr/model.py` to understand the model pipeline and the returned values)
###Code
from cs231n.simclr.data_utils import *
from cs231n.simclr.model import *
from cs231n.simclr.utils import *
###Output
_____no_output_____
###Markdown
Train the SimCLR modelRun the following cells to load in the pretrained weights and continue to train a little bit more. This part will take ~10 minutes and will output to `pretrained_model/trained_simclr_model.pth`.**NOTE:** Don't worry about logs such as '_[WARN] Cannot find rule for ..._'. These are related to another module used in the notebook. You can verify the integrity of your code changes through our provided prompts and comments.
###Code
# Do not modify this cell.
feature_dim = 128
temperature = 0.5
k = 200
batch_size = 64
epochs = 1
temperature = 0.5
percentage = 0.5
pretrained_path = './pretrained_model/pretrained_simclr_model.pth'
# Prepare the data.
train_transform = compute_train_transform()
train_data = CIFAR10Pair(root='data', train=True, transform=train_transform, download=True)
train_data = torch.utils.data.Subset(train_data, list(np.arange(int(len(train_data)*percentage))))
train_loader = DataLoader(train_data, batch_size=batch_size, shuffle=True, num_workers=16, pin_memory=True, drop_last=True)
test_transform = compute_test_transform()
memory_data = CIFAR10Pair(root='data', train=True, transform=test_transform, download=True)
memory_loader = DataLoader(memory_data, batch_size=batch_size, shuffle=False, num_workers=16, pin_memory=True)
test_data = CIFAR10Pair(root='data', train=False, transform=test_transform, download=True)
test_loader = DataLoader(test_data, batch_size=batch_size, shuffle=False, num_workers=16, pin_memory=True)
# Set up the model and optimizer config.
model = Model(feature_dim)
model.load_state_dict(torch.load(pretrained_path, map_location='cpu'), strict=False)
model = model.to(device)
flops, params = profile(model, inputs=(torch.randn(1, 3, 32, 32).to(device),))
flops, params = clever_format([flops, params])
print('# Model Params: {} FLOPs: {}'.format(params, flops))
optimizer = optim.Adam(model.parameters(), lr=1e-3, weight_decay=1e-6)
c = len(memory_data.classes)
# Training loop.
results = {'train_loss': [], 'test_acc@1': [], 'test_acc@5': []} #<< -- output
if not os.path.exists('results'):
os.mkdir('results')
best_acc = 0.0
for epoch in range(1, epochs + 1):
train_loss = train(model, train_loader, optimizer, epoch, epochs, batch_size=batch_size, temperature=temperature, device=device)
results['train_loss'].append(train_loss)
test_acc_1, test_acc_5 = test(model, memory_loader, test_loader, epoch, epochs, c, k=k, temperature=temperature, device=device)
results['test_acc@1'].append(test_acc_1)
results['test_acc@5'].append(test_acc_5)
# Save statistics.
if test_acc_1 > best_acc:
best_acc = test_acc_1
torch.save(model.state_dict(), './pretrained_model/trained_simclr_model.pth')
###Output
Files already downloaded and verified
###Markdown
Finetune a Linear Layer for Classification!Now it's time to put the representation vectors to the test!We remove the projection head from the SimCLR model and slap on a linear layer to finetune for a simple classification task. All layers before the linear layer are frozen, and only the weights in the final linear layer are trained. We compare the performance of the SimCLR + finetuning model against a baseline model, where no self-supervised learning is done beforehand, and all weights in the model are trained. You will get to see for yourself the power of self-supervised learning and how the learned representation vectors improve downstream task performance. Baseline: Without Self-Supervised LearningFirst, let's take a look at the baseline model. We'll remove the projection head from the SimCLR model and slap on a linear layer to finetune for a simple classification task. No self-supervised learning is done beforehand, and all weights in the model are trained. Run the following cells. **NOTE:** Don't worry if you see low but reasonable performance.
###Code
class Classifier(nn.Module):
def __init__(self, num_class):
super(Classifier, self).__init__()
# Encoder.
self.f = Model().f
# Classifier.
self.fc = nn.Linear(2048, num_class, bias=True)
def forward(self, x):
x = self.f(x)
feature = torch.flatten(x, start_dim=1)
out = self.fc(feature)
return out
# Do not modify this cell.
feature_dim = 128
temperature = 0.5
k = 200
batch_size = 128
epochs = 10
percentage = 0.1
train_transform = compute_train_transform()
train_data = CIFAR10(root='data', train=True, transform=train_transform, download=True)
trainset = torch.utils.data.Subset(train_data, list(np.arange(int(len(train_data)*percentage))))
train_loader = DataLoader(trainset, batch_size=batch_size, shuffle=True, num_workers=16, pin_memory=True)
test_transform = compute_test_transform()
test_data = CIFAR10(root='data', train=False, transform=test_transform, download=True)
test_loader = DataLoader(test_data, batch_size=batch_size, shuffle=False, num_workers=16, pin_memory=True)
model = Classifier(num_class=len(train_data.classes)).to(device)
for param in model.f.parameters():
param.requires_grad = False
flops, params = profile(model, inputs=(torch.randn(1, 3, 32, 32).to(device),))
flops, params = clever_format([flops, params])
print('# Model Params: {} FLOPs: {}'.format(params, flops))
optimizer = optim.Adam(model.fc.parameters(), lr=1e-3, weight_decay=1e-6)
no_pretrain_results = {'train_loss': [], 'train_acc@1': [], 'train_acc@5': [],
'test_loss': [], 'test_acc@1': [], 'test_acc@5': []}
best_acc = 0.0
for epoch in range(1, epochs + 1):
train_loss, train_acc_1, train_acc_5 = train_val(model, train_loader, optimizer, epoch, epochs, device='cuda')
no_pretrain_results['train_loss'].append(train_loss)
no_pretrain_results['train_acc@1'].append(train_acc_1)
no_pretrain_results['train_acc@5'].append(train_acc_5)
test_loss, test_acc_1, test_acc_5 = train_val(model, test_loader, None, epoch, epochs)
no_pretrain_results['test_loss'].append(test_loss)
no_pretrain_results['test_acc@1'].append(test_acc_1)
no_pretrain_results['test_acc@5'].append(test_acc_5)
if test_acc_1 > best_acc:
best_acc = test_acc_1
# Print the best test accuracy.
print('Best top-1 accuracy without self-supervised learning: ', best_acc)
###Output
Files already downloaded and verified
###Markdown
With Self-Supervised LearningLet's see how much improvement we get with self-supervised learning. Here, we pretrain the SimCLR model using the simclr loss you wrote, remove the projection head from the SimCLR model, and use a linear layer to finetune for a simple classification task.
###Code
# Do not modify this cell.
feature_dim = 128
temperature = 0.5
k = 200
batch_size = 128
epochs = 10
percentage = 0.1
pretrained_path = './pretrained_model/trained_simclr_model.pth'
train_transform = compute_train_transform()
train_data = CIFAR10(root='data', train=True, transform=train_transform, download=True)
trainset = torch.utils.data.Subset(train_data, list(np.arange(int(len(train_data)*percentage))))
train_loader = DataLoader(trainset, batch_size=batch_size, shuffle=True, num_workers=16, pin_memory=True)
test_transform = compute_test_transform()
test_data = CIFAR10(root='data', train=False, transform=test_transform, download=True)
test_loader = DataLoader(test_data, batch_size=batch_size, shuffle=False, num_workers=16, pin_memory=True)
model = Classifier(num_class=len(train_data.classes))
model.load_state_dict(torch.load(pretrained_path, map_location='cpu'), strict=False)
model = model.to(device)
for param in model.f.parameters():
param.requires_grad = False
flops, params = profile(model, inputs=(torch.randn(1, 3, 32, 32).to(device),))
flops, params = clever_format([flops, params])
print('# Model Params: {} FLOPs: {}'.format(params, flops))
optimizer = optim.Adam(model.fc.parameters(), lr=1e-3, weight_decay=1e-6)
pretrain_results = {'train_loss': [], 'train_acc@1': [], 'train_acc@5': [],
'test_loss': [], 'test_acc@1': [], 'test_acc@5': []}
best_acc = 0.0
for epoch in range(1, epochs + 1):
train_loss, train_acc_1, train_acc_5 = train_val(model, train_loader, optimizer, epoch, epochs)
pretrain_results['train_loss'].append(train_loss)
pretrain_results['train_acc@1'].append(train_acc_1)
pretrain_results['train_acc@5'].append(train_acc_5)
test_loss, test_acc_1, test_acc_5 = train_val(model, test_loader, None, epoch, epochs)
pretrain_results['test_loss'].append(test_loss)
pretrain_results['test_acc@1'].append(test_acc_1)
pretrain_results['test_acc@5'].append(test_acc_5)
if test_acc_1 > best_acc:
best_acc = test_acc_1
# Print the best test accuracy. You should see a best top-1 accuracy of >=70%.
print('Best top-1 accuracy with self-supervised learning: ', best_acc)
###Output
Files already downloaded and verified
###Markdown
Plot your ComparisonPlot the test accuracies between the baseline model (no pretraining) and same model pretrained with self-supervised learning.
###Code
plt.plot(no_pretrain_results['test_acc@1'], label="Without Pretrain")
plt.plot(pretrain_results['test_acc@1'], label="With Pretrain")
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.title('Test Top-1 Accuracy')
plt.legend()
plt.show()
###Output
_____no_output_____
###Markdown
Using GPUGo to `Runtime > Change runtime type` and set `Hardware accelerator` to `GPU`. This will reset Colab. **Rerun the top cell to mount your Drive again.** Self-Supervised Learning What is self-supervised learning?Modern day machine learning requires lots of labeled data. But often times it's challenging and/or expensive to obtain large amounts of human-labeled data. Is there a way we could ask machines to automatically learn a model which can generate good visual representations without a labeled dataset? Yes, enter self-supervised learning! Self-supervised learning (SSL) allows models to automatically learn a "good" representation space using the data in a given dataset without the need for their labels. Specifically, if our dataset were a bunch of images, then self-supervised learning allows a model to learn and generate a "good" representation vector for images. The reason SSL methods have seen a surge in popularity is because the learnt model continues to perform well on other datasets as well i.e. new datasets on which the model was not trained on! What makes a "good" representation?A "good" representation vector needs to capture the important features of the image as it relates to the rest of the dataset. This means that images in the dataset representing semantically similar entities should have similar representation vectors, and different images in the dataset should have different representation vectors. For example, two images of an apple should have similar representation vectors, while an image of an apple and an image of a banana should have different representation vectors. Contrastive Learning: SimCLRRecently, [SimCLR](https://arxiv.org/pdf/2002.05709.pdf) introduces a new architecture which uses **contrastive learning** to learn good visual representations. Contrastive learning aims to learn similar representations for similar images and different representations for different images. As we will see in this notebook, this simple idea allows us to train a surprisingly good model without using any labels.Specifically, for each image in the dataset, SimCLR generates two differently augmented views of that image, called a **positive pair**. Then, the model is encouraged to generate similar representation vectors for this pair of images. See below for an illustration of the architecture (Figure 2 from the paper).
###Code
# Run this cell to view the SimCLR architecture.
from IPython.display import Image
Image('images/simclr_fig2.png', width=500)
###Output
_____no_output_____
###Markdown
Given an image **x**, SimCLR uses two different data augmentation schemes **t** and **t'** to generate the positive pair of images **$\hat{x}_i$** and **$\hat{x}_j$**. $f$ is a basic encoder net that extracts representation vectors from the augmented data samples, which yields **$h_i$** and **$h_j$**, respectively. Finally, a small neural network projection head $g$ maps the representation vectors to the space where the contrastive loss is applied. The goal of the contrastive loss is to maximize agreement between the final vectors **$z_i = g(h_i)$** and **$z_j = g(h_j)$**. We will discuss the contrastive loss in more detail later, and you will get to implement it.After training is completed, we throw away the projection head $g$ and only use $f$ and the representation $h$ to perform downstream tasks, such as classification. You will get a chance to finetune a layer on top of a trained SimCLR model for a classification task and compare its performance with a baseline model (without self-supervised learning). Pretrained WeightsFor your convenience, we have given you pretrained weights (trained for ~18 hours on CIFAR-10) for the SimCLR model. Run the following cell to download pretrained model weights to be used later. (This will take ~1 minute)
###Code
%%bash
DIR=pretrained_model/
if [ ! -d "$DIR" ]; then
mkdir "$DIR"
fi
URL=http://downloads.cs.stanford.edu/downloads/cs231n/pretrained_simclr_model.pth
FILE=pretrained_model/pretrained_simclr_model.pth
if [ ! -f "$FILE" ]; then
echo "Downloading weights..."
wget "$URL" -O "$FILE"
fi
# Setup cell.
%pip install thop
import torch
import os
import importlib
import pandas as pd
import numpy as np
import torch.optim as optim
import torch.nn as nn
import random
from thop import profile, clever_format
from torch.utils.data import DataLoader
from torchvision.datasets import CIFAR10
import matplotlib.pyplot as plt
%matplotlib inline
%load_ext autoreload
%autoreload 2
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
###Output
Collecting thop
Downloading https://files.pythonhosted.org/packages/6c/8b/22ce44e1c71558161a8bd54471123cc796589c7ebbfc15a7e8932e522f83/thop-0.0.31.post2005241907-py3-none-any.whl
Requirement already satisfied: torch>=1.0.0 in /usr/local/lib/python3.7/dist-packages (from thop) (1.9.0+cu102)
Requirement already satisfied: typing-extensions in /usr/local/lib/python3.7/dist-packages (from torch>=1.0.0->thop) (3.7.4.3)
Installing collected packages: thop
Successfully installed thop-0.0.31.post2005241907
###Markdown
Data AugmentationOur first step is to perform data augmentation. Implement the `compute_train_transform()` function in `cs231n/simclr/data_utils.py` to apply the following random transformations:1. Randomly resize and crop to 32x32.2. Horizontally flip the image with probability 0.53. With a probability of 0.8, apply color jitter (see `compute_train_transform()` for definition)4. With a probability of 0.2, convert the image to grayscale Now complete `compute_train_transform()` and `CIFAR10Pair.__getitem__()` in `cs231n/simclr/data_utils.py` to apply the data augmentation transform and generate **$\hat{x}_i$** and **$\hat{x}_j$**. Test to make sure that your data augmentation code is correct:
###Code
from cs231n.simclr.data_utils import *
from cs231n.simclr.contrastive_loss import *
answers = torch.load('simclr_sanity_check.key')
from PIL import Image
import torchvision
from torchvision.datasets import CIFAR10
def test_data_augmentation(correct_output=None):
train_transform = compute_train_transform(seed=2147483647)
trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=train_transform)
trainloader = torch.utils.data.DataLoader(trainset, batch_size=2, shuffle=False, num_workers=2)
dataiter = iter(trainloader)
images, labels = dataiter.next()
img = torchvision.utils.make_grid(images)
img = img / 2 + 0.5 # unnormalize
npimg = img.numpy()
plt.imshow(np.transpose(npimg, (1, 2, 0)))
plt.show()
output = images
print("Maximum error in data augmentation: %g"%rel_error( output.numpy(), correct_output.numpy()))
# Should be less than 1e-07.
test_data_augmentation(answers['data_augmentation'])
###Output
Downloading https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz to ./data/cifar-10-python.tar.gz
###Markdown
Base Encoder and Projection HeadThe next steps are to apply the base encoder and projection head to the augmented samples **$\hat{x}_i$** and **$\hat{x}_j$**.The base encoder $f$ extracts representation vectors for the augmented samples. The SimCLR paper found that using deeper and wider models improved performance and thus chose [ResNet](https://arxiv.org/pdf/1512.03385.pdf) to use as the base encoder. The output of the base encoder are the representation vectors **$h_i = f(\hat{x}_i$)** and **$h_j = f(\hat{x}_j$)**.The projection head $g$ is a small neural network that maps the representation vectors **$h_i$** and **$h_j$** to the space where the contrastive loss is applied. The paper found that using a nonlinear projection head improved the representation quality of the layer before it. Specifically, they used a MLP with one hidden layer as the projection head $g$. The contrastive loss is then computed based on the outputs **$z_i = g(h_i$)** and **$z_j = g(h_j$)**.We provide implementations of these two parts in `cs231n/simclr/model.py`. Please skim through the file and make sure you understand the implementation. SimCLR: Contrastive LossA mini-batch of $N$ training images yields a total of $2N$ data-augmented examples. For each positive pair $(i, j)$ of augmented examples, the contrastive loss function aims to maximize the agreement of vectors $z_i$ and $z_j$. Specifically, the loss is the normalized temperature-scaled cross entropy loss and aims to maximize the agreement of $z_i$ and $z_j$ relative to all other augmented examples in the batch: $$l \; (i, j) = -\log \frac{\exp (\;\text{sim}(z_i, z_j)\; / \;\tau) }{\sum_{k=1}^{2N} \mathbb{1}_{k \neq i} \exp (\;\text{sim} (z_i, z_k) \;/ \;\tau) }$$ where $\mathbb{1} \in \{0, 1\}$ is an indicator function that outputs $1$ if $k\neq i$ and $0$ otherwise. $\tau$ is a temperature parameter that determines how fast the exponentials increase.sim$(z_i, z_j) = \frac{z_i \cdot z_j}{|| z_i || || z_j ||}$ is the (normalized) dot product between vectors $z_i$ and $z_j$. The higher the similarity between $z_i$ and $z_j$, the larger the dot product is, and the larger the numerator becomes. The denominator normalizes the value by summing across $z_i$ and all other augmented examples $k$ in the batch. The range of the normalized value is $(0, 1)$, where a high score close to $1$ corresponds to a high similarity between the positive pair $(i, j)$ and low similarity between $i$ and other augmented examples $k$ in the batch. The negative log then maps the range $(0, 1)$ to the loss values $(\inf, 0)$. The total loss is computed across all positive pairs $(i, j)$ in the batch. Let $z = [z_1, z_2, ..., z_{2N}]$ include all the augmented examples in the batch, where $z_{1}...z_{N}$ are outputs of the left branch, and $z_{N+1}...z_{2N}$ are outputs of the right branch. Thus, the positive pairs are $(z_{k}, z_{k + N})$ for $\forall k \in [1, N]$. Then, the total loss $L$ is: $$L = \frac{1}{2N} \sum_{k=1}^N [ \; l(k, \;k+N) + l(k+N, \;k)\;]$$ **NOTE:** this equation is slightly different from the one in the paper. We've rearranged the ordering of the positive pairs in the batch, so the indices are different. The rearrangement makes it easier to implement the code in vectorized form.We'll walk through the steps of implementing the loss function in vectorized form. Implement the functions `sim`, `simclr_loss_naive` in `cs231n/simclr/contrastive_loss.py`. Test your code by running the sanity checks below.
###Code
from cs231n.simclr.contrastive_loss import *
answers = torch.load('simclr_sanity_check.key')
def test_sim(left_vec, right_vec, correct_output):
output = sim(left_vec, right_vec).cpu().numpy()
print("Maximum error in sim: %g"%rel_error(correct_output.numpy(), output))
# Should be less than 1e-07.
test_sim(answers['left'][0], answers['right'][0], answers['sim'][0])
test_sim(answers['left'][1], answers['right'][1], answers['sim'][1])
def test_loss_naive(left, right, tau, correct_output):
naive_loss = simclr_loss_naive(left, right, tau).item()
print("Maximum error in simclr_loss_naive: %g"%rel_error(correct_output, naive_loss))
# Should be less than 1e-07.
test_loss_naive(answers['left'], answers['right'], 5.0, answers['loss']['5.0'])
test_loss_naive(answers['left'], answers['right'], 1.0, answers['loss']['1.0'])
###Output
Maximum error in simclr_loss_naive: 0
Maximum error in simclr_loss_naive: 5.65617e-08
###Markdown
Now implement the vectorized version by implementing `sim_positive_pairs`, `compute_sim_matrix`, `simclr_loss_vectorized` in `cs231n/simclr/contrastive_loss.py`. Test your code by running the sanity checks below.
###Code
def test_sim_positive_pairs(left, right, correct_output):
sim_pair = sim_positive_pairs(left, right).cpu().numpy()
print("Maximum error in sim_positive_pairs: %g"%rel_error(correct_output.numpy(), sim_pair))
# Should be less than 1e-07.
test_sim_positive_pairs(answers['left'], answers['right'], answers['sim'])
def test_sim_matrix(left, right, correct_output):
out = torch.cat([left, right], dim=0)
sim_matrix = compute_sim_matrix(out).cpu()
assert torch.isclose(sim_matrix, correct_output).all(), "correct: {}. got: {}".format(correct_output, sim_matrix)
print("Test passed!")
test_sim_matrix(answers['left'], answers['right'], answers['sim_matrix'])
def test_loss_vectorized(left, right, tau, correct_output):
vec_loss = simclr_loss_vectorized(left, right, tau, device).item()
print("Maximum error in loss_vectorized: %g"%rel_error(correct_output, vec_loss))
# Should be less than 1e-07.
test_loss_vectorized(answers['left'].to(device), answers['right'].to(device), 5.0, answers['loss']['5.0'])
test_loss_vectorized(answers['left'].to(device), answers['right'].to(device), 1.0, answers['loss']['1.0'])
###Output
Maximum error in loss_vectorized: 0
Maximum error in loss_vectorized: 1.13123e-07
###Markdown
Implement the train functionComplete the `train()` function in `cs231n/simclr/utils.py` to obtain the model's output and use `simclr_loss_vectorized` to compute the loss. (Please take a look at the `Model` class in `cs231n/simclr/model.py` to understand the model pipeline and the returned values)
###Code
from cs231n.simclr.data_utils import *
from cs231n.simclr.model import *
from cs231n.simclr.utils import *
###Output
_____no_output_____
###Markdown
Train the SimCLR modelRun the following cells to load in the pretrained weights and continue to train a little bit more. This part will take ~10 minutes and will output to `pretrained_model/trained_simclr_model.pth`.**NOTE:** Don't worry about logs such as '_[WARN] Cannot find rule for ..._'. These are related to another module used in the notebook. You can verify the integrity of your code changes through our provided prompts and comments.
###Code
# Do not modify this cell.
feature_dim = 128
temperature = 0.5
k = 200
batch_size = 64
epochs = 1
temperature = 0.5
percentage = 0.5
pretrained_path = './pretrained_model/pretrained_simclr_model.pth'
# Prepare the data.
train_transform = compute_train_transform()
train_data = CIFAR10Pair(root='data', train=True, transform=train_transform, download=True)
train_data = torch.utils.data.Subset(train_data, list(np.arange(int(len(train_data)*percentage))))
train_loader = DataLoader(train_data, batch_size=batch_size, shuffle=True, num_workers=16, pin_memory=True, drop_last=True)
test_transform = compute_test_transform()
memory_data = CIFAR10Pair(root='data', train=True, transform=test_transform, download=True)
memory_loader = DataLoader(memory_data, batch_size=batch_size, shuffle=False, num_workers=16, pin_memory=True)
test_data = CIFAR10Pair(root='data', train=False, transform=test_transform, download=True)
test_loader = DataLoader(test_data, batch_size=batch_size, shuffle=False, num_workers=16, pin_memory=True)
# Set up the model and optimizer config.
model = Model(feature_dim)
model.load_state_dict(torch.load(pretrained_path, map_location='cpu'), strict=False)
model = model.to(device)
flops, params = profile(model, inputs=(torch.randn(1, 3, 32, 32).to(device),))
flops, params = clever_format([flops, params])
print('# Model Params: {} FLOPs: {}'.format(params, flops))
optimizer = optim.Adam(model.parameters(), lr=1e-3, weight_decay=1e-6)
c = len(memory_data.classes)
# Training loop.
results = {'train_loss': [], 'test_acc@1': [], 'test_acc@5': []} #<< -- output
if not os.path.exists('results'):
os.mkdir('results')
best_acc = 0.0
for epoch in range(1, epochs + 1):
train_loss = train(model, train_loader, optimizer, epoch, epochs, batch_size=batch_size, temperature=temperature, device=device)
results['train_loss'].append(train_loss)
test_acc_1, test_acc_5 = test(model, memory_loader, test_loader, epoch, epochs, c, k=k, temperature=temperature, device=device)
results['test_acc@1'].append(test_acc_1)
results['test_acc@5'].append(test_acc_5)
# Save statistics.
if test_acc_1 > best_acc:
best_acc = test_acc_1
torch.save(model.state_dict(), './pretrained_model/trained_simclr_model.pth')
###Output
Files already downloaded and verified
###Markdown
Finetune a Linear Layer for Classification!Now it's time to put the representation vectors to the test!We remove the projection head from the SimCLR model and slap on a linear layer to finetune for a simple classification task. All layers before the linear layer are frozen, and only the weights in the final linear layer are trained. We compare the performance of the SimCLR + finetuning model against a baseline model, where no self-supervised learning is done beforehand, and all weights in the model are trained. You will get to see for yourself the power of self-supervised learning and how the learned representation vectors improve downstream task performance. Baseline: Without Self-Supervised LearningFirst, let's take a look at the baseline model. We'll remove the projection head from the SimCLR model and slap on a linear layer to finetune for a simple classification task. No self-supervised learning is done beforehand, and all weights in the model are trained. Run the following cells. **NOTE:** Don't worry if you see low but reasonable performance.
###Code
class Classifier(nn.Module):
def __init__(self, num_class):
super(Classifier, self).__init__()
# Encoder.
self.f = Model().f
# Classifier.
self.fc = nn.Linear(2048, num_class, bias=True)
def forward(self, x):
x = self.f(x)
feature = torch.flatten(x, start_dim=1)
out = self.fc(feature)
return out
# Do not modify this cell.
feature_dim = 128
temperature = 0.5
k = 200
batch_size = 128
epochs = 10
percentage = 0.1
train_transform = compute_train_transform()
train_data = CIFAR10(root='data', train=True, transform=train_transform, download=True)
trainset = torch.utils.data.Subset(train_data, list(np.arange(int(len(train_data)*percentage))))
train_loader = DataLoader(trainset, batch_size=batch_size, shuffle=True, num_workers=16, pin_memory=True)
test_transform = compute_test_transform()
test_data = CIFAR10(root='data', train=False, transform=test_transform, download=True)
test_loader = DataLoader(test_data, batch_size=batch_size, shuffle=False, num_workers=16, pin_memory=True)
model = Classifier(num_class=len(train_data.classes)).to(device)
for param in model.f.parameters():
param.requires_grad = False
flops, params = profile(model, inputs=(torch.randn(1, 3, 32, 32).to(device),))
flops, params = clever_format([flops, params])
print('# Model Params: {} FLOPs: {}'.format(params, flops))
optimizer = optim.Adam(model.fc.parameters(), lr=1e-3, weight_decay=1e-6)
no_pretrain_results = {'train_loss': [], 'train_acc@1': [], 'train_acc@5': [],
'test_loss': [], 'test_acc@1': [], 'test_acc@5': []}
best_acc = 0.0
for epoch in range(1, epochs + 1):
train_loss, train_acc_1, train_acc_5 = train_val(model, train_loader, optimizer, epoch, epochs, device='cuda')
no_pretrain_results['train_loss'].append(train_loss)
no_pretrain_results['train_acc@1'].append(train_acc_1)
no_pretrain_results['train_acc@5'].append(train_acc_5)
test_loss, test_acc_1, test_acc_5 = train_val(model, test_loader, None, epoch, epochs)
no_pretrain_results['test_loss'].append(test_loss)
no_pretrain_results['test_acc@1'].append(test_acc_1)
no_pretrain_results['test_acc@5'].append(test_acc_5)
if test_acc_1 > best_acc:
best_acc = test_acc_1
# Print the best test accuracy.
print('Best top-1 accuracy without self-supervised learning: ', best_acc)
###Output
Files already downloaded and verified
###Markdown
With Self-Supervised LearningLet's see how much improvement we get with self-supervised learning. Here, we pretrain the SimCLR model using the simclr loss you wrote, remove the projection head from the SimCLR model, and use a linear layer to finetune for a simple classification task.
###Code
# Do not modify this cell.
feature_dim = 128
temperature = 0.5
k = 200
batch_size = 128
epochs = 10
percentage = 0.1
pretrained_path = './pretrained_model/trained_simclr_model.pth'
train_transform = compute_train_transform()
train_data = CIFAR10(root='data', train=True, transform=train_transform, download=True)
trainset = torch.utils.data.Subset(train_data, list(np.arange(int(len(train_data)*percentage))))
train_loader = DataLoader(trainset, batch_size=batch_size, shuffle=True, num_workers=16, pin_memory=True)
test_transform = compute_test_transform()
test_data = CIFAR10(root='data', train=False, transform=test_transform, download=True)
test_loader = DataLoader(test_data, batch_size=batch_size, shuffle=False, num_workers=16, pin_memory=True)
model = Classifier(num_class=len(train_data.classes))
model.load_state_dict(torch.load(pretrained_path, map_location='cpu'), strict=False)
model = model.to(device)
for param in model.f.parameters():
param.requires_grad = False
flops, params = profile(model, inputs=(torch.randn(1, 3, 32, 32).to(device),))
flops, params = clever_format([flops, params])
print('# Model Params: {} FLOPs: {}'.format(params, flops))
optimizer = optim.Adam(model.fc.parameters(), lr=1e-3, weight_decay=1e-6)
pretrain_results = {'train_loss': [], 'train_acc@1': [], 'train_acc@5': [],
'test_loss': [], 'test_acc@1': [], 'test_acc@5': []}
best_acc = 0.0
for epoch in range(1, epochs + 1):
train_loss, train_acc_1, train_acc_5 = train_val(model, train_loader, optimizer, epoch, epochs)
pretrain_results['train_loss'].append(train_loss)
pretrain_results['train_acc@1'].append(train_acc_1)
pretrain_results['train_acc@5'].append(train_acc_5)
test_loss, test_acc_1, test_acc_5 = train_val(model, test_loader, None, epoch, epochs)
pretrain_results['test_loss'].append(test_loss)
pretrain_results['test_acc@1'].append(test_acc_1)
pretrain_results['test_acc@5'].append(test_acc_5)
if test_acc_1 > best_acc:
best_acc = test_acc_1
# Print the best test accuracy. You should see a best top-1 accuracy of >=70%.
print('Best top-1 accuracy with self-supervised learning: ', best_acc)
###Output
Files already downloaded and verified
###Markdown
Plot your ComparisonPlot the test accuracies between the baseline model (no pretraining) and same model pretrained with self-supervised learning.
###Code
plt.plot(no_pretrain_results['test_acc@1'], label="Without Pretrain")
plt.plot(pretrain_results['test_acc@1'], label="With Pretrain")
plt.xlabel('Epochs')
plt.ylabel('Accuracy')
plt.title('Test Top-1 Accuracy')
plt.legend()
plt.show()
###Output
_____no_output_____ |
SampledGauss_SGLD_LR.ipynb | ###Markdown
Experiments approximating the posterior with diagonal Gaussians from SGLD samplesWe start by building the model and showing the basic inference procedure and calculation of the performance on the MNIST classification and the outlier detection task. Then perform multiple runs of the model with different number of samples in the ensemble to calculate performance statistics.
###Code
# Let's first setup the libraries, session and experimental data
import experiment
import inferences
import edward as ed
import tensorflow as tf
import numpy as np
import os
s = experiment.setup()
mnist, notmnist = experiment.get_data()
# Builds the model and approximation variables used for the model
y_, model_variables = experiment.get_model_3layer()
approx_variables = experiment.get_gauss_approximation_variables_3layer()
# Performs inference with our custom inference class
inference_dict = {model_variables[key]: val for key, val in approx_variables.iteritems()}
inference = inferences.VariationalGaussSGLD(inference_dict, data={y_: model_variables['y']})
n_iter=1000
inference.initialize(n_iter=n_iter, step_size=0.005, burn_in=0)
tf.global_variables_initializer().run()
for i in range(n_iter):
batch = mnist.train.next_batch(100)
info_dict = inference.update({model_variables['x']: batch[0],
model_variables['y']: batch[1]})
inference.print_progress(info_dict)
inference.finalize()
# Computes the accuracy of our model
accuracy, disagreement = experiment.get_metrics(model_variables, approx_variables, num_samples=10)
print(accuracy.eval({model_variables['x']: mnist.test.images, model_variables['y']: mnist.test.labels}))
print(disagreement.eval({model_variables['x']: mnist.test.images, model_variables['y']: mnist.test.labels}))
# Computes some statistics for the proposed outlier detection
outlier_stats = experiment.get_outlier_stats(model_variables, disagreement, mnist, notmnist)
print(outlier_stats)
print('TP/(FN+TP): {}'.format(float(outlier_stats['TP']) / (outlier_stats['TP'] + outlier_stats['FN'])))
print('FP/(FP+TN): {}'.format(float(outlier_stats['FP']) / (outlier_stats['FP'] + outlier_stats['TN'])))
###Output
{'FP': 6, 'TN': 9994, 'FN': 3959, 'TP': 6041}
TP/(FN+TP): 0.6041
FP/(FP+TN): 0.0006
###Markdown
The following cell performs multiple runs of this model with different number of samples within the ensemble to capture performance statistics. Results are saved in `SampledGauss_SGLD_LR.csv`.
###Code
import pandas as pd
results = pd.DataFrame(columns=('run', 'samples', 'acc', 'TP', 'FN', 'TN', 'FP'))
for run in range(5):
inference_dict = {model_variables[key]: val for key, val in approx_variables.iteritems()}
inference = inferences.VariationalGaussSGLD(inference_dict, data={y_: model_variables['y']})
n_iter=1000
inference.initialize(n_iter=n_iter, step_size=0.005, burn_in=0)
tf.global_variables_initializer().run()
for i in range(n_iter):
batch = mnist.train.next_batch(100)
info_dict = inference.update({model_variables['x']: batch[0],
model_variables['y']: batch[1]})
inference.print_progress(info_dict)
inference.finalize()
for num_samples in range(15):
accuracy, disagreement = experiment.get_metrics(model_variables, approx_variables,
num_samples=num_samples + 1)
acc = accuracy.eval({model_variables['x']: mnist.test.images, model_variables['y']: mnist.test.labels})
outlier_stats = experiment.get_outlier_stats(model_variables, disagreement, mnist, notmnist)
results.loc[len(results)] = [run, num_samples + 1, acc,
outlier_stats['TP'], outlier_stats['FN'],
outlier_stats['TN'], outlier_stats['FP']]
results.to_csv('SampledGauss_SGLD_LR.csv', index=False)
###Output
1000/1000 [100%] ██████████████████████████████ Elapsed: 8s | Acceptance Rate: 1.000
1000/1000 [100%] ██████████████████████████████ Elapsed: 8s | Acceptance Rate: 1.000
1000/1000 [100%] ██████████████████████████████ Elapsed: 9s | Acceptance Rate: 1.000
1000/1000 [100%] ██████████████████████████████ Elapsed: 11s | Acceptance Rate: 1.000
1000/1000 [100%] ██████████████████████████████ Elapsed: 11s | Acceptance Rate: 1.000
|
5.Shor's Algorithm for factoring.ipynb | ###Markdown
Shor's Algorithm for factoring In this tutorial, we will walk through Shor’s Algorithm using the quantum circuit model. As we know already, the security of RSA is based on the use of a one-way function – prime factorization – which is related to the problem of period finding in modular exponentiation. As we saw, if one picks two prime numbers, $p$ and $q$, which multiply together to give a modulus $N$, then one can efficiently find the modular exponentiation period $r$, and thus generate a public encryption key e and a private decryption key $d$. However, if we are just given the modulus $N$, then we are stuck, because there’s no known efficient classical algorithm that lets us find the prime factors $p$ and $q$, and so there’s no efficient means to determine the period $r$. Thus, even if we reveal the modulus $N$ and the public encryption key $e$, there is no known efficient way for an eavesdropper to calculate the private key $d$ on a classical computer. However, **if Eve has access to a quantum computer** that can run Shor’s Algorithm, then she can efficiently find the modular exponentiation period r. $$e\cdot d = 1 \mod r ~~~~~\rightarrow~~~~~ d = e^{−1} \mod r$$ This is called order finding, and Shor’s Algorithm finds the order $r$ of a number $a$ with respect to the modulus $N$, $$a^x \mod N ~~~~~\rightarrow~~~~~ \text{order (period) } r,$$ where $a$ is the number that is raised to integer powers under modular exponentiation. With a means to efficiently determine $r$, Eve can calculate the prime numbers $p$ and $q$ and then derive the decryption key $d$, thus compromising RSA.Let’s walk through Shor's algorithm, step by step, with the initialization stage. We need two registers of qubits for Shor’s Algorithm. Register 1 is used to store the results of a period finding protocol, which is implemented using the Quantum Fourier Transform. Register 2 is used to store the values of the modular exponentiation. This is the function that will apply in the compute section. The number of qubits in the first register should generate a state space that is at least large enough to capture the maximum possible period, and do so at least twice to see it repeat. Let’s define N as twice the maximum period. So we need $$2 L > 2r_{max} = N ~~~~~\rightarrow~~~~~ N^2 < 2^{2L} < 2N^2 ~~~~~\rightarrow~~~~~ 2L \text{ qubits}.$$ The more qubits we have, the more densely we can sample the solution space, and thereby reduce the error in determining the period. Here, we’ll take 2L qubits for the first register. And for simplicity, we’ll use the same number of qubits in the second register. By choosing 2L qubits, the number of states – $2^{2L} > N^2$. This guarantees that there are at least $N$ terms contributing to the probability amplitude when estimating the period, even as the period $r$ gets exponentially large, approaching $N/2$. We prepare the qubits in state $|0\rangle^{\otimes 2L}$.Next, at the compute stage, we use Hadamard gates to place the register 1 qubits into an equal superposition state. We again use the superscripted tensor product notation to indicate that we apply a Hadamard gate to each of the $2L$ qubits. This puts each qubit into a superposition state, $\frac{1}{\sqrt{2}}(| 0 \rangle + | 1\rangle)$. Multiplying out all $2L$ of these single qubit superposition states results in a single large equal superposition state with $2^{2L}$ components. From a component with $2L$ qubits in state $| 0 \rangle$ to a component with all qubits in state $| 1 \rangle$, and with all combinations in between. If we now number these components from $0$ to $2^{2L−1}$, we can rewrite the superposition state as a sum over $x$ $$|0\rangle^{\otimes 2L}|0\rangle^{\otimes 2L} \nonumber \xrightarrow {\substack{H^{\otimes 2L}}}\frac{1}{\sqrt{2^{2L}}} \Big(|0\rangle + |1\rangle\Big)^{\otimes 2L} |0\rangle^{\otimes 2L} = \frac{1}{\sqrt{2^{2L}}}\Big(|00\cdots 0\rangle + \cdots + |11\cdots 1\rangle\Big)|0\rangle^{\otimes 2L} = \frac{1}{\sqrt{2^{2L}}}\sum_{x=0}^{2^{2L}-1}|x\rangle|0\rangle^{\otimes 2L}.$$In fact, each decimal number $x$ corresponds to one of the binary numbers represented by the $2L$ qubits. Next, the function $f(x) = a^x \mod N$ is performed: $$\frac{1}{\sqrt{2^{2L}}}\sum_{x=0}^{2^{2L}-1}|x\rangle|0\rangle^{\otimes 2L} \xrightarrow {\substack{U_{f(x)}}} \frac{1}{\sqrt{2^{2L}}}\sum_{x=0}^{2^{2L}-1}|x\rangle|f(x)\rangle = \frac{1}{\sqrt{2^{2L}}}\sum_{x=0}^{2^{2L}-1}|x\rangle|a^x \mod N\rangle.$$ $f(x)$ implements modular exponentiation, which outputs a number $a^x \mod N$. We will present in detail how the modular exponentiation is implemented in a real circuit below. In fact, there are multiple approaches to doing it based on reversible computing and multiplication algorithms. The approach we adopt is based on [this article](https://arxiv.org/pdf/quant-ph/0205095.pdf). We note that this function is implemented using ancilla qubits and it’s efficient, requiring a number of gates that scales only polynomially with the number of qubits. The number $a$ is chosen at random, and it must be co-prime with $N$. That is, it must have no common factors with $N$. The resulting output values from the function $f$ are then stored in the Register 2 qubits. Since the values of the power $x$ are taken from the qubits in the first register, implementing $f(x)$ makes a conditional connection between the qubits in Register 1 and those in Register 2. Although we ultimately won’t need to measure the qubits in Register 2, this step sets the stage for quantum interference and quantum parallelism to occur in Register 1 at the next step, which is the Quantum Fourier Transform. Here is how the circuit looks like. Below we will implement each building block of the circuit. Implementation of the Modular ExponentiationWe will adopt the approach presented in [this article](https://arxiv.org/pdf/quant-ph/0205095.pdf) which uses Kitaev's version of order finding in Shor's algorithm, **Phase Estimation Algorithm** as a subroutine.The state $|u\rangle$ must be the eigenstate or a superposition of eigenstate of the unitary $U$ for the algorithm to work properly. As stated, our unitary does the following transformation on the bottom register (multiplies by $a$ to the content of the register, mod N):$$U|y\rangle = |ay \mod N\rangle.$$It can be shown that the eigenvalue has the following form (you can see it by checking $U|u\rangle = \lambda |u\rangle$)$$|u_s\rangle = \frac{1}{\sqrt{r}} \sum_{k=0}^{r-1}\exp{\Big[ \frac{-2\pi i sk}{r}\Big]}|x^k \mod N\rangle, ~~~ s=0,1,\cdots r-1.$$Preparing this state is not an easy task experimentally. We note that $$ \frac{1}{\sqrt{r}} \sum_{k=0}^{r-1}|u_s\rangle = |1\rangle,$$ which ($|1\rangle$) is a superposition of eigenstates and pretty easy to construct. Here is the required circuit. To implement the unitary $U$ that carries out transformation $|x\rangle|0\rangle \rightarrow |x\rangle|ax \text{ mod } N\rangle$, which uses the `controlled_mult_mod_N`, the article implements the following cicuitthat uses another circuit, an adder in Fourier space (the function to be implemented below `add_in_fourier_space` as well as `controlled_controlled_add_in_fourier_space`)The addition in Fourier domain looks like the followingAnd if needed we can transform back by conjugating with quantum fourier transform (defined below) Implement the above circuits from bottom to top
###Code
from qiskit import QuantumCircuit, ClassicalRegister, QuantumRegister
from qiskit import execute, IBMQ
from qiskit import BasicAer
import sys
import math
import random
import array
import fractions
import numpy as np
###Output
_____no_output_____
###Markdown
Criate Circuit for Addition in Fourier domain
###Code
# first define a helper function to use below
def get_angles(a, N):
"""Function that calculates the array of angles
to be used in the addition in Fourier Space"""
s = bin(int(a))[2:].zfill(N)
angles = np.zeros([N])
for i in range(0, N):
for j in range(i, N):
if s[j] == '1':
angles[N-i-1] += math.pow(2, -(j-i))
angles[N-i-1] *= np.pi
return angles
print(get_angles(12,60))
def add_in_fourier_space(circuit, q, a, N, inv = False):
"""Creates the circuit that performs addition a in Fourier Space
Can also be used for subtraction by setting
the parameter inv to True"""
angle = get_angles(a, N)
for i in range(0, N):
if inv == False:
circuit.u1(angle[i], q[i])
else:
circuit.u1(-angle[i], q[i])
###Output
_____no_output_____
###Markdown
Create Circuit for Controlled Controlled Addition in Fourier space In order to implement the `Controlled Controlled Addition mod N`, we see that we need QFT, inverse QFT, `Controlled Addition` as well as `Controlled Controlled Addition`. Let's first implement the `Controlled Addition` and `Controlled Controlled Addition` gates and then cover the QFT theory and implementation of `Controlled Controlled Addition mod N`.
###Code
def controlled_add_in_fourier_space(circuit, q, ctrl, a, n, inv=False):
"""Single controlled version of the add_in_fourier_space() circuit"""
angle = get_angles(a, n)
for i in range(n):
if inv == False:
circuit.cu1(angle[i], ctrl, q[i])
else:
circuit.cu1(-angle[i], ctrl, q[i])
def ccphase(circuit, angle, ctrl1, ctrl2, tgt):
"""Creates a doubly controlled phase gate,
a helper function for doubly controlled addition"""
circuit.cu1(angle/2, ctrl1, tgt)
circuit.cx(ctrl2, ctrl1)
circuit.cu1(-angle/2, ctrl1, tgt)
circuit.cx(ctrl2, ctrl1)
circuit.cu1(angle/2, ctrl2, tgt)
def controlled_controlled_add_in_fourier_space(circuit, q, ctrl1, ctrl2, a, n, inv=False):
"""Doubly controlled version of the add_in_fourier_space() circuit"""
angle = get_angles(a, n)
for i in range(n):
if inv == False:
ccphase(circuit, angle[i], ctrl1, ctrl2, q[i])
else:
ccphase(circuit, -angle[i], ctrl1, ctrl2, q[i])
###Output
_____no_output_____
###Markdown
Now let's get intuition on QFT and implement it. Then we will combine it with the above gate to implement the `Controlled Controlled Addition` circuit. Quantum Fourier TransformThe Quantum Fourier Transform is a quantum version of the classical [discrete time Fourier Transform](https://en.wikipedia.org/wiki/Discrete-time_Fourier_transform). The classical Fourier Transform takes a vector of numbers, $x$ -- often a [digital sampling of a signal](https://en.wikipedia.org/wiki/Sampling_(signal_processing)) to be analyzed -- and transforms it to a vector of numbers, $y$, in the frequency domain.\begin{equation}y_k \equiv \frac{1}{\sqrt{N}}\sum_{j=0}^{N-1}x_je^{i2\pi jk/N}\end{equation}Periodic behavior in the time domain is more easily identified in the transformed [frequency domain](https://en.wikipedia.org/wiki/Frequency_domain), which is why we do this. For example, a sine wave that oscillates in time with a specific frequency will transform to a large amplitude spike at plus or minus that frequency in the transform domain. Thus, it's easy to identify the location of the spikes and then read off the frequency directly. And if we know a signal's frequency, then we also know its period, since the frequency is $1/\text{period}$.\\Now, the Quantum Fourier Transform is essentially the same transformation, which is why we'll use it here for period finding. It takes a state $|j\rangle$ and transforms it to a superposition state with specific phase factors.\begin{equation}|j\rangle \rightarrow \frac{1}{\sqrt{N}}\sum_{k=0}^{N-1}e^{i2\pi jk/N}|k\rangle\end{equation}If we start with a superposition state with coefficients $x_j$, the transformed result is also a superposition state with coefficients $y_k$, where the \textit{probability amplitudes $y_k$ are the classical discrete time Fourier Transform of the probability amplitudes $x_j$}.\begin{equation}\sum_{j=0}^{N-1}x_j|j\rangle \rightarrow \sum_{k=0}^{N-1}\frac{1}{\sqrt{N}}\sum_{j=0}^{N-1}x_je^{i2\pi jk/N}|k\rangle = \sum_{k=0}^{N-1}y_k|k\rangle\end{equation}And due to quantum parallelism and quantum interference, implementing the Quantum Fourier Transform is exponentially faster than implementing the classical fast Fourier Transform algorithm. That sounds great, but there's an important catch related to quantum measurement.As you know, the measurement of a quantum state is probabilistic. Although the output of the Quantum Fourier Transform is a large superposition state with transformed probability amplitudes, we generally can't access those amplitudes. Our measurement projects out only a single state, and even if we identically prepare the system and measure it many times, we only learn about the magnitude squared of the corresponding coefficients. We lose the phase information. So we don't have access to the probability amplitudes in the quantum computer, and this is quite different from the classical Fourier Transform where the entire output vector of complex numbers can be directly read. Thus, the Quantum Fourier Transform is most useful in problems where there's a unique period or phase that can be found with high probability.If we represent the ket $|j\rangle$ in its binary representation $|j_1\rangle\otimes |j_2\rangle\otimes\cdots \otimes |j_n\rangle$, then the $n$-qubit output state can be written as the product ofnsingle-qubit states (for the derivation, see chapter 5 of Nilsen $\&$ Chuang, Eqs (5.5)-(5.10)) \begin{eqnarray}\label{eqn2}\left\vert j_{1}\right\rangle \otimes \left\vert j_{2}\right\rangle \otimes &&\nonumber...\otimes \left\vert j_{n-1}\right\rangle \otimes \left\vert j_{n}\right\rangle \rightarrow\left( \frac{\left\vert 0\right\rangle +\exp \left( 2\pi i0.j_{n}\right) \left\vert 1\right\rangle }{\sqrt{2}}\right) \otimes \left( \frac{\left\vert 0\right\rangle +\exp \left( 2\pi i0.j_{n-1}j_{n}\right) \left\vert 1\right\rangle }{\sqrt{2}}\right) \\&& \otimes ...\otimes \left( \frac{\left\vert 0\right\rangle +\exp \left( 2\pi i0.j_{2}...j_{n}\right) \left\vert 1\right\rangle }{\sqrt{2}}\right) \otimes \left( \frac{\left\vert 0\right\rangle +\exp \left( 2\pi i0.j_{1}...j_{n}\right) \left\vert 1\right\rangle }{\sqrt{2}}\right). \end{eqnarray}The figure below shows a graphical representation of the Quantum Fourier Transform for an $n$-qubit system.The figure below shows the circuit implementation of the Quantum Fourier Transform in terms of multiple Hadamard gates and controlled gates. The phase rotation $R_k$ is defined as$$R_k\lvert 0\rangle = \lvert 0\rangle,$$ $$R_k\lvert 1\rangle = \displaystyle \exp \left(i\frac{2\pi }{2^{k}}\right) \left\vert 1\right\rangle .$$ To return the qubit states to their original ordering, we need to apply **SWAP**-gates, which aregenerally used to exchange qubit states.Let's analyze how the system evolves under this implementation.A Hadamard gate is applied on the first qubit$$\lvert j_1 \rangle \rightarrow \frac{\lvert 0 \rangle + \exp (2\pi i0.j_1)\lvert 1 \rangle }{\sqrt{2}},$$and this puts the system in state$$\frac{\left\vert 0\right\rangle +\exp \left( 2\pi i0.j_{1}\right) \left\vert 1\right\rangle }{\sqrt {2}}\otimes \left\vert j_{2}\right\rangle \otimes \left\vert j_{3}\right\rangle \otimes ...\otimes \left\vert j_{n}\right\rangle .$$ A controlled phase $R_2$-gate is applied with the second qubit as control and the first as target,$$\frac{\left\vert 0 \right \rangle + \exp \left(2\pi i0.j_1 j_2\right) \left\lvert 1 \right\rangle }{\sqrt{2}}\otimes \left\lvert j_2 \right\rangle \otimes \left\lvert j_3 \right \rangle \otimes ... \otimes \left\vert j_n \right\rangle .$$A controlled phase $R_3$-gate is applied with the third qubit as control and the first as target,$$\frac{\left\vert 0\right\rangle + \exp \left(2\pi i0.j_1 j_2 j_3 \right) \left \vert 1 \right \rangle}{\sqrt{2}} \otimes \left\vert j_2 \right \rangle \otimes \left\vert j_3 \right\rangle \otimes ... \otimes \left\vert j_n \right\rangle.$$This continues until a controlled phase $R_n$-gate is applied with the last qubit as control and the first as target, leaving the system in the state$$\frac{\left\vert 0 \right \rangle + \exp \left(2\pi i0.j_1 j_2 j_3 ... j_n\right) \left\vert 1 \right\rangle}{\sqrt{2}}\otimes \left\vert j_2 \right\rangle \otimes \left\vert j_3 \right\rangle \otimes ... \otimes \left\vert j_n \right\rangle.$$A Hadamard gate is applied on the second qubit,$$\left (\frac{\left\vert0\right\rangle+\exp \left (2 \pi i0.j_1j_2j_3...j_n\right) \left\vert 1 \right\rangle}{\sqrt{2}}\right)\otimes \left(\frac{\left\vert 0 \right\rangle + \exp \left(2 \pi i0.j_2\right) \left\vert 1 \right\rangle}{\sqrt{2}}\right) \otimes \left\vert j_3 \right\rangle \otimes ... \otimes \left\vert j_n\right\rangle.$$A controlled phase $R_2$ -gate is applied with the third qubit as control and the second as target,$$\left(\frac{\left\vert 0 \right\rangle + \exp \left (2 \pi i0.j_1 j_2 j_3 ... j_n\right) \left\vert 1 \right\rangle}{\sqrt{2}}\right) \otimes \left(\frac{\left\vert 0 \right\rangle + \exp \left(2\pi i0.j_2 j_3 \right) \left\vert 1 \right\rangle}{\sqrt{2}}\right) \otimes \left\vert j_3\right\rangle\otimes ... \otimes \left\vert j_n \right\rangle.$$This continues until a controlled phase $R_{n-1}$-gate is applied with the last qubit as control and the second as target, leaving the system in the state$$\frac{\left\vert 0 \right\rangle + \exp \left(2\pi i0.j_1 j_2 j_3 ... j_n \right) \left\vert 1 \right\rangle}{\sqrt{2}}\otimes\frac{\left\vert 0\right\rangle + \exp \left(2 \pi i0.j_2 j_3 ... j_n\right) \left\vert 1 \right\rangle }{\sqrt{2}} \otimes \left\vert j_3 \right\rangle \otimes ... \otimes \left\vert j_n\right\rangle.$$This same process is done on each qubit until the last qubit, on which you can only apply a Hadamard gate. This implementation transforms as\begin{eqnarray}\label{eqn3}\left\vert j_{1}\right\rangle \otimes \left\vert j_{2}\right\rangle \otimes ...\otimes \left\vert j_{n-1}\right\rangle \otimes \left\vert j_{n}\right\rangle &&\rightarrow \left( \frac{\left\vert 0\right\rangle +\exp \left( 2\pi i0.j_{1}...j_{n}\right) \left\vert 1\right\rangle }{\sqrt{2}}\right) \\&&\nonumber\otimes \left( \frac{\left\vert 0\right\rangle +\exp \left( 2\pi i0.j_{2}...j_{n}\right) \left\vert 1\right\rangle }{\sqrt{2}}\right) \otimes ...\\&&\nonumber \otimes \left( \frac{\left\vert 0\right\rangle +\exp \left( 2\pi i0.j_{n-1}j_{n}\right) \left\vert 1\right\rangle }{\sqrt{2}}\right) \\&&\nonumber\otimes \left( \frac{\left\vert 0\right\rangle +\exp \left( 2\pi i0.j_{n}\right) \left\vert 1\right\rangle }{\sqrt{2}}\right) .\end{eqnarray}To returnthe qubit states to their original ordering, we need to apply swap-gates, which are generally usedto exchange qubit states. Implement QFT and Inverse QFT
###Code
def create_QFT(circuit, reg, n , with_swaps = False):
""" Function to create QFT """
# Apply the H gates and Cphases
""" The Cphases with |angle| < threshold are not created because they do
nothing. The threshold is put as being 0 so all CPhases are created,
but the clause is there so if wanted just need to change the 0 of the
if-clause to the desired value """
i = n - 1
while i >= 0:
circuit.h(up_reg[i])
j = i - 1
while j >= 0:
if (np.pi) / (pow(2, (i-j))) > 0:
circuit.cu1((np.pi)/(pow(2, (i-j))), reg[i], reg[j]) # cu1(angle, ctrl, trgt)
j = j - 1
i = i - 1
# If specified, apply the Swaps at the end
if with_swaps == True:
i=0
while i < ((n-1) / 2):
circuit.swap(reg[i], reg[n-1-i])
i = i + 1
def create_inverse_QFT(circuit, reg, n, with_swaps=False):
""" Function to create inverse QFT """
# If specified, apply the Swaps at the beggining
if with_swaps == True:
i = 0
while i < ((n-1)/2):
circuit.swap(reg[i], reg[n-1-i])
i = i + 1
""" Apply the H gates and Cphases"""
i=0
while i < n:
circuit.h(reg[i])
if i != n-1:
j = i + 1
y = i
while y>=0:
if (np.pi) / (pow(2, (j-y))) > 0:
circuit.cu1(-(np.pi) / (pow(2, (j-y))), reg[j], reg[y])
y = y - 1
i = i + 1
###Output
_____no_output_____
###Markdown
Going back to implementing the CC adder and the "mod N" version of it Let's implement the circuit and it's inverse.
###Code
def controlled_controlled_add_mod_N(circuit, q, ctrl1, ctrl2, aux, a, N, n):
"""Circuit that implements doubly controlled modular addition by a
args: self explanatory from the picture"""
controlled_controlled_add_in_fourier_space(circuit, q, ctrl1, ctrl2, a, n)
add_in_fourier_space(circuit, q, N, n, inv=True)
create_inverse_QFT(circuit, q, n)
circuit.cx(q[n-1], aux)
create_QFT(circuit, q, n)
controlled_add_in_fourier_space(circuit, q, aux, N, n)
controlled_controlled_add_in_fourier_space(circuit, q, ctrl1, ctrl2, a, n, inv=True)
create_inverse_QFT(circuit, q, n)
circuit.x(q[n-1])
circuit.cx(q[n-1], aux)
circuit.x(q[n-1])
create_QFT(circuit, q, n)
controlled_controlled_add_in_fourier_space(circuit, q, ctrl1, ctrl2, a, n)
def controlled_controlled_add_mod_N_inv(circuit, q, ctrl1, ctrl2, aux, a, N, n):
"""Circuit that implements the inverse of doubly controlled modular addition by a"""
controlled_controlled_add_in_fourier_space(circuit, q, ctrl1, ctrl2, a, n, inv=True)
create_inverse_QFT(circuit, q, n)
circuit.x(q[n-1])
circuit.cx(q[n-1], aux)
circuit.x(q[n-1])
create_QFT(circuit, q, n)
controlled_controlled_add_in_fourier_space(circuit, q, ctrl1, ctrl2, a, n)
controlled_add_in_fourier_space(circuit, q, aux, N, n, inv=True)
create_inverse_QFT(circuit, q, n)
circuit.cx(q[n-1], aux)
create_QFT(circuit, q, n)
add_in_fourier_space(circuit, q, N, n)
controlled_controlled_add_in_fourier_space(circuit, q, ctrl1, ctrl2, a, n, inv=True)
###Output
_____no_output_____
###Markdown
Implement the controlled multiplication mod N circuit
###Code
# helper functions
def euclid_gcd(a, b):
if a == 0:
return (b, 0, 1)
else:
g, y, x = euclid_gcd(b%a, a)
return (g, x-(b//a)*y, y)
def mod_inv(a, m):
g, x, y = euclid_gcd(a, m)
if g != 1:
raise Exception('modular inverse does not exist')
else:
return x % m
def controlled_mult_mod_N(circuit, ctrl, q, aux, a, N, n):
"""Circuit that implements single controlled modular multiplication by a
args: self explanatory from the picture"""
# CMULT(a) mod N
create_QFT(circuit, aux, n+1)
for i in range(0, n):
controlled_controlled_add_mod_N(circuit, aux, q[i], ctrl, aux[n+1], (2**i)*a % N, N, n+1)
create_inverse_QFT(circuit, aux, n+1, 0)
for i in range(0, n):
circuit.cswap(ctrl, q[i], aux[i])
# CMULT(a^{-1}) mod N,
# this is done to make sure circuit is reversible so that we can use the qubits further
a_inv = mod_inv(a, N)
create_QFT(circuit, aux, n+1, 0)
i = n-1
while i >= 0:
controlled_controlled_add_mod_N_inv(circuit, aux, q[i], ctrl, aux[n+1], math.pow(2,i)*a_inv % N, N, n+1)
i -= 1
create_inverse_QFT(circuit, aux, n+1, 0)
###Output
_____no_output_____
###Markdown
Going back to the original Shor's circuit and measurement of the Register 1 Now, returning to Shor's Algorithm, the Quantum Fourier Transform is applied here to the qubits in Register 1, and it imparts specific phase factors that are related to both $x$ and $z$.\begin{eqnarray} \frac{1}{\sqrt{2^{2L}}}\sum_{x=0}^{2^{2L-1}}|x\rangle|a^x \mod N\rangle \xrightarrow {\substack{QFT}} &&\nonumber \frac{1}{\sqrt{2^{2L}}} \sum_{z=0}^{2^{2L-1}}\sum_{x=0}^{2^{2L-1}} e^{i2\pi xz/2^{2L}}|z\rangle|a^x \mod N\rangle \\&&\nonumber = \frac{1}{\sqrt{2^{2L}}}\sum_{z=0}^{2^{2L-1}}\sum_{x=0}^{2^{2L-1}} \omega^{xz}|z\rangle|a^x \mod N\rangle\end{eqnarray}That is, they're related to both the coefficients of the qubits on Register 1 and the modular exponentiation stored on Register 2. The phase sampling increment is represented here by $\omega$, and it's the phase $$\frac{2\pi}{2^{2L}}.$$ Here we can see that increasing the number of qubits ($L$) will reduce the step size, and thus the error in estimating the actual period. Essentially, more qubits will more densely sample the phases that represent the period. Lastly, we measure the qubits in Register 1. The projected state that results is a binary value of $z$, and its decimal value is $$z_{\text{decimal}} = \text{integer} ~ \times 2^{2L}/r. $$ Thus, it can be used to find the period $r$ using a [continued fraction expansion](https://en.wikipedia.org/wiki/Continued_fraction) of $z/2^{2L}$. Putting everyting together Postprocessing the measurement and finding factors p and q of N=pq Here are the steps of Shor's algorithm 1. randomly pick a number, $a$, that's smaller than $N$ and relatively prime. That is, their greatest common divisor--$\gcd (a,N)=1$. 2. We then use Shor's Algorithm to find the period of $a^x \mod N$. Shor's Algorithm, with classical post-processing, will efficiently give us the period $r$. Before proceeding, we need to do a couple checks. $r$ must be an even number we need to ensure that $a^{r/2} + 1 \neq 0 \mod N$. If we fail either of these tests, we need to go back to step 1 and pick another value of $a$. 3. We know that $$a^r = 1 \mod N,$$ as this is a property of modular exponentiation. We can rewrite this expression as $$a^r - 1 = k N$$ for an integer $k$. 4. Replace $N$ with the unknown prime factors $p$ and $q$, and we factor the left-hand side to yield $$a^r-1 = kpq.$$ $$(a^{r/2}+1)(a^{r/2}-1) = kpq$$ 5. Finally solve for $p$ and $q$: $$p=\gcd (a^{r/2}+1, N)$$ $$q=\gcd (a^{r/2}-1, N)$$
###Code
# Choose N
N = 15
def get_value_a(N):
""" Function to get the value a (1 < a < N), such that a and N are coprime. """
#YOUR CODE HERE
a = random.randint(2,N)
while math.gcd(a,N)!= 1:
a = random.randint(2,N)
return a
# choose a
a = get_value_a(N)
# define number of qubits
n = math.ceil(math.log(N, 2))
print('Total number of qubits used: {0}\n'.format(4*n + 2))
# Let's create quantum and classical registers
# auxilliary quantum register used in addition and multiplication
aux = QuantumRegister(n + 2)
# quantum register where the sequential QFT is performed
up_reg = QuantumRegister(2 * n)
# quantum register where the multiplications are made
down_reg = QuantumRegister(n)
# classical register where the measured values of the QFT are stored
classic_reg = ClassicalRegister(2 * n)
# Create Quantum Circuit!
circuit = QuantumCircuit(down_reg , up_reg , aux, classic_reg)
# Initialize down register to |1> (see pic)
# and create maximal superposition in top register
circuit.h(up_reg)
circuit.x(down_reg[0])
# Apply the multiplication gates in order to create the exponentiation
for i in range(0, 2*n):
controlled_mult_mod_N(circuit, up_reg[i], down_reg, aux, int(pow(a, pow(2, i))), N, n)
# Apply inverse QFT
create_inverse_QFT(circuit, up_reg, 2*n ,1)
# Measure the top qubits, to get value C
circuit.measure(up_reg, classic_reg)
def continued_fractions(C, K):
"""
implements the cont frac algo
C = a_0 + 1/(a_1 + 1/(a_2 + 1/(a_3 + .../(a_{K-1} + 1/a_K))))
returns the list of [a_0, a_1, ..., a_K]
"""
a = []
# YOUR CODE HERE
t = math.floor(C)
a.append(t)
C = C - t
i = 0
while C!=0 and i<K:
t = math.floor(1/C)
a.append(t)
C = 1/C-t
i += 1
return a
def convergents(a):
"""
Finds convergents from coefficients
param a: list, output of function continued_fractions(C, K)
"""
print('a=: ', a)
z = []
r = []
# set the first two elements: z0 = a0, z1=a1a0 + 1, r0=1, r1=a1
z.append(a[0])
r.append(1)
z.append(a[1] * a[0] + 1)
r.append(a[1])
# YOUR CODE HERE
k = len(a)
for i in range (2,k):
z.append(a[i]*z[i-1]+z[i-2])
r.append(a[i]*r[i-1]+r[i-2])
return z, r
def check_and_return_period(C,N,K=10):
""" checks if f(x)=a^{r_k} mod N = 1
returns r period"""
# YOUR CODE HERE
c_frac= continued_fractions(C/2**n,K)
z,r = convergents(c_frac)
for i in range(0,len(c_frac)-1):
if ((a**r[i])% N) == 1 :
return r[i]
def find_factors(r):
# YOUR CODE HERE
p = math.gcd(N, int(a**(r/2))+1)
q = math.gcd(N, int(a**(r/2))-1)
return p,q
###Output
_____no_output_____
###Markdown
Run everyting and find factors
###Code
""" Simulate the created Quantum Circuit """
# to run on IBM, use backend=IBMQ.get_backend('ibmq_qasm_simulator') in execute() function
# to run locally, use backend=BasicAer.get_backend('qasm_simulator') in execute() function
simulation = execute(circuit, backend=BasicAer.get_backend('qasm_simulator'), shots=10)
# Get the results of the simulation in proper structure
sim_result=simulation.result()
counts_result = sim_result.get_counts(circuit)
# Get the C value from the final state qubits
output_desired = list(sim_result.get_counts().keys())[i]
print('output_desired=: ', output_desired)
C = int(output_desired, 2)
print('C=: ', C)
result = (int(list(sim_result.get_counts().values())[i] ) )
print("------> Analysing result {0}. \
This result happened in {1:.4f} % of all cases\n".format(output_desired, result))
# Print the final C value to user
print('In decimal, C value for this result is: {0}\n'.format(C))
# Get the period using the value obtained
period = check_and_return_period(C, 10, N)
print('period is : ', period)
# Get the factors using the period r
factors = find_factors(period)
print('the factors are : ', factors)
###Output
output_desired=: 11111100
C=: 252
------> Analysing result 11111100. This result happened in 1.0000 % of all cases
In decimal, C value for this result is: 252
a=: [15, 1, 3, 1125899906842624]
period is : 4
the factors are : (5, 3)
|
basics_numpy.ipynb | ###Markdown
- Notes on using external packages
###Code
DELIMITER = ','
dataset = np.loadtxt("basics_dataset.txt", delimiter=DELIMITER)
print(dataset)
print(type(dataset))
###Output
<class 'numpy.ndarray'>
###Markdown
- Notes on the the numpy NDArray object
###Code
dataset[0]
dataset[0, :]
dataset[:, 0]
dataset[-1]
dataset[:, -1]
###Output
_____no_output_____
###Markdown
- Notes on indexing lists and numpy NDArrays- Note on advanced indexing
###Code
dataset[:, :2]
dataset[1:4, :]
###Output
_____no_output_____ |
mgnify/src/others/ERP009703_go_temperature_analysis_v4.ipynb | ###Markdown
Plotting temperature and photosynthesis-related GO term counts, normalised by number of InterPro annotations, for Ocean Sampling Day (OSD) 2014: amplicon and metagenome sequencing study from the June solstice in the year 2014, project PRJEB8682The following task shows how to analysie metadata and annotations retrieved from the EMG API and combined on the fly to generate the visualisations.
###Code
import copy
try:
from urllib import urlencode
except ImportError:
from urllib.parse import urlencode
from pandas import DataFrame
import matplotlib.pyplot as plt
import numpy as np
from jsonapi_client import Session, Filter
API_BASE = 'https://www.ebi.ac.uk/metagenomics/api/v0.2/'
###Output
_____no_output_____
###Markdown
List all runshttps://www.ebi.ac.uk/metagenomics/api/v0.2/pipelines/4.0/runs?experiment_type=metagenomic&study_accession=ERP009703
###Code
def find_metadata(metadata, key):
"""
Extract metadata value for given key
"""
for m in metadata:
if m.var_name.lower() == key.lower():
return m.var_value
return None
metadata_key = 'temperature'
normilize_key = 'Predicted CDS with InterProScan match'
# map GO terms to the temperature
result = {}
with Session(API_BASE) as s:
# list of runs missing metadata
missing_meta = list()
print('Loading data from API.', end='', flush=True)
# preparing url
params = {
'experiment_type': 'metagenomic',
'study_accession': 'ERP009703',
}
f = Filter(urlencode(params))
# list runs
for anls in s.iterate('pipelines/4.0/analysis', f):
print('.', end='', flush=True)
# find temperature
m_value = float(find_metadata(anls.sample.metadata, metadata_key))
if m_value is None:
# missing value, skip run!
missing_meta.append(anls.accession)
continue
_pcds = int(find_metadata(anls.metadata, normilize_key))
if _pcds is None:
# missing value, skip run!
continue
try:
result[m_value]
except KeyError:
result[m_value] = {}
# list a summary of GO terms derived from InterPro matches
rt = "runs/%s/pipelines/%s/go-slim" % (anls.accession, anls.pipeline_version)
af = Filter(urlencode({'page_size': 100}))
for ann in s.iterate(rt, af):
try:
result[m_value][ann.accession]
except KeyError:
result[m_value][ann.accession] = list()
# normalize annotation counts, adjusting value
_norm = int(ann.count)/_pcds
# assign value
result[m_value][ann.accession].append(_norm)
print("DONE")
print("Missing: ", missing_meta)
###Output
Loading data from API.......................................................................................................................................................DONE
Missing: []
###Markdown
Clean up data
###Code
# remove invalid temperatures
for k in copy.deepcopy(list(result.keys())):
if k > 2000:
del result[k]
# average value of the same temperature
for k in result:
for k1 in result[k]:
result[k][k1] = np.mean(result[k][k1])
###Output
_____no_output_____
###Markdown
Plot
###Code
df = DataFrame(result).T
df_go = df[['GO:0009579','GO:0015979']].copy()
df_go = df_go.dropna()
df_go.plot(y=['GO:0009579', 'GO:0015979'], use_index=True, style='o')
plt.show()
###Output
_____no_output_____
###Markdown
Calculate correlation
###Code
from scipy.stats import spearmanr
x = df_go.index.tolist()
correl = []
correl_p = []
for k in df_go.keys():
y = list(df_go[k])
rho, p = spearmanr(x, y)
correl.append(rho)
correl_p.append(p)
df_go.loc['rho'] = correl
df_go.loc['p'] = correl_p
df_go
###Output
_____no_output_____ |
Magic_notebook.ipynb | ###Markdown
Creature power averages in last years standard.I wanted to take a look at the powers from each color in Magic the Gathering and see the range between them.The goal was to see if there were creatures with stronger powers in one color.
###Code
import pandas as pd
import matplotlib.pyplot as plt # Allows me to make the graphs.
plt.rcParams.update({'font.size': 20, 'figure.figsize': (10, 8)}) # Set font and plot size to be larger.
from scipy.stats import f_oneway
import scikit_posthocs as sp
import numpy as np
# Assinging my data of "standard" cards to magic_df
magic_df = pd.read_json('StandardCards.json')
# Placing card names as the begining of each row.
magic_df = magic_df.transpose()
# Replaced all instances of * in the power column.
magic_df["power"] = magic_df["power"].replace('*', 1)
# pandas.to_numeric(arg, errors='raise', downcast=None)
# Converted all powers from string to numbers.
magic_df["power"] = pd.to_numeric(magic_df["power"])
# Placed all creatures in here.
creatures = magic_df[(magic_df["power"] >= 0)]
# mask = magic_df["colors"].apply(lambda val: 'W' in val) and len(val) == 1) frames = pdf1, df2, df3] anova pythonimport numpy scipy oneway! Info from professor during class Q and A.
# df1 - magic_df[mask]
# Attempting to separate creature colors.
maskW = creatures["colors"].apply(lambda val: 'W' in val and len(val) == 1)
white_creatures = creatures[maskW]
maskG = creatures["colors"].apply(lambda val: 'G' in val and len(val) == 1)
green_creatures = creatures[maskG]
maskU = creatures["colors"].apply(lambda val: 'U' in val and len(val) == 1)
blue_creatures = creatures[maskU]
maskR = creatures["colors"].apply(lambda val: 'R' in val and len(val) == 1)
red_creatures = creatures[maskR]
maskB = creatures["colors"].apply(lambda val: 'B' in val and len(val) == 1)
black_creatures = creatures[maskB]
###Output
_____no_output_____
###Markdown
So the above coding is just me setting everything up. I have in the comments what's happening, but a short explanation would be that I had to find all instances of "*" in the creatures powers and replace them with 0. Then I had to convert the powers to integers and then stuffed them all in the creatures variable.Below in each graph you will see that there are gaps/holes. I don't understand what the cause of that is, but I don't believe it means that there is nonthing there. However the graphs determine what gets filled in must not be reading it properly from the data given.
###Code
# White creatures power frequency (histogram).
white_creatures['power'].plot(kind='hist', title='White Creatures Power');
# White creatures power (boxplot).
white_creatures['power'].plot(kind="box");
# Green creatures power frequency (histogram).
green_creatures['power'].plot(kind='hist', title='Green Creatures Power');
# Green creatures power (boxplot).
green_creatures['power'].plot(kind="box");
# Red creatures power frequency (histogram).
red_creatures['power'].plot(kind='hist', title='Red Creatures Power');
# Red creatures power (boxplot).
red_creatures['power'].plot(kind="box");
# Blue creatures power frequency (histogram).
blue_creatures['power'].plot(kind='hist', title='Blue Creatures Power');
# Blue creatures power (boxplot).
blue_creatures['power'].plot(kind="box");
# Black creatures power frequency (histogram).
black_creatures['power'].plot(kind='hist', title='Black Creatures Power');
# Black creatures power (boxplot).
black_creatures['power'].plot(kind="box");
#https://datatofish.com/horizontal-bar-chart-matplotlib/ Where I got the information on how to create horizontal graphs.
colours = ['White', 'Green', 'Red', 'Blue', 'Black']
powers = [white_creatures['power'].mean(), green_creatures['power'].mean(), red_creatures['power'].mean(), blue_creatures['power'].mean(), black_creatures['power'].mean()]
plt.barh(colours, powers)
plt.title('Creature Power Averages')
plt.ylabel('Colors')
plt.xlabel('Power Averages')
plt.show()
###Output
_____no_output_____
###Markdown
The Graphs AboveLooking at the graphs we can see that normal power ranges went from 0 to 3. Then we had less cards when it came to 4+ and a few extreme cases of them going above 7.The majority of the creatures though fell between 2 - 3 when we look at the final graph that has the averages of the five colors. To answer my initial question based off of the averages I was able to obtain it would appear that Green had more creatures of higher powers and the others, followed by what appears to be a tie between Black and Red, then White, and lastly Blue.
###Code
# scipy.stats.f_oneway
F, p = f_oneway(white_creatures_powers, green_creatures_powers, red_creatures_powers, blue_creatures_powers, black_creatures_powers)
print(F)
print(p)
###Output
3.59545707330559
0.0066229033280666965
###Markdown
Here I tried to do some work with regression and finding the significant values, but I was not able to get the data in the format I neededor I was unable to properly code this.
###Code
# Pin pointing down to the powers only
white_creatures_powers = white_creatures['power']
green_creatures_powers = green_creatures['power']
red_creatures_powers = red_creatures['power']
blue_creatures_powers = blue_creatures['power']
black_creatures_powers = black_creatures['power']
# Making an array out of each color.
white_array = [white_creatures_powers]
green_array = [green_creatures_powers]
red_array = [red_creatures_powers]
blue_array = [blue_creatures_powers]
black_array = [black_creatures_powers]
# Made each color it's own dataframe
wcp_df = pd.DataFrame(white_array)
gcp_df = pd.DataFrame(green_array)
rcp_df = pd.DataFrame(red_array)
ucp_df = pd.DataFrame(blue_array)
bcp_df = pd.DataFrame(black_array)
# Grabbed them all here
frames = [wcp_df, gcp_df, rcp_df, ucp_df, bcp_df]
# Combined them all displaying color and power as column headers and name at the beginning of row.
mashed = pd.concat(frames)
# Here is where I'm the most confused and don't understand how to format the data.
sp.posthoc_nemenyi_friedman(mashed)
###Output
_____no_output_____ |
Arrays and Linked Lists/006_Detecting Loops.ipynb | ###Markdown
Detecting Loops in Linked ListsIn this notebook, you'll implement a function that detects if a loop exists in a linked list. The way we'll do this is by having two pointers, called "runners", moving through the list at different rates. Typically we have a "slow" runner which moves at one node per step and a "fast" runner that moves at two nodes per step.If a loop exists in the list, the fast runner will eventually move behind the slow runner as it moves to the beginning of the loop. Eventually it will catch up to the slow runner and both runners will be pointing to the same node at the same time. If this happens then you know there is a loop in the linked list. Below is an example where we have a slow runner (the green arrow) and a fast runner (the red arrow).
###Code
class Node:
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self, init_list=None):
self.head = None
if init_list:
for value in init_list:
self.append(value)
def append(self, value):
if self.head is None:
self.head = Node(value)
return
# Move to the tail (the last node)
node = self.head
while node.next:
node = node.next
node.next = Node(value)
return
list_with_loop = LinkedList([2, -1, 3, 0, 5])
# Creating a loop where the last node points back to the second node
loop_start = list_with_loop.head.next
node = list_with_loop.head
while node.next:
node = node.next
node.next = loop_start
###Output
_____no_output_____
###Markdown
>**Exercise:** Given a linked list, implement a function `iscircular` that returns `True` if a loop exists in the list and `False` otherwise.
###Code
def iscircular(linked_list):
"""
Determine wether the Linked List is circular or not
Args:
linked_list(obj): Linked List to be checked
Returns:
bool: Return True if the linked list is circular, return False otherwise
"""
# TODO: Write function to check if linked list is circular
if linked_list.head is None:
return False
slow = linked_list.head
fast = linked_list.head
while fast and fast.next:
# slow pointer moves one node
slow = slow.next
# fast pointer moves two nodes
fast = fast.next.next
if slow == fast:
return True
# Test Cases
small_loop = LinkedList([0])
small_loop.head.next = small_loop.head
print ("Pass" if iscircular(list_with_loop) else "Fail")
print ("Pass" if not iscircular(LinkedList([-4, 7, 2, 5, -1])) else "Fail")
print ("Pass" if not iscircular(LinkedList([1])) else "Fail")
print ("Pass" if iscircular(small_loop) else "Fail")
print ("Pass" if not iscircular(LinkedList([])) else "Fail")
###Output
Pass
Pass
Pass
Pass
Pass
|
PaperPinelineCodes/CodesOnLongerUsed/CodeCheck -CleanUpTracksAndGetWhiskingParameters.ipynb | ###Markdown
remove x y points based on threshold ( of rmse distance from previous frame )
###Code
direc = r"../dataFolders/PaperPipelineOutput/RawTracks/"
visitnum = 'FirstVisit/'
path = os.path.join(direc, visitnum)
trackslist = glob.glob(path + '*.csv')
name = 'c-2_m22_'
f = [file for file in trackslist if name in file]
f
circ_parameters_path = glob.glob('../dataFolders/PaperPipelineOutput/CircleParameters/' + '*.csv')
circ_parameters = pd.read_csv(circ_parameters_path[0])
data = f[0]
name = os.path.basename(data)[:-4]
print(name)
file = pd.read_csv(data)
x = file.x.values
y = file.y.values
p = file.likelihood
x_notinView = x <=5
y_notinView = y <=5
x[x_notinView & y_notinView]=np.nan
y[x_notinView & y_notinView]=np.nan
# add filter for DLC likelihood
med = file['likelihood'].rolling(11).median()
x[med < 0.6] = np.nan
y[med < 0.6] = np.nan
if x.size == 0 or y.size == 0:
print(name + 'has emtpy x y tracks')
axes = file.plot(subplots=True, figsize=(15,4))
med = file['likelihood'].rolling(11).median()
plt.plot(med)
plt.plot(x,y, 'o-.', alpha = 0.2)
plt.xlim(0, 648)
plt.ylim(0,488)
plt.title('camera view')
name = [n for n in circ_parameters.name if n + '_' in f[0]][0]
circ_x = circ_parameters.loc[circ_parameters.name == name, 'circ_x'].values
circ_y = circ_parameters.loc[circ_parameters.name == name, 'circ_y'].values
circ_radii = circ_parameters.loc[circ_parameters.name == name, 'circ_radii'].values
cent_x = x - circ_x
cent_y = x - circ_y
r = np.linalg.norm([cent_x, cent_y], axis = 0)
r = r/circ_radii
trajectory = pd.DataFrame([x, y, r]).T
trajectory.columns = ['x', 'y', 'r']
axes = trajectory.plot(subplots=True, figsize=(15,4))
# get rmse values for subsequent frames
rmse = GetRMSE(x[1:], y[1:], x[:-1], y[:-1])
filtered_x = np.copy(x[1:])
filtered_y = np.copy(y[1:])
filtered_x[(rmse > cutoff) | (rmse == np.nan)] = np.nan
filtered_y[(rmse > cutoff) | (rmse == np.nan)] = np.nan
filtered_r = np.linalg.norm([filtered_x - circ_x, filtered_y - circ_y], axis = 0)
filtered_r = filtered_r/circ_radii
filt_trajectory = pd.DataFrame([filtered_x, filtered_y, filtered_r]).T
filt_trajectory.columns = ['x', 'y', 'r']
axes = filt_trajectory.plot(subplots=True, figsize=(15,4))
t = (pd.Series(filtered_x).rolling(30).median(center=True))
t_reverse = t[::-1]
t_reverse
s_end = np.argmax([ ~np.isnan(t) for t in r_reverse ] )
trim_end = len(t)-s
t_begin = (pd.Series(filtered_x).rolling(3).median(center=True))
s_begin = np.argmax([ ~np.isnan(t) for t in t_begin ] )
trim_begin = s_begin
s_begin
# Apply filters
trajectory = filt_trajectory.copy()
trajectory = trajectory.drop(['r'], axis = 1)
trajectory = trajectory.loc[trim_begin:trim_end, :]
print(trajectory.shape)
for colname in trajectory.columns:
print(colname)
trajectory.loc[:, colname] = signal.medfilt(trajectory.loc[:, colname], kernel_size=11)
# trajectory.loc[:,colname] = trajectory.loc[:,colname].interpolate(method = 'polynomial', order = 3)
trajectory.loc[:, colname] = trajectory.loc[:, colname].interpolate(method = 'polynomial', order = 3, limit = 40)
nans = trajectory.loc[:,colname].isnull()
trajectory.loc[:,colname] = trajectory.loc[:,colname].interpolate(method = 'pad')
# trajectory.loc[:,colname] = interpolate.interp1d(trajectory.loc[:,colname])
trajectory.loc[:, colname] = signal.savgol_filter(trajectory.loc[:, colname],window_length=15,polyorder=3, axis=0)
trajectory.loc[nans, colname]= np.nan
r = np.linalg.norm([trajectory.loc[:,'x'].values - circ_x, trajectory.loc[:,'y'].values - circ_y], axis = 0)
trajectory['r'] = r/circ_radii
axes = pd.concat([filt_trajectory, trajectory], axis = 1).plot(subplots = True, figsize = (15,8))
x_interpl = x.interpolate(method='polynomial', order=interpol_order)
y_interpl = y.interpolate(method='polynomial', order=interpol_order)
x_interpl = x_interpl[~np.isnan(x_interpl)]
y_interpl= y_interpl[~np.isnan(y_interpl)]
r_interpl = np.linalg.norm([x_interpl - circ_x, y_interpl - circ_y], axis = 0)
r_interpl = r_interpl/circ_radii
_,ax = plt.subplots(3,1, figsize = (20,6))
ax[0].plot(x_interpl)
ax[1].plot(y_interpl)
ax[2].plot(r_interpl)
ax[2].set_xlabel('Frames')
plt.suptitle('interpolated Data')
# savitzky-golay method for smoothening
x_savgol = signal.savgol_filter(x_interpl, savgol_win, savgol_polyorder)
y_savgol = signal.savgol_filter(y_interpl, savgol_win, savgol_polyorder)
r_savgol = np.linalg.norm([x_savgol- circ_x, y_savgol- circ_y], axis = 0)
r_savgol = r_savgol/circ_radii
_,ax = plt.subplots(3,1, figsize = (20,6))
ax[0].plot(x_savgol)
ax[1].plot(y_savgol)
ax[2].plot(r_savgol)
ax[2].set_xlabel('Frames')
plt.suptitle('smoothened Data')
###Output
_____no_output_____
###Markdown
I don't believe the last bit of the data, look at DLC confidence in that interval
###Code
plt.scatter(np.arange(len(r_savgol)), r_savgol, c = file.likelihood[2:-1], cmap = plt.cm.cool )
plt.colorbar()
###Output
_____no_output_____
###Markdown
Possible solution - use DLC likehood and remove points less than 0.4
###Code
x = pd.Series(filtered_x)
y = pd.Series(filtered_y)
x_interpl = x.interpolate(method='polynomial', order=interpol_order)
y_interpl = y.interpolate(method='polynomial', order=interpol_order)
x_interpl = x_interpl[~np.isnan(x_interpl)]
y_interpl= y_interpl[~np.isnan(y_interpl)]
plt.plot(x_interpl, y_interpl, 'o-')
###Output
_____no_output_____
###Markdown
OHHH FUCK! Should be using 2D interpolation, shouldn't I?
###Code
# lets first look at DLC likelihood
# plt.scatter(np.arange(len(filtered_x)),filtered_x, c = file.likelihood[1:], cmap = plt.cm.cool)
# plt.show()
plt.scatter(filtered_x, filtered_y, c = file.likelihood[1:], cmap = plt.cm.cool)
plt.colorbar()
###Output
_____no_output_____
###Markdown
get angle and magnitude
###Code
def Unitvector(x_gauss, y_gauss):
from sklearn import preprocessing
# get the slope of the tangent
trajectory = np.asarray([x_gauss, y_gauss])
m = np.gradient(trajectory, axis = 1)
m_atx = m[1]/m[0]
# get the tangent vector at x = x0 + 1
tangent_x = x_gauss+1
tangent_y = m_atx + y_gauss
# get the unit tangent vector
u_x = []
u_y = []
for x,y,x0,y0 in zip(tangent_x, tangent_y, x_gauss, y_gauss):
if np.any(np.isnan([x, y])) or np.any(np.isinf([x, y])):
unit_x = np.nan
unit_y = np.nan
else:
vector = np.asarray([x-x0, y-y0]).reshape(1,-1)
[unit_x, unit_y] = preprocessing.normalize(vector, norm = 'l2')[0]
u_x.append(unit_x)
u_y.append(unit_y)
u_x = np.asarray(u_x)
u_y = np.asarray(u_y)
return(u_x, u_y)
def getAngle(loc, tangent):
cross = np.cross(tangent, loc)
dot = np.dot(tangent, loc)
angle = np.arctan2(cross, dot)*180/np.pi
return(angle)
def wrapAngle(angle):
angle = np.absolute(angle)
for i,a in enumerate(angle):
if a > 90:
a = 180 - a
angle[i] = a
return(angle)
r = np.linalg.norm([x_interpl, y_interpl], axis = 0)
r = r/circ_radii
# savitzky-golay method
x_savgol = signal.savgol_filter(x_interpl, savgol_win, savgol_polyorder)
y_savgol = signal.savgol_filter(y_interpl, savgol_win, savgol_polyorder)
r_savgol = np.linalg.norm([x_savgol, y_savgol], axis = 0)
r_savgol_norm = r_savgol/circ_radii
# save all usable variables as series
df1 = pd.Series(data = x_savgol, name = 'x_savgol')
df2 = pd.Series(data = y_savgol, name = 'y_savgol')
df3 = pd.Series(data = r_savgol_norm, name = 'radial distance savgol')
#calculate the unit tangent vectors - savitzky-golay vector
u_x, u_y = Unitvector(x_savgol, y_savgol)
angle_savgol = []
for x0, y0, x, y in zip(x_savgol, y_savgol, u_x, u_y):
loc = [x0, y0]
tangent = [x, y]
a = getAngle(loc, tangent)
angle_savgol.append(a)
angle_savgol = wrapAngle(angle_savgol)
df4 = pd.Series(data = angle_savgol, name = 'angle_savgol')
# new_file = pd.concat([file, df1, df2, df3, df4], axis = 1)
# new_file.to_csv(newpath + name + 'RadiusAndAngle.csv', index_label = False)
###Output
_____no_output_____ |
Notebooks/Data Analysis.ipynb | ###Markdown
Analyzing Historical Forex Rates DataAuthor: Joshua HewThis notebook was made to sort and analyze the data stored in the database Setup
###Code
import os
import pandas as pd
import matplotlib.pyplot as plt
import datetime
# enable access to local data and python scripts
os.chdir("C:\\Users\\admin\\Desktop\\Dev\\MachineLearning\\Forex")
# print plots inline
%matplotlib inline
# import data from csv into dataframe
df = pd.read_csv('historical_forex_rates.csv')
# preview data
df
###Output
_____no_output_____
###Markdown
Cleaning and Preparing Data:- sort the data by date- check for missing dates between our data's current date range: 1999-01-01 to 2004-12-01- convert all currency rates to have base USD- remove extraneous data
###Code
def sort_by_date(df):
""" returns a new dataframe sorted by date in ascending order."""
# sort by date
df['date'] = pd.to_datetime(df['date'])
df = df.sort_values(by='date')
# reset indexing
df = df.reset_index(drop=True)
return df
df = sort_by_date(df)
# view data
df
# check for missing dates between the 1999-01-01 and 2004-12-01 date in dataframe
def get_missing_dates(df):
# TODO: once I catch up and reupload the csv, will use min and max for start and end dates
# TODO: maybe find less expensive way of finding missing dates
# gets the series that contains the date of every forex rate
dates = df['date']
# create range of dates to check through
start_date = datetime.datetime(1999, 1, 1)
end_date = datetime.datetime(2004, 12, 1)
# convert series of datetime objects to list of strings so that it is easier to use comparison operations
dates = [str(i) for i in dates]
missing_dates = []
curr_date = start_date
while curr_date < end_date:
if str(curr_date) not in dates:
missing_dates.append(curr_date)
curr_date += datetime.timedelta(days=1)
return missing_dates
missing_dates = get_missing_dates(df)
print(missing_dates)
# convert EUR base to USD
def change_base_to_USD(row):
""" to be used with the dataframe.apply() method. """
if row['base'] == 'USD':
# row['changed_base'] = False
pass
else:
# row['changed_base'] = True
num = row['USD']
row['base'] = 'USD'
row['USD'] = row['USD'] / num
row['EUR'] = row['EUR'] / num
row['JPY'] = row['JPY'] / num
row['GBP'] = row['GBP'] / num
row['CHF'] = row['CHF'] / num
return row
df = df.apply(change_base_to_USD, axis=1)
df.head(20)
# remove extraneous data
df = df.drop(df.index[[2163, 2164]])
# view data
df
###Output
_____no_output_____
###Markdown
Graph the DataGraph of the value of the USD relative to other currencies over time:
###Code
# plot the data
# plt.plot(df['date'].tolist(), df['EUR'].tolist())
df.plot(x='date', y='EUR')
df.plot(x='date', y='JPY', c='orange')
df.plot(x='date', y='GBP', c='green')
df.plot(x='date', y='CHF', c='red')
###Output
_____no_output_____
###Markdown
Final Steps of Data PreparationBefore we use this dataset for feature engineering and model testing, there are still a few things left to do:- eliminate unnecessary information
###Code
# drop the source column
df = df.drop(columns=['source'])
# view the data
df
# export data as csv so that we can create features and train mahine learning models
df.to_csv('sorted_historical_forex_rates.csv', index=False)
###Output
_____no_output_____ |
Additional.ipynb | ###Markdown
Communication
###Code
from ipaddress import IPv4Address
from pyairmore.request import AirmoreSession
from pyairmore.services.messaging import MessagingService
c = "192.168.0.108"
ip = IPv4Address(c)
s = AirmoreSession(ip)
print("Running:", s.is_server_running)
wa = s.request_authorization()
print("Authorization:",wa)
service = MessagingService(s)
###Output
Running: True
Authorization: True
###Markdown
Importing Libraries
###Code
import numpy
import numpy as npy
import matplotlib.pyplot as plt
import os
import time
import cv2
import tensorflow as tf
import random
import PIL
from IPython.display import display
from PIL import Image
###Output
_____no_output_____
###Markdown
Confirmation
###Code
model = tf.keras.models.load_model('Dataset/Allen3.h5')
def prepare(filepath,j):
y2=0
global ld
global model
IMG_SIZE = 224
img_array = cv2.imread(filepath)
new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE))
x=model.predict(new_array.reshape(-1,IMG_SIZE, IMG_SIZE, 3))
if x == 1:
ct=time.time()
if (ct-ld)>0.5:
# plt.imshow(img_array, cmap='gray')
# plt.show() --- Matplotlib altering colours. Why ?
cv2.imwrite("test/final/f{}.jpg".format(j),img_array)
ld=ct
y2=1
return y2
###Output
_____no_output_____
###Markdown
YOLO
###Code
def main1(n1,j):
y1 = 0
y1b = 0
n = n1
global ld # Global variable for showing last detected time
# load the COCO class labels our YOLO model was trained on - *preset
lpath = os.path.sep.join(['yolo-coco', "coco.names"])
la = open(lpath).read().strip().split("\n")
# derive the paths to the YOLO weights and model configuration - *preset
weightsPath = os.path.sep.join(['yolo-coco', "yolov3.weights"])
configPath = os.path.sep.join(['yolo-coco', "yolov3.cfg"])
# load our YOLO object detector trained on COCO dataset (80 classes) - *preset
net = cv2.dnn.readNetFromDarknet(configPath, weightsPath)
# load input to get its dimensions
im = cv2.imread(n)
(H, W) = im.shape[:2]
# Colour for the labels
npy.random.seed(42)
colours = npy.random.randint(0, 255, size=(len(la), 3),dtype="uint8")
# Naming layers - *preset
ln = net.getLayerNames()
ln = [ln[i[0] - 1] for i in net.getUnconnectedOutLayers()]
# construct a blob from the input image and then perform a forward - *preset
# pass of the YOLO object detector, giving us our bounding boxes and associated probabilities
blob = cv2.dnn.blobFromImage(im, 1 / 255.0, (416, 416),swapRB=True, crop=False)
net.setInput(blob)
start = time.time()
out = net.forward(ln)
end = time.time()
box1 = []
classID1 = []
confidence1 = []
for o in out:
for det in o:
s1 = det[5:]
classID = npy.argmax(s1)
confidence = s1[classID]
if confidence > 0.5:
box = det[0:4] * npy.array([W, H, W, H])
(cX, cY, w1, h1) = box.astype("int")
x = int(cX - (w1 / 2))
y = int(cY - (h1 / 2))
box1.append([x, y, int(w1), int(h1)])
confidence1.append(float(confidence))
classID1.append(classID)
# apply non-maxima suppression to suppress weak, overlapping bounding - *preset
id1 = cv2.dnn.NMSBoxes(box1, confidence1, 0.5, 0.3)
if len(id1) > 0:
for i in id1.flatten():
temp = []
(x, y) = (box1[i][0], box1[i][1])
(w, h) = (box1[i][2], box1[i][3])
cl = [int(c) for c in colours[classID1[i]]]
text = "{}".format(la[classID1[i]])
if text == "truck":
area=w*h
cv2.rectangle(im, (x-2, y-2), (x + w + 2, y + h + 2), cl, 2)
cv2.putText(im, str(i)+", "+str(x)+" "+(str(y)), (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX,0.5, cl, 2)
cv2.imwrite("test/detected/d{}.jpg".format(j),im)
if area>100:
im_refined = cv2.imread("test/detected/d{}.jpg".format(j))
crop = im_refined[int(y):int(y+h),int(x):int(x+w)]
cv2.imwrite("test/crops/c{}_{}.jpg".format(j,i),crop)
y1b = prepare("test/crops/c{}_{}.jpg".format(j,i),j)
if y1b==1:
y1=1
return y1
###Output
_____no_output_____
###Markdown
Main module
###Code
def call(given):
y0=0
yes=0
vid1 = "Demo/Geo/demo ({}).mp4".format(given)
frames = 60
# cv2.VideoCapture(0) - If you want webcam
cap = cv2.VideoCapture(vid1)
i,j,ld = 0,0,0
while True:
r, f = cap.read()
if r:
cv2.imshow('Test Video', f)
f = cv2.resize(f,(400,300))
if i%frames == 0:
try:
j = j+1
s = "test/overall/ss{}.jpg".format(j)
cv2.imwrite(s,f)
y0 = main1(s,j)
if y0==1:
yes=1
except:
pass
i=i+1
if cv2.waitKey(1) & 0xFF == ord('q'):
# Press Q to quit
break
else:
break
cap.release()
cv2.destroyAllWindows()
return yes
###Output
_____no_output_____
###Markdown
Plotting
###Code
def person(points1,p1,p2):
initial1 = p1
initial2 = p2
if (p1,p2) in [(1,5),(5,5),(5,1),(1,1)]:
l = [1,4,6]
random.shuffle(l)
for i in range(3):
c = call(l[i])
if c==1:
if i==0:
if p1==1:
p1+=1
else:
p1-=1
if i==1:
if p1==1:
p1+=1
if p2==1:
p2-=1
else:
p2+=1
else:
p1-=1
if p2==1:
p2-=1
else:
p2+=1
if i==2:
if p2==5:
p2-=1
else:
p2+=1
break
else:
l = [1,2,3,4,5,6,7,8]
random.shuffle(l)
for i in range(8):
c = call(l[i])
if c==1:
if i==0:
p2=p2+1
if i==1:
p1+=1
p2+=1
if i==2:
p1+=1
if i==3:
p1+=1
p2-=1
if i==4:
p2-=1
if i==5:
p1-=1
p2-=1
if i==6:
p1-=1
if i==7:
p2+=1
p1-=1
break
if (p1,p2) in points1:
return person(points1,initial1,initial2)
elif p1 not in range(1,6) or p2 not in range(1,6):
return person(points1, initial1, initial2)
else:
points1.append((p1,p2))
print(points1)
message = "Ambulance found at "+str(p1)+","+str(p2)
# service.send_message("9591136337", message)
print(message)
return points1
###Output
_____no_output_____
###Markdown
Display
###Code
points = []
points1 = [(1,5)]
for i in range(5):
points1 = person(points1,points1[-1][0],points1[-1][1])
for k in range(1,6):
for l in range(1,6):
if (k,l) not in points1:
points.append((k,l))
x = list(map(lambda x: x[0], points))
y = list(map(lambda x: x[1], points))
x1 = list(map(lambda x1: x1[0], points1))
y1 = list(map(lambda x1: x1[1], points1))
plt.xticks(npy.arange(1, 6, 1))
plt.yticks(npy.arange(1, 6, 1))
plt.scatter(x,y,c="r")
plt.scatter(x1,y1,c="g")
plt.grid(True)
plt.plot(x1,y1,'g--');
plt.show()
###Output
[(1, 5), (1, 4)]
Ambulance found at 1,4
|
Week 3/Day 1/Tugas Hari 1 Pekan 3.ipynb | ###Markdown
Soal 1: Pemahaman Component Matplotlib- Jelaskan apa itu Figure- Jelaskan apa itu Axis jawab:- Figure adalah window atau page atau halaman dalam objek visual. kalau kita ngegambar di kertas, maka kertas tersebutlah yang di namakan figure.- Axis adalah suatu area di dalam figure dimana data akan di plot. di dalam Axis juga terdapat berbagai macam komponen lagi seperti x-axis, y-axis, dan lain sebagainya. Soal 2: Membuat Component Figure dan Axis- Buatlah Figure dan Axis kosong tanpa Data- Plot data di bawah ini dengan 2 cara, yaitu dengan membuat figure dan axis secara explicit dan Implicit
###Code
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0, 20, 100)
y = np.cos(x/2)
# Figure dan Axis kosong tanpa Data
fig = plt.figure()
ax = fig.add_subplot()
plt.show()
###Output
_____no_output_____
###Markdown
Exected Output:
###Code
# figure dan axis secara explicit
fig = plt.figure()
ax = fig.add_subplot()
ax.plot(x,y)
# figure dan axis secara implisit
fig = plt.figure()
plt.plot(x,y)
###Output
_____no_output_____
###Markdown
Expected Output: Soal 3: Memasukan multiple data ke dalam satu axis- Plot ketiga data berikut ke dalam satu axis, dan gunakan seaborn style- save data tersebut dengan nama file bebas (apa saja) dan tampilkan kembali gambar tersebut.
###Code
x = np.linspace(0, 20, 100)
y = np.cos(x/2)
y2 = np.sin(x)
y3 = np.sin(2*x)
from IPython.display import Image
plt.style.use('seaborn')
fig, ax = plt.subplots()
ax.plot(x,y,x,y2,x,y3)
fig.savefig('soal3.png')
###Output
_____no_output_____ |
tutorial/EEGlab_Notebook.ipynb | ###Markdown
Load useful libs Data science
###Code
import numpy as np
###Output
_____no_output_____
###Markdown
MNE
###Code
import mne
###Output
_____no_output_____
###Markdown
HyPyP Load dataLoading datasetsFor each participant, both .set file and .fdt files should be in the same directory.In this notebook, we use data that is preprocessed in EEGlab: data should be epoched.Note: it is not necessary that participants have the same number of epochs, but they must have same number of samples per epoch
###Code
path_1 = "EEGLAB/eeglab_data_epochs_ica.set"
path_2 = "EEGLAB/eeglab_data_epochs_ica.set"
epo1 = mne.io.read_epochs_eeglab(
path_1
)
epo2 = mne.io.read_epochs_eeglab(
path_2
)
###Output
_____no_output_____
###Markdown
We need to equalize the number of epochs between our two participants.
###Code
mne.epochs.equalize_epoch_counts([epo1, epo2])
###Output
Dropped 0 epochs:
Dropped 0 epochs:
###Markdown
Choosing sensors in international standard 10/20 system for using the MNE template and overwrite the EEGlab position.Note: EOG (Eyes) are removed for this analysis
###Code
StanSys = ['Nz', 'Fp1', 'Fpz', 'Fp2', 'F7', 'F9', 'PO3',
'F3', 'Fz', 'F4', 'F8', 'T3', 'C3', 'CP3', 'PO4',
'Cz', 'C4', 'T4', 'T5', 'P3', 'Pz', 'P3', 'PO7',
'P4', 'T6', 'O1', 'Oz', 'O2', 'Iz', 'P1', 'PO8',
'AF3', 'AF7', 'AF4', 'AF8', 'F6', 'F10', 'F2', 'F5',
'FC1', 'FC3', 'FC5', 'FCz', 'FC2', 'FC4', 'FC6', 'F1',
'FT9', 'FT7', 'FT8', 'FT10', 'C5', 'C6', 'CPz', 'CP1',
'CP5', 'CP2', 'CP4', 'CP6', 'TP8', 'TP10', 'TP7', 'TP9',
'P5', 'P7', 'P9', 'P2', 'P4', 'P6', 'P8', 'P10', 'POz']
low_StanSys = []
for name in StanSys:
low_StanSys.append(name.lower())
names_epo1 = np.array([ch['ch_name'] for ch in epo1.info['chs']])
names_epo2 = np.array([ch['ch_name'] for ch in epo2.info['chs']])
epo_ref1 = epo1.copy()
for idx in range(len(names_epo1)):
aux_name = names_epo1[idx].lower()
if aux_name in low_StanSys:
ind = low_StanSys.index(aux_name)
nw_ch = StanSys[ind]
mne.rename_channels(epo_ref1.info, {names_epo1[idx]:nw_ch})
else:
epo_ref1.drop_channels(names_epo1[idx])
epo_ref2 = epo2.copy()
for idx in range(len(names_epo2)):
aux_name = names_epo2[idx].lower()
if aux_name in low_StanSys:
ind = low_StanSys.index(aux_name)
nw_ch = StanSys[ind]
mne.rename_channels(epo_ref2.info, {names_epo2[idx]:nw_ch})
else:
epo_ref2.drop_channels(names_epo2[idx])
locations = mne.channels.make_standard_montage('standard_1020', head_size=0.092)
epo_ref2.set_montage(locations)
epo_ref1.set_montage(locations)
###Output
_____no_output_____ |
Lec_2_Postulados/Lec_2_Postulados.ipynb | ###Markdown
Lección 2: Los postulados de la mecánica cuántica La mecánica cuántica es el marco teórico en el que los científicos trabajan el desarrollo de teorías físicas relacionadas con el mundo microscópico. Este marco de trabajo matemático, por si solo, no indica las leyes que un sistema debería cumplir, sin embargo, ofrece el panorama de cómo este sistema puede cambiar.Los postulados de la mecánica cuántica son aquellos que establecen la relación entre el mundo físico y el formalismo matemático de la mecánica cuántica. Es importante tener en cuenta que el desarrollo de estos postulados se dio a traves del ensayo y el error, de forma tal que estos parecen partir de motivaciones no muy claras, sin embargo, nuestro objetivo en esta sesión es aprender el cómo aplicarlos y cuándo hacerlo.**SUPER IMPORTANTE:** En este ejemplo intentaremos presentar al lector el formalismo necesario para estudiar la computación cuántica en forma teórica, así como una posible intuición física sobre la misma. Esta sesióne stá disponible en nuestro servidor de MyBinder. Primero importaremos alguna librerías que son necesarias para desarrollar nuestro experimento
###Code
from qiskit import QuantumRegister, ClassicalRegister
from qiskit import QuantumCircuit, execute, Aer
from qiskit.circuit import Parameter
from qiskit.visualization import plot_histogram,state_visualization
from qiskit.quantum_info.operators import Operator
import matplotlib.pyplot as plt
import numpy as np
pi=np.pi
###Output
_____no_output_____
###Markdown
Ahora definimos una función con un parametro $\phi$ que nos servirá para hacer una evolución temporal en una simulación de un interferómetro de Mach-Zehnder.
###Code
def MZ_interferometer(phi):
## La variable phi esta relacionada al cambio de fase en uno de los dos caminos
MZ_circuit=QuantumCircuit(1)
## Se define una compuerta de Hadamard la cual cumple la función de beam splitter
MZ_circuit.h(0)
## Luego se hace una diferencia de camino a traves del uno de los caminos del campo,
## En este caso el que esta en el estado que llamamos |1>
MZ_circuit.p(phi,0)
## finalmente ponemos el siguiente BS para terminar con el interferómetro
MZ_circuit.h(0)
MZ_gate=MZ_circuit.to_gate()
MZ_gate.name = "MZ-Interferometer"
return MZ_gate
###Output
_____no_output_____
###Markdown
Postulado 1 El primer postulado de la mecánica cuántica nos indica el espacio matemático en el que, dado un sistema, se trabaja el formalismo de la mecánica cuántica.Éste dicta que:>Dado un sistema físico aislado hay un espacio vectorial complejo con un producto interno definido (un espacio de Hilbert) conocido como ***espacio de estados*** del sistema. El sistema en este espacio se representa a partir de un ***vector de estado***, el cual es unitario en este espacio, es decir.$$|\psi\rangle = \sum_k c_k|k\rangle \hspace{2em} \text{donde} \hspace{2em} \langle\psi|\psi\rangle = \sum_k |c_k|^2 = 1.$$La notación que se utiliza en la mecánica cuántica para escribir estos estados se conoce como la notación bra-ket de Dirac. En esta notación el estado bra se escribe, $\langle \psi |$ y su correspondiente ket es $|\psi\rangle$.En el caso de la computación cuántica nosotros vamos a estar interesados en un espacio de estados particular, un espacio de en el que el sistema tiene dos estados bien definidos $|0\rangle$ y $|1\rangle$, este espacio de estados lo llamaremos el espacio de qubit. En este caso los estados $|0\rangle$ y $|1\rangle$ son la base de nuestro espacio vectorial, y dado que estos se definen ortonormales, podemos representarlos en una forma vectorial$$|0\rangle = \begin{bmatrix} 1 \\ 0 \end{bmatrix} \hspace{2em} \text{y} \hspace{2em} |1\rangle = \begin{bmatrix} 0 \\ 1 \end{bmatrix}$$Por lo tanto, el ket asociado a un estado arbitrario $|\psi\rangle$ se puede representar de la forma$$ |\psi\rangle = \alpha|0\rangle + \beta|1\rangle = \begin{bmatrix} \alpha \\ \beta \end{bmatrix} $$Los coeficientes $\alpha$ y $\beta$ representan las amplitudes de los estados $|0\rangle$ y $|1\rangle$ respectivamente. Estos números Estan relacionados con las *probabilidades* de encontrar el sistema, en este caso el qubit, en un estado o el otro. Más en detalle, las probabilidades de encontrar el qubit $|\psi\rangle$ en el estado $|0\rangle$ o $|1\rangle$ después de realizar la medición son$$p(|0\rangle) = |\alpha|^2 \hspace{2em}\text{y}\hspace{2em} p(|1\rangle) = |\beta|^2$$Antes de continuar hagamos un pequeño experimento.Preparemos un estado de una forma partícular, en concreto vamos a prepararlo en el estado$$|\psi\rangle = \frac{1}{\sqrt{2}}\left(|0\rangle + |1\rangle\right) $$
###Code
## Inicializamos los registros necesarios
qr=QuantumRegister(1)
cr=ClassicalRegister(1)
qc=QuantumCircuit(qr,cr)
## Aplicamos una compuerta de Hadamard
qc.h(qr[0])
qc.measure(qr[0],cr[0])
qc.draw(output='mpl')
###Output
_____no_output_____
###Markdown
De acuerdo con lo que vimos anteriormente entonces $\alpha = \beta = \frac{1}{\sqrt{2}}$. Por lo tanto, las probabilidades de que el qubit esté en los estados $|0\rangle$ o $|1\rangle$ son $p(|0\rangle) = \frac{1}{2}$ y $p(|1\rangle) = \frac{1}{2}$ respectivamente. Ahora realizamos una medición.
###Code
## Usamos el simulador qasm
backend = Aer.get_backend('qasm_simulator')
results = execute(qc,backend,shots=10000).result().get_counts()
plot_histogram(results)
###Output
_____no_output_____
###Markdown
Lo que haremos ahora es agregar una fase de la forma $e^{i\phi}$ en la amplitud del estado $|1\rangle$. Por lo cual el estado toma la forma$$|\psi\rangle = \frac{1}{\sqrt{2}}\left(|0\rangle + i|1\rangle\right) .$$
###Code
qr=QuantumRegister(1)
cr=ClassicalRegister(1)
qc=QuantumCircuit(qr,cr)
qc.h(qr[0])
qc.p(pi/2,qr[0])
qc.measure(qr[0],cr[0])
qc.draw(output='mpl')
###Output
_____no_output_____
###Markdown
Midiendo nuevamente tenemos.
###Code
backend = Aer.get_backend('qasm_simulator')
results = execute(qc,backend,shots=10000).result().get_counts()
plot_histogram(results)
###Output
_____no_output_____
###Markdown
Es decir que, así se añadiera un factor de fase las distribuciones de probabilidad luego de medir son iguales, por lo tanto, los números $\alpha$ y $\beta$ tienen que ser números de la forma $\alpha = |\alpha|e^{i\theta_\alpha}$ y $\beta = |\beta|e^{i\theta_\beta}$, es decir, estos números pertenecen a $\mathbb{C}$. Con base a este resultado, podemos escribir apropiadamente el bra asociado al estado $|\psi\rangle$. Este es$$\langle \psi | = \alpha^* \langle 0 | + \beta^*\langle 1 | = \begin{bmatrix}\alpha^* ,\beta^*\end{bmatrix} $$Estos estados cumplen con las relaciones$$\langle 0|0 \rangle =\begin{bmatrix}1 ,0\end{bmatrix}\begin{bmatrix}1 \\0\end{bmatrix} = 1$$$$\langle 1|1\rangle = \begin{bmatrix}0 ,1\end{bmatrix}\begin{bmatrix}0 \\1\end{bmatrix} = 1$$$$\langle 0|1\rangle = \begin{bmatrix}1 ,0\end{bmatrix}\begin{bmatrix}0 \\1\end{bmatrix} = 0$$$$\langle 1|0\rangle = \begin{bmatrix}0 ,1\end{bmatrix}\begin{bmatrix}1 \\0\end{bmatrix} = 0$$Por lo cual el Bra-Ket del estado $|\psi\rangle$, el cual representa el producto punto en el espacio de estados, se escribe:$$\langle\psi|\psi\rangle = \left( \alpha^* \langle 0 | + \beta^*\langle 1 | \right) \left(\alpha|0\rangle + \beta|1\rangle\right)$$$$ \langle\psi|\psi\rangle =|\alpha|^2 + |\beta|^2 = 1 $$O vectorialmente$$\langle\psi|\psi\rangle = \begin{bmatrix}\alpha^* ,\beta^*\end{bmatrix}\begin{bmatrix}\alpha \\\beta\end{bmatrix} = |\alpha|^2 + |\beta|^2 = 1$$Adicionalmente, así como definimos el Bra-ket podemos definir un Ket-Bra, que tendría la forma$$|\psi\rangle\langle\psi| = \begin{bmatrix}\alpha\alpha^*&\alpha\beta^*\\\beta\alpha^*&\beta\beta^*\end{bmatrix}$$Este tipo de producto, que es similar al producto tensorial, se conoce en este contexto como el producto de Kronecker.Dado que los números $\alpha$ y $\beta$ son complejos entonces un sistema de dos estados, como es el caso de un qubit, puede representarse sobre la superficie de una esfera de radio $1$, esta esfera se conoce como la *Esfera de Bloch*. Postulado 2 >La evolución temporal de un sistema cuántico ***cerrado*** se describe a traves de una ***transformación unitaria***. esto implica que si en un tiempo $t_{1}$ el sistema se encuentra en el estado $|\psi\rangle$. Luego, en un instante $t_2$ el sistema estará en el estado $|\psi '\rangle$. Esta evolución se da por un operador unitario $U(t_1,t_2)$, que solo depende de los dos tiempos ya mencionados. Esta evolución se puede escribir como$$ |\psi'\rangle = U |\psi\rangle. $$Así mismo, teniendo en mente el operador Hamiltoniano de un sistema cerrado, se puede escribir la evolución temporal de este a traves de la ecuación de Schrödinger, $$ i\hbar \frac{d|\psi\rangle}{dt} = \mathcal{H} |\psi\rangle $$Como hemos visto, así como los estados tienen una representación vectorial, los operadores que actuan sobre los estados se pueden representar matricialmente para que modifiquen estos estados. En el caso de la computación cuántica cada una de las compuertas que se usan tiene una representación matricial. El primer operador que veremos es el operador identidad $\mathbb{1}$. Este operador no modifica el estado de ninguna forma, y se puede representar matricialmente como$$\mathbb{1} =\begin{bmatrix}1 & 0 \\ 0 & 1\end{bmatrix} $$ Otra transformación se representa mediante el símbolo $X$, esta transformación lo que hace es intercambiar los elementos de la base, es decir$$\begin{equation}X|0\rangle\rightarrow|1\rangle, \hspace{2em}X|1\rangle\rightarrow|0\rangle\end{equation}$$Matricialmente se puede representar como$$\begin{equation}X=\begin{bmatrix}0 & 1 \\ 1 & 0\end{bmatrix}\end{equation}$$Esta transformación se llama phase-flip y se puede representar mediante el operador $Z$. esta cambia la fase relativa entre los estados $|0\rangle$ y $|1\rangle$ en un factor de $\pi$, es decir$$\begin{equation}Z|0\rangle\rightarrow|0\rangle, \hspace{2em} Z|1\rangle\rightarrow -|1\rangle\end{equation} $$Matricialmente se representa por$$\begin{equation}Z=\begin{bmatrix}1 & 0 \\ 0 & -1\end{bmatrix} \end{equation}$$Los operadores $X$ y $Z$ son dos de los conocidos operadores de Pauli, Estos se representan por las llamadas matrices de Pauli. Adicionalmente hay otra transformación que viene de la combinación entre $X$ y $Z$ de la forma $ZX$, esta actúa sobre el estado de forma tal que $$\begin{equation}ZX|0\rangle\rightarrow-|1\rangle, \hspace{2em} ZX|1\rangle\rightarrow |0\rangle.\end{equation} $$Se puede representar matricialmente de la forma$$\begin{equation}ZX=\begin{bmatrix}0 & 1 \\ -1 & 0\end{bmatrix} = iY\end{equation}$$Con $Y$ La tercera matriz de Pauli. Esta tiene la forma$$\begin{equation}Y=\begin{bmatrix}0 & -i \\ i & 0\end{bmatrix}\end{equation}$$En este punto es importante definir la operación $^\dagger$ que se realiza sobre un operador. Esta operación implica tomar el operador transpuesto y complejo conjugado, por ejemplo para el operador $Y$ tenemos$$\begin{equation}Y=\begin{bmatrix}0 & -i \\ i & 0\end{bmatrix}\Rightarrow Y^\dagger=\begin{bmatrix}0 & i \\ -i & 0\end{bmatrix}^* = \begin{bmatrix}0 & -i \\ i & 0\end{bmatrix}\end{equation}$$Como vimos, $Y = Y^\dagger$, esta es una propiedad llamada *Hermiticidad*. Cuando un operador en mecánica cuántica es hermítico, entonces es posible medir los observables asociados a ese operador.Además de los operadores de Pauli hay otro par de operadores que son importantes para futuros desarrollos. El primero es el operador de Hadamard, el cual tiene la forma$$H =\frac{1}{\sqrt{2}} \begin{bmatrix}1 & 1\\1 & -1 \end{bmatrix}$$Esta compuerta lo que hace es rotar los estados en un ángulo de 45°. Es decir$$|0\rangle\rightarrow \frac{1}{\sqrt{2}}\left(|0\rangle + |1\rangle\right)\hspace{2em} \text{y}\hspace{2em}|1\rangle \rightarrow \frac{1}{\sqrt{2}} \left(|0\rangle - |1\rangle\right)$$Un ultimo operador que nos sirve en este momento es el cambio de fase. Este operador lo que hace es añadir una fase cuando el sistema se encuentra en el estado $|1\rangle$. Matricialmente se puede representar como $$P_\phi =\begin{bmatrix}1 & 0\\0 & e^{i\phi} \end{bmatrix}$$Para ilustrar este principio lo que haremos será simular un interferómetro de Mach-Zehnder como el que se muestra en la siquiente figura.En este caso, solo se envía un fotón por la entrada que representa el estado $|0\rangle$. El estado inicial se puede representar de la forma$$ |\psi_i\rangle = |0\rangle$$.En esta figura se tiene queAhora debemos representar este interferómetro mediante un circuito cuántico y encontrar la probabilidad con la que alguno de los medidores va a detectar el fotón, es decir, determinar la probabilidad de que esté en el estado $|0\rangle$ o $|1\rangle$.Para esto se tiene el haz que ingresa. Luego, este pasa por un divisor de haz, este divisor de haz lo que hace es dar al fotón la posibilidad de seguir su camino (camino $|0\rangle$) o ser reflejado (camino $|1\rangle$) con probabilidad de 50\%. Esto se puede representar mediante una compuerta de Hadamard $H$. Luego de esto, el fotón puede o no ser desfasado, la condición de que el desfasador $\phi$ actue depende de si el fotón va o no por el camino $|1\rangle$. Este desfasador se puede representar por la compuerta de fase $P_\phi$. Finalmente, sin importar el camino, el haz pasa nuevamente por un divisor de haz, es decir, una nueva compuerta Hadamard. Por lo cual el interferómetro se podría visualizar de la siguiente forma
###Code
## Primero definiremos el fotón que unicia por el camino que definimos como el estado inicial $|0>$
qr=QuantumRegister(1)
cr=ClassicalRegister(1)
qc=QuantumCircuit(qr,cr)
## definimos el parametro
phi=Parameter('$\phi$')
## Definimos el espaciamiento deseado
angulos = np.linspace(0,2*pi,100)
## Aplicamos el interferómetro de MZ a nuestro estado inicial
MZ_I = MZ_interferometer(phi)
qc.append(MZ_I,[0])
qc.measure(qr[0],cr[0])
qc.decompose().draw(output='mpl')
###Output
_____no_output_____
###Markdown
Luego de pasar por el interferómetro, el estado final toma la forma$$|\psi_f\rangle = \cos\frac{\phi}{2}|0\rangle - i\sin\frac{\phi}{2} |1\rangle$$Por lo tanto, las probabilidades de medir el estado $|0\rangle$, es decir, que se haga una detección en el detector $D_4$ y de medir $|1\rangle$, es decir, hacer una detección en el detector $D_5$ son:$$P_0 = \cos^2 \frac{\phi}{2} \hspace{2em} \text{y}\hspace{2em} P_1 = \sin^2 \frac{\phi}{2}$$De acá se ve claramente que $$ P_0 + P_1 = \cos^2 \frac{\phi}{2} +\sin^2 \frac{\phi}{2} = 1 $$
###Code
shots=1024
backend = Aer.get_backend('qasm_simulator')
resultados = execute(qc,backend,parameter_binds=[{phi:angulo}for angulo in angulos],shots=shots).result().get_counts()
## Capturamos la probabilidad de en el medidor 1
P_0 = np.array([resultado.get('0',0)/shots for resultado in resultados])
## Capturamos la probabilidad de en el medidor 2
P_1 = np.array([resultado.get('1',0)/shots for resultado in resultados])
## Graficamos
plt.title(r'Probabilidad de medición por detector en el interferometro Mach-Zehnder')
plt.xlabel(r'$\phi$ (radianes)')
plt.ylabel(r'$Probabilidades$')
plt.plot(angulos,P_0,label='P_0',color='k')
plt.plot(angulos,P_1,label='P_1',color='r')
plt.plot(angulos,P_0 + P_1,label='P_0 + P_1',color='b')
plt.legend(bbox_to_anchor = (1, 1))
plt.show()
###Output
_____no_output_____
###Markdown
Postulado 3 >Las mediciones a un sistema cuántico se describen a traves de una colección ${M_{m}}$ de ***operadores de medición***. Estos operadores actuan sobre el es estacio de estados del sistema. El indice $m$ se refiere a las posibles mediciones que pueden resultar en el experimento. Es decir, si un sistema se encuentra en el estado $|\psi>$ justo antes de la medición, la probabilidad de que se de el resultado $m$ es$$p(m) = \langle\psi|M_m^{\dagger}M_m|\psi\rangle.$$Luego de la medición el estado del sistema colapsa al estado$$\frac{M_m |\psi\rangle}{\sqrt{\langle\psi|M_m^{\dagger}M_m|\psi\rangle}}.$$Es importante tener en cuenta que los operadores de medición satisfacen la relación de completez$$\sum_m M_m^{\dagger}M_m = I .$$Esta relación de completez muestra también el hecho de que la suma de las probabilidades de que el sistema este en el estado $m$ sea uno:$$\sum_m p(m) = \sum_m \langle\psi|M_m^{\dagger}M_m|\psi\rangle = 1$$En el caso de un qubit, tenemos dos operadores de medición, el que mide el estado $|0\rangle$ que llamamos $M_0$ y el que mide el estado $|1\rangle$ que llamamos $M_1$. Se representan de la forma$$M_0= |0\rangle\langle 0| = \begin{bmatrix}1 & 0 \\ 0 & 0\end{bmatrix} \hspace{2em} \text{y} \hspace{2em} M_1= |1\rangle\langle 1| = \begin{bmatrix}0 & 0 \\ 0 & 1\end{bmatrix} $$Entonces, por ejemplo, tomemos el estado final presentado en el caso del interferómetro de Mach-Zehnder$$|\psi\rangle = \cos\frac{\phi}{2}|0\rangle - i\sin\frac{\phi}{2} |1\rangle$$Primero supongamos que al realizar la medición el estado resulta ser $|0\rangle$, entonces el estado luego de la medición es$$|\psi\rangle \rightarrow \frac{M_0 |\psi\rangle}{\sqrt{\langle\psi|M_0^{\dagger}M_0|\psi\rangle}}$$$$= \frac{\cos\frac{\phi}{2} |0\rangle}{\sqrt{\cos^2\frac{\phi}{2}}} = |0\rangle$$De igual forma, suponiendo que al medir el estado colapsó al estado $|1\rangle$, se tiene $$|\psi\rangle \rightarrow \frac{M_1 |\psi\rangle}{\sqrt{\langle\psi|M_1^{\dagger}M_1|\psi\rangle}}$$$$= \frac{\sin\frac{\phi}{2} |1\rangle}{\sqrt{\sin^2\frac{\phi}{2}}} = |1\rangle$$ Postulado 4 >El espacio de los estados de un sistema físico compuesto es el producto tensorial entre los espacios de estados de los componentes de este sistema compuesto. Esto quiere decir que, si tenemos $1,2,...,n$ sistemas que se encuentran en los estados $|\psi_1>,|\psi_2>,...,|\psi_n>$ respectivamente, entonces, la decripción de el sistema físico compuesto $|\Psi>$ sería$$|\Psi> = |\psi_1>\otimes |\psi_2> \otimes ... \otimes |\psi_n>$$Para ilustrar este postulado, vamos a pensar en dos sistemas de 1 qubit los cuales vamos a nombrar $|\psi_1\rangle$ y $|\psi_2\rangle$ por lo cual el sistema completo se puede ver de la forma $|\Psi\rangle = |\psi_1\rangle \otimes |\psi_2\rangle$. Una base para expandir estos estados es la de {$|0\rangle$, $|1\rangle$}, esta base para cada uno de los qubits, entonces, el estado total se puede expandir en la base:$$ \{|0\rangle,|1\rangle\} \otimes \{|0\rangle,|1\rangle\} = \{|0\rangle\otimes |0\rangle, |0\rangle\otimes |1\rangle, |1\rangle\otimes |0\rangle, |1\rangle\otimes |1\rangle\} $$Usando la notación $|0\rangle\otimes |0\rangle = |0 0\rangle$ y así para los otros sistemas, donde el primer y segundo número corresponden a los sistemas $|\psi_1\rangle$ y $|\psi_2\rangle$ respectivamente. Este producto se puede visualizar vectorialmente de la forma$$|0 0\rangle = |0\rangle\otimes |0\rangle = \begin{bmatrix}1\\0\end{bmatrix}\otimes\begin{bmatrix}1\\0\end{bmatrix} = \begin{bmatrix}1\begin{bmatrix}1\\0\end{bmatrix}\\0\begin{bmatrix}1\\0\end{bmatrix}\end{bmatrix} = \begin{bmatrix}1\\0\\0\\0\end{bmatrix}$$Realizando los otros productos de la base se puede llegar a $$ |0 0\rangle = \begin{bmatrix}1\\0\\0\\0\end{bmatrix},\hspace{1em}|0 1\rangle = \begin{bmatrix}0\\1\\0\\0\end{bmatrix},\hspace{1em}|1 0\rangle = \begin{bmatrix}0\\0\\1\\0\end{bmatrix},\hspace{1em}|1 1\rangle = \begin{bmatrix}0\\0\\0\\1\end{bmatrix}.$$Sin embargo, como bien sabemos, hay infinitos conjuntos de vectores que pueden ser la base del espacio en el que estamos trabajando, del mismo modo, hay diferentes estados de dos partículas que pueden funcionar como base para el espacio de Hilbert en el que los posibles estados de estas partículas reciden. Una base de interes para la computación cuántica es la conocida *Base de Bell*. La base de Bell para dos qubits representa los posibles estados *entrelazados* que pueden haber entre ellas. Los 4 elementos de la base de Bell para 2 qubits son$$|\Psi^+\rangle_{1,2} = \frac{1}{\sqrt{2}}\left(|01 \rangle + |10\rangle\right)$$$$|\Psi^-\rangle_{1,2} = \frac{1}{\sqrt{2}}\left(|01 \rangle - |10\rangle\right)$$$$|\Phi^+\rangle_{1,2} = \frac{1}{\sqrt{2}}\left(|00 \rangle + |11 \rangle\right)$$$$|\Phi^-\rangle_{1,2} = \frac{1}{\sqrt{2}}\left(|00 \rangle - |11 \rangle\right)$$Como pueden notar, NO es posible expresar alguno de los anteriores estados de la forma $|\psi\rangle_1 \otimes |\psi\rangle_1$, es decir, no se puede expresar como el producto de estados de las partículas singulares. Este tipo de estados es único de la mecánica cuántica, y son estados en los que, una vez se haga la medición de una de las dos partículas, o uno de los dos qubits, el estado del segundo quedará totalmente determinado por el resultado de la medición hecha en el primer qubit.Ahora vamos a cunstruir estos estados, para esto tenemos el siguiente cuadro|Estado inicial $|ij\rangle$|$\left(H_1 \otimes I_2\right)$|$|\Psi\rangle_{i,j}$||:------------:|:---------------:|:--------------:||$ |00 \rangle$|$\frac{1}{\sqrt{2}}\left(|00 \rangle + |10\rangle\right)$|$|\Phi^+\rangle_{1,2}$||$ |01 \rangle$|$\frac{1}{\sqrt{2}}\left(|01 \rangle + |11\rangle\right)$|$|\Psi^+\rangle_{1,2}$||$ |10 \rangle$|$\frac{1}{\sqrt{2}}\left(|00 \rangle - |10\rangle\right)$|$|\Phi^-\rangle_{1,2}$||$ |11 \rangle$|$\frac{1}{\sqrt{2}}\left(|01 \rangle - |11\rangle\right)$|$|\Psi^-\rangle_{1,2}$|$$\hspace{2em}\overset{\text{Hadamard sobre } q_1}{\longrightarrow}\hspace{2em}\overset{\text{CNOT} q_1,q_2}{\longrightarrow}$$A continuación vamos a construir el primer estado de la base de Bell
###Code
## Iniciamos los registros necesarios
qr=QuantumRegister(2)
cr=ClassicalRegister(2)
qc=QuantumCircuit(qr,cr)
## Ahora realizamos la operación de Hadamard sobre el primer qubit de abajo hacia arriba, es decir, el qubit[1]
qc.h(qr[1])
## Ahora aplicamos la compuerta CNOT con controlada por el primer qubit, apuntando al segundo, es decir
qc.cx(qr[1],qr[0])
qc.measure(qr[0],cr[0])
qc.measure(qr[1],cr[1])
qc.draw(output='mpl')
backend = Aer.get_backend('qasm_simulator')
results = execute(qc,backend,shots=10000).result().get_counts()
plot_histogram(results)
###Output
_____no_output_____ |
finalized_code/Ridge_reg.ipynb | ###Markdown
Ridge regre y = market orientation
###Code
market_data = fun.delete_id_columns(clean) #1
market_data, pred_market = fun.drop_response_rows_with_NAs(market_data, "Market_Orientation", "PPI_Likelihood") #2
market_data = fun.replace_NAN_with_na(market_data) #3
market_data = fun.entry_to_lowercase(market_data) #4
market_data = fun.remove_underscores_spaces(market_data) #5
market_data = fun.convert_to_categorical(market_data) #6
market_data = fun.impute_data(market_data)
market_data.YEAR = market_data.YEAR.astype('category')
market_data = standarize_data(market_data)
market_data = market_data.drop("continent", axis = 1)
market_data.shape
### 1. create dummy
X_market = get_dummyXs_y(market_data, "Market_Orientation")[0]
y_market = get_dummyXs_y(market_data, "Market_Orientation")[1]
X_train_mo, X_test_mo, y_train_mo, y_test_mo = train_test_split(X_market,y_market, test_size = 0.3, random_state = 2021)
alpha_set = np.arange(150,570,2)
ridge_cv=RidgeCV(alphas=alpha_set, store_cv_values = True, fit_intercept = False)
model_cv=ridge_cv.fit(X_train_mo,y_train_mo)
model_cv.alpha_
cv_per_alpha = np.mean(model_cv.cv_values_, axis = 0)
cv_df = pd.DataFrame({'alpha': alpha_set, 'MSPE': cv_per_alpha})
sns.scatterplot(data = cv_df, x = "alpha", y = "MSPE").set_title('Figure 3: Optimal Alpha for y=Market Orientation')
plt.axvline(x=model_cv.alpha_, c="red", linestyle = "dashed", label = r'$\alpha$ = 456')
plt.legend(loc='upper right')
#plt.text(458,0.80,'a=456',rotation=90)
#refit model with alpha =3 and get score
rir = Ridge(alpha = model_cv.alpha_)
rir.fit(X_train_mo,y_train_m)
y_pred_ridge = rir.predict(X_test)
MSE_market = mean_squared_error(y_test,y_pred_ridge)
MSE_market
rir.coef_
betas = rir.coef_
max5_index = [list(abs(betas)).index(x) for x in np.sort(abs(betas))[::-1][:20]]
min5_index = [list(abs(betas)).index(x) for x in np.sort(abs(betas))[:5]]
betas[max5_index]
betas[min5_index]
X_train.columns[max5_index]
feature_imp_mo = pd.DataFrame([X_train.columns[max5_index], betas[max5_index]]).T
feature_imp_mo.columns= ["name", "beta"]
feature_imp_mo
###Output
_____no_output_____
###Markdown
predict y for market orientation y = Na
###Code
#pred_market.columns
#pred_market = pred_market.drop("continent", axis = 1)
# smallData = fun.replace_NAN_with_na(pred_market) #3
# smallData = fun.entry_to_lowercase(smallData) #4
# smallData = fun.remove_underscores_spaces(smallData) #5
# smallData = fun.convert_to_categorical(smallData) #6
# smallData = fun.impute_data(smallData)
# smallData
# smallData.columns
#smallData.dtypes
# smallData.YEAR = smallData.YEAR.astype('category')
# std_data = standarize_data(smallData)
# std_data = std_data.reset_index(drop = True)
#std_data = std_data.drop("Market_Orientation",axis = 1)
# isNA = []
# sumNA = []
# for i in std_data.columns:
# isNA.append(i)
# a = std_data[i].isna().sum()
# sumNA.append(a)
# inf = pd.DataFrame([isNA, sumNA]).T
# inf.columns = ["a","b"]
# inf
# #impute
# for i in inf[21:33].a:
# std_data[i] = std_data[i].fillna(np.nanmedian(market_data[i]))
# data_pt = std_data.iloc[[0]]
# data_pt
###Output
_____no_output_____
###Markdown
Ridge regression with y=PPI_Likelihood
###Code
clean.head(4)
ppi_data = fun.delete_id_columns(clean) #1
ppi_data, pred_market = fun.drop_response_rows_with_NAs(ppi_data,"PPI_Likelihood" ,"Market_Orientation") #2
ppi_data = fun.replace_NAN_with_na(ppi_data) #3
ppi_data = fun.entry_to_lowercase(ppi_data) #4
ppi_data = fun.remove_underscores_spaces(ppi_data) #5
ppi_data = fun.convert_to_categorical(ppi_data) #6
ppi_data = fun.impute_data(ppi_data)#7
ppi_data.head(3)
ppi_data = ppi_data.drop("Country", axis = 1)
ppi_data.YEAR = ppi_data.YEAR.astype('category')
ppi_data = standarize_data(ppi_data)
ppi_data.head()
X_ppi = get_dummyXs_y(ppi_data, "PPI_Likelihood")[0]
y_ppi = get_dummyXs_y(ppi_data, "PPI_Likelihood")[1]
X_train_ppi, X_test_ppi, y_train_ppi, y_test_ppi = train_test_split(X_ppi ,y_ppi, test_size = 0.3,
random_state = 2021)
alpha_set = np.arange(10,70,1)
ridge_cv_ppi=RidgeCV(alphas=alpha_set, store_cv_values = True, fit_intercept = False)
model_ppi_cv=ridge_cv_ppi.fit(X_train_ppi,y_train_ppi)
model_ppi_cv.alpha_
ppi_cv_per_alpha = np.mean(model_ppi_cv.cv_values_, axis = 0)
ppi_cv_df = pd.DataFrame({'alpha': alpha_set, 'MSPE': ppi_cv_per_alpha})
sns.scatterplot(data = ppi_cv_df, x = "alpha", y = "MSPE", ax=ax1).set_title('Figure 4: Optimal Alpha for y = PPI Likelihood')
plt.axvline(x=29, c="red", linestyle = "dashed",label = r'$\alpha$ = 29' )
plt.legend(loc='upper right')
# Two subplots
fig, axes = plt.subplots(1, 2, figsize=(10,5))
fig.subplots_adjust(wspace=.5)
sns.scatterplot(ax = axes[0],data = cv_df, x = "alpha", y = "MSPE")
axes[0].set_title('Figure 2: Optimal Alpha for y=Market Orientation')
axes[0].axvline(x=model_cv.alpha_, c="red", linestyle = "dashed", label = r'$\alpha$ = 456')
axes[0].legend(loc='upper right')
sns.scatterplot(ax = axes[1], data = ppi_cv_df, x = "alpha", y = "MSPE")
axes[1].set_title('Figure 3: Optimal Alpha for y = PPI Likelihood')
axes[1].axvline(x=29, c="red", linestyle = "dashed",label = r'$\alpha$ = 29' )
axes[1].legend(loc='upper right')
#refit model with alpha =3 and get score
ridge_ppi = Ridge(alpha = model_ppi_cv.alpha_)
ridge_ppi.fit(X_train_ppi,y_train_ppi)
y_pred_ridge_ppi = ridge_ppi.predict(X_test_ppi)
MSE_ppi = np.mean((y_pred_ridge_ppi-np.array(y_test_ppi))**2)
MSE_ppi
#top 20 coeff/variable that are most important by abs value
betas_ppi = ridge_ppi.coef_
max5_index_ppi = [list(abs(betas_ppi)).index(x) for x in np.sort(abs(betas_ppi))[::-1][:20]]
min5_index_ppi = [list(abs(betas_ppi)).index(x) for x in np.sort(abs(betas_ppi))[:5]]
betas_ppi[max5_index_ppi]
betas_ppi[min5_index_ppi]
X_train_ppi.columns[max5_index_ppi]
feature_imp_ppi = pd.DataFrame([X_train_ppi.columns[max5_index_ppi], betas_ppi[max5_index_ppi]]).T
feature_imp_ppi.columns = ["name", "beta"]
feature_imp_ppi
###Output
_____no_output_____
###Markdown
Model $Y=\beta_1*X_C+\beta2*X_Z+\beta3*X_size$Whem the country is cambodia, then we have $X_C = 1, X_Z=0$, the model is $Y_C=\beta_1+\beta_3*X_size$Whem the country is zimbawe, then we have $X_Z = 1, X_C=0$, the model is $Y_noC=\beta_2+\beta_3*X_size$take the difference: $Y_C-Y_noC = \beta_1-\beta_2$if b1 =3 , b2 = 5 ppi would decrease by 2 units, comparing ppi of C to Z, the avg ppi decreases by 2 units, holding all other variables constant.
###Code
all_together = pd.concat([feature_imp_ppi, feature_imp_mo],axis = 1)
all_together
###Output
_____no_output_____ |
courses/machine_learning/deepdive2/introduction_to_tensorflow/solutions/what_if_mortgage.ipynb | ###Markdown
LABXX: What-if Tool: Model Interpretability Using Mortgage Data **Learning Objectives**1. Create a What-if Tool visualization2. What-if Tool exploration using the XGBoost Model Introduction This notebook shows how to use the [What-if Tool (WIT)](https://pair-code.github.io/what-if-tool/) on a deployed [Cloud AI Platform](https://cloud.google.com/ai-platform/) model. The What-If Tool provides an easy-to-use interface for expanding understanding of black-box classification and regression ML models. With the plugin, you can perform inference on a large set of examples and immediately visualize the results in a variety of ways. Additionally, examples can be edited manually or programmatically and re-run through the model in order to see the results of the changes. It contains tooling for investigating model performance and fairness over subsets of a dataset. The purpose of the tool is to give people a simple, intuitive, and powerful way to explore and investigate trained ML models through a visual interface with absolutely no code required.[Extreme Gradient Boosting (XGBoost)](https://xgboost.ai/) is a decision-tree-based ensemble Machine Learning algorithm that uses a gradient boosting framework. In prediction problems involving unstructured data (images, text, etc.) artificial neural networks tend to outperform all other algorithms or frameworks. However, when it comes to small-to-medium structured/tabular data, decision tree based algorithms are considered best-in-class right now. Please see the chart below for the evolution of tree-based algorithms over the years.*You don't need your own cloud project* to run this notebook. ** UPDATE LINK BEFORE PRODUCTION **: Each learning objective will correspond to a __TODO__ in the [student lab notebook](https://github.com/GoogleCloudPlatform/training-data-analyst/blob/gwendolyn-dev/courses/machine_learning/deepdive2/ml_on_gc/what_if_mortgage.ipynb)) -- try to complete that notebook first before reviewing this solution notebook. Set up environment variables and load necessary libraries We will start by importing the necessary libraries for this lab.
###Code
import sys
python_version = sys.version_info[0]
print("Python Version: ", python_version)
!pip3 install witwidget
import pandas as pd
import numpy as np
import witwidget
from witwidget.notebook.visualization import WitWidget, WitConfigBuilder
###Output
_____no_output_____
###Markdown
Loading the mortgage test datasetThe model we'll be exploring here is a binary classification model built with XGBoost and trained on a [mortgage dataset](https://www.ffiec.gov/hmda/hmdaflat.htm). It predicts whether or not a mortgage application will be approved. In this section we'll:* Download some test data from Cloud Storage and load it into a numpy array + Pandas DataFrame* Preview the features for our model in Pandas
###Code
# Download our Pandas dataframe and our test features and labels
!gsutil cp gs://mortgage_dataset_files/data.pkl .
!gsutil cp gs://mortgage_dataset_files/x_test.npy .
!gsutil cp gs://mortgage_dataset_files/y_test.npy .
###Output
Copying gs://mortgage_dataset_files/data.pkl...
| [1 files][104.0 MiB/104.0 MiB]
Operation completed over 1 objects/104.0 MiB.
Copying gs://mortgage_dataset_files/x_test.npy...
/ [1 files][172.0 KiB/172.0 KiB]
Operation completed over 1 objects/172.0 KiB.
Copying gs://mortgage_dataset_files/y_test.npy...
/ [1 files][ 628.0 B/ 628.0 B]
Operation completed over 1 objects/628.0 B.
###Markdown
Preview the Features Preview the features from our model as a pandas DataFrame
###Code
features = pd.read_pickle('data.pkl')
features.head()
features.info()
###Output
<class 'pandas.core.frame.DataFrame'>
Int64Index: 999999 entries, 310650 to 875688
Data columns (total 44 columns):
as_of_year 999999 non-null int16
occupancy 999999 non-null int8
loan_amt_thousands 999999 non-null float64
county_code 999999 non-null float64
applicant_income_thousands 999999 non-null float64
population 999999 non-null float64
ffiec_median_fam_income 999999 non-null float64
tract_to_msa_income_pct 999999 non-null float64
num_owner_occupied_units 999999 non-null float64
num_1_to_4_family_units 999999 non-null float64
agency_code_Consumer Financial Protection Bureau (CFPB) 999999 non-null uint8
agency_code_Department of Housing and Urban Development (HUD) 999999 non-null uint8
agency_code_Federal Deposit Insurance Corporation (FDIC) 999999 non-null uint8
agency_code_Federal Reserve System (FRS) 999999 non-null uint8
agency_code_National Credit Union Administration (NCUA) 999999 non-null uint8
agency_code_Office of the Comptroller of the Currency (OCC) 999999 non-null uint8
loan_type_Conventional (any loan other than FHA, VA, FSA, or RHS loans) 999999 non-null uint8
loan_type_FHA-insured (Federal Housing Administration) 999999 non-null uint8
loan_type_FSA/RHS (Farm Service Agency or Rural Housing Service) 999999 non-null uint8
loan_type_VA-guaranteed (Veterans Administration) 999999 non-null uint8
property_type_Manufactured housing 999999 non-null uint8
property_type_One to four-family (other than manufactured housing) 999999 non-null uint8
loan_purpose_Home improvement 999999 non-null uint8
loan_purpose_Home purchase 999999 non-null uint8
loan_purpose_Refinancing 999999 non-null uint8
preapproval_Not applicable 999999 non-null uint8
preapproval_Preapproval was not requested 999999 non-null uint8
preapproval_Preapproval was requested 999999 non-null uint8
purchaser_type_Affiliate institution 999999 non-null uint8
purchaser_type_Commercial bank, savings bank or savings association 999999 non-null uint8
purchaser_type_Fannie Mae (FNMA) 999999 non-null uint8
purchaser_type_Farmer Mac (FAMC) 999999 non-null uint8
purchaser_type_Freddie Mac (FHLMC) 999999 non-null uint8
purchaser_type_Ginnie Mae (GNMA) 999999 non-null uint8
purchaser_type_Life insurance company, credit union, mortgage bank, or finance company 999999 non-null uint8
purchaser_type_Loan was not originated or was not sold in calendar year covered by register 999999 non-null uint8
purchaser_type_Other type of purchaser 999999 non-null uint8
purchaser_type_Private securitization 999999 non-null uint8
hoepa_status_HOEPA loan 999999 non-null uint8
hoepa_status_Not a HOEPA loan 999999 non-null uint8
lien_status_Not applicable (purchased loans) 999999 non-null uint8
lien_status_Not secured by a lien 999999 non-null uint8
lien_status_Secured by a first lien 999999 non-null uint8
lien_status_Secured by a subordinate lien 999999 non-null uint8
dtypes: float64(8), int16(1), int8(1), uint8(34)
memory usage: 104.0 MB
###Markdown
Load the test features and labels into numpy arrays Developing machine learning models in Python often requires the use of NumPy arrays. Recall that NumPy, which stands for Numerical Python, is a library consisting of multidimensional array objects and a collection of routines for processing those arrays. NumPy arrays are efficient data structures for working with data in Python, and machine learning models like those in the scikit-learn library, and deep learning models like those in the Keras library, expect input data in the format of NumPy arrays and make predictions in the format of NumPy arrays. As such, it is common to need to save NumPy arrays to file. Note that the data info reveals the following datatypes dtypes: float64(8), int16(1), int8(1), uint8(34) -- and no strings or "objects". So, let's now load the features and labels into numpy arrays.
###Code
x_test = np.load('x_test.npy')
y_test = np.load('y_test.npy')
###Output
_____no_output_____
###Markdown
Let's take a look at the contents of the 'x_test.npy' file. You can see the "array" structure.
###Code
print(x_test)
###Output
[[2.016e+03 1.000e+00 4.170e+02 ... 0.000e+00 1.000e+00 0.000e+00]
[2.016e+03 1.000e+00 2.760e+02 ... 0.000e+00 1.000e+00 0.000e+00]
[2.016e+03 1.000e+00 6.000e+01 ... 0.000e+00 1.000e+00 0.000e+00]
...
[2.016e+03 1.000e+00 5.000e+02 ... 0.000e+00 0.000e+00 0.000e+00]
[2.016e+03 1.000e+00 1.100e+02 ... 0.000e+00 1.000e+00 0.000e+00]
[2.016e+03 1.000e+00 3.680e+02 ... 0.000e+00 1.000e+00 0.000e+00]]
###Markdown
Combine the features and labels into one array for the What-if ToolNote that the numpy.hstack() function is used to stack the sequence of input arrays horizontally (i.e. column wise) to make a single array. In the following example, the numpy matrix is reshaped into a vector using the reshape function with .reshape((-1, 1) to convert the array into a single column matrix.
###Code
test_examples = np.hstack((x_test,y_test.reshape(-1,1)))
###Output
_____no_output_____
###Markdown
Using the What-if Tool to interpret our modelWith our test examples ready, we can now connect our model to the What-if Tool using the `WitWidget`. To use the What-if Tool with Cloud AI Platform, we need to send it:* A Python list of our test features + ground truth labels* Optionally, the names of our columns* Our Cloud project, model, and version name (we've created a public one for you to play around with)See the next cell for some exploration ideas in the What-if Tool. Create a What-if Tool visualizationThis prediction adjustment function is needed as this xgboost model's prediction returns just a score for the positive class of the binary classification, whereas the What-If Tool expects a list of scores for each class (in this case, both the negative class and the positive class). **NOTE:** The WIT may take a minute to load. While it is loading, review the parameters that are defined in the next cell, BUT NOT RUN IT, it is simply for reference.
###Code
# ******** DO NOT RUN THIS CELL ********
# TODO 1
PROJECT_ID = 'YOUR_PROJECT_ID'
MODEL_NAME = 'YOUR_MODEL_NAME'
VERSION_NAME = 'YOUR_VERSION_NAME'
TARGET_FEATURE = 'mortgage_status'
LABEL_VOCAB = ['denied', 'approved']
# TODO 1a
config_builder = (WitConfigBuilder(test_examples.tolist(), features.columns.tolist() + ['mortgage_status'])
.set_ai_platform_model(PROJECT_ID, MODEL_NAME, VERSION_NAME, adjust_prediction=adjust_prediction)
.set_target_feature(TARGET_FEATURE)
.set_label_vocab(LABEL_VOCAB))
###Output
_____no_output_____
###Markdown
Run this cell to load the WIT config builder. **NOTE:** The WIT may take a minute to load
###Code
# TODO 1b
def adjust_prediction(pred):
return [1 - pred, pred]
config_builder = (WitConfigBuilder(test_examples.tolist(), features.columns.tolist() + ['mortgage_status'])
.set_ai_platform_model('wit-caip-demos', 'xgb_mortgage', 'v1', adjust_prediction=adjust_prediction)
.set_target_feature('mortgage_status')
.set_label_vocab(['denied', 'approved']))
WitWidget(config_builder, height=800)
###Output
_____no_output_____
###Markdown
LABXX: What-if Tool: Model Interpretability Using Mortgage Data **Learning Objectives**1. Create a What-if Tool visualization2. What-if Tool exploration using the XGBoost Model Introduction This notebook shows how to use the [What-if Tool (WIT)](https://pair-code.github.io/what-if-tool/) on a deployed [Cloud AI Platform](https://cloud.google.com/ai-platform/) model. The What-If Tool provides an easy-to-use interface for expanding understanding of black-box classification and regression ML models. With the plugin, you can perform inference on a large set of examples and immediately visualize the results in a variety of ways. Additionally, examples can be edited manually or programmatically and re-run through the model in order to see the results of the changes. It contains tooling for investigating model performance and fairness over subsets of a dataset. The purpose of the tool is to give people a simple, intuitive, and powerful way to explore and investigate trained ML models through a visual interface with absolutely no code required.[Extreme Gradient Boosting (XGBoost)](https://xgboost.ai/) is a decision-tree-based ensemble Machine Learning algorithm that uses a gradient boosting framework. In prediction problems involving unstructured data (images, text, etc.) artificial neural networks tend to outperform all other algorithms or frameworks. However, when it comes to small-to-medium structured/tabular data, decision tree based algorithms are considered best-in-class right now. Please see the chart below for the evolution of tree-based algorithms over the years.*You don't need your own cloud project* to run this notebook. ** UPDATE LINK BEFORE PRODUCTION **: Each learning objective will correspond to a __TODO__ in the [student lab notebook](https://github.com/GoogleCloudPlatform/training-data-analyst/blob/gwendolyn-dev/courses/machine_learning/deepdive2/ml_on_gc/what_if_mortgage.ipynb)) -- try to complete that notebook first before reviewing this solution notebook. Set up environment variables and load necessary libraries We will start by importing the necessary libraries for this lab.
###Code
import sys
python_version = sys.version_info[0]
print("Python Version: ", python_version)
!pip3 install witwidget
import pandas as pd
import numpy as np
import witwidget
from witwidget.notebook.visualization import WitWidget, WitConfigBuilder
###Output
_____no_output_____
###Markdown
Loading the mortgage test datasetThe model we'll be exploring here is a binary classification model built with XGBoost and trained on a [mortgage dataset](https://www.ffiec.gov/hmda/hmdaflat.htm). It predicts whether or not a mortgage application will be approved. In this section we'll:* Download some test data from Cloud Storage and load it into a numpy array + Pandas DataFrame* Preview the features for our model in Pandas
###Code
# Download our Pandas dataframe and our test features and labels
!gsutil cp gs://mortgage_dataset_files/data.pkl .
!gsutil cp gs://mortgage_dataset_files/x_test.npy .
!gsutil cp gs://mortgage_dataset_files/y_test.npy .
###Output
Copying gs://mortgage_dataset_files/data.pkl...
| [1 files][104.0 MiB/104.0 MiB]
Operation completed over 1 objects/104.0 MiB.
Copying gs://mortgage_dataset_files/x_test.npy...
/ [1 files][172.0 KiB/172.0 KiB]
Operation completed over 1 objects/172.0 KiB.
Copying gs://mortgage_dataset_files/y_test.npy...
/ [1 files][ 628.0 B/ 628.0 B]
Operation completed over 1 objects/628.0 B.
###Markdown
Preview the Features Preview the features from our model as a pandas DataFrame
###Code
features = pd.read_pickle('data.pkl')
features.head()
features.info()
###Output
<class 'pandas.core.frame.DataFrame'>
Int64Index: 999999 entries, 310650 to 875688
Data columns (total 44 columns):
as_of_year 999999 non-null int16
occupancy 999999 non-null int8
loan_amt_thousands 999999 non-null float64
county_code 999999 non-null float64
applicant_income_thousands 999999 non-null float64
population 999999 non-null float64
ffiec_median_fam_income 999999 non-null float64
tract_to_msa_income_pct 999999 non-null float64
num_owner_occupied_units 999999 non-null float64
num_1_to_4_family_units 999999 non-null float64
agency_code_Consumer Financial Protection Bureau (CFPB) 999999 non-null uint8
agency_code_Department of Housing and Urban Development (HUD) 999999 non-null uint8
agency_code_Federal Deposit Insurance Corporation (FDIC) 999999 non-null uint8
agency_code_Federal Reserve System (FRS) 999999 non-null uint8
agency_code_National Credit Union Administration (NCUA) 999999 non-null uint8
agency_code_Office of the Comptroller of the Currency (OCC) 999999 non-null uint8
loan_type_Conventional (any loan other than FHA, VA, FSA, or RHS loans) 999999 non-null uint8
loan_type_FHA-insured (Federal Housing Administration) 999999 non-null uint8
loan_type_FSA/RHS (Farm Service Agency or Rural Housing Service) 999999 non-null uint8
loan_type_VA-guaranteed (Veterans Administration) 999999 non-null uint8
property_type_Manufactured housing 999999 non-null uint8
property_type_One to four-family (other than manufactured housing) 999999 non-null uint8
loan_purpose_Home improvement 999999 non-null uint8
loan_purpose_Home purchase 999999 non-null uint8
loan_purpose_Refinancing 999999 non-null uint8
preapproval_Not applicable 999999 non-null uint8
preapproval_Preapproval was not requested 999999 non-null uint8
preapproval_Preapproval was requested 999999 non-null uint8
purchaser_type_Affiliate institution 999999 non-null uint8
purchaser_type_Commercial bank, savings bank or savings association 999999 non-null uint8
purchaser_type_Fannie Mae (FNMA) 999999 non-null uint8
purchaser_type_Farmer Mac (FAMC) 999999 non-null uint8
purchaser_type_Freddie Mac (FHLMC) 999999 non-null uint8
purchaser_type_Ginnie Mae (GNMA) 999999 non-null uint8
purchaser_type_Life insurance company, credit union, mortgage bank, or finance company 999999 non-null uint8
purchaser_type_Loan was not originated or was not sold in calendar year covered by register 999999 non-null uint8
purchaser_type_Other type of purchaser 999999 non-null uint8
purchaser_type_Private securitization 999999 non-null uint8
hoepa_status_HOEPA loan 999999 non-null uint8
hoepa_status_Not a HOEPA loan 999999 non-null uint8
lien_status_Not applicable (purchased loans) 999999 non-null uint8
lien_status_Not secured by a lien 999999 non-null uint8
lien_status_Secured by a first lien 999999 non-null uint8
lien_status_Secured by a subordinate lien 999999 non-null uint8
dtypes: float64(8), int16(1), int8(1), uint8(34)
memory usage: 104.0 MB
###Markdown
Load the test features and labels into numpy arrays Developing machine learning models in Python often requires the use of NumPy arrays. Recall that NumPy, which stands for Numerical Python, is a library consisting of multidimensional array objects and a collection of routines for processing those arrays. NumPy arrays are efficient data structures for working with data in Python, and machine learning models like those in the scikit-learn library, and deep learning models like those in the Keras library, expect input data in the format of NumPy arrays and make predictions in the format of NumPy arrays. As such, it is common to need to save NumPy arrays to file. Note that the data info reveals the following datatypes dtypes: float64(8), int16(1), int8(1), uint8(34) -- and no strings or "objects". So, let's now load the features and labels into numpy arrays.
###Code
x_test = np.load('x_test.npy')
y_test = np.load('y_test.npy')
###Output
_____no_output_____
###Markdown
Let's take a look at the contents of the 'x_test.npy' file. You can see the "array" structure.
###Code
print(x_test)
###Output
[[2.016e+03 1.000e+00 4.170e+02 ... 0.000e+00 1.000e+00 0.000e+00]
[2.016e+03 1.000e+00 2.760e+02 ... 0.000e+00 1.000e+00 0.000e+00]
[2.016e+03 1.000e+00 6.000e+01 ... 0.000e+00 1.000e+00 0.000e+00]
...
[2.016e+03 1.000e+00 5.000e+02 ... 0.000e+00 0.000e+00 0.000e+00]
[2.016e+03 1.000e+00 1.100e+02 ... 0.000e+00 1.000e+00 0.000e+00]
[2.016e+03 1.000e+00 3.680e+02 ... 0.000e+00 1.000e+00 0.000e+00]]
###Markdown
Combine the features and labels into one array for the What-if ToolNote that the numpy.hstack() function is used to stack the sequence of input arrays horizontally (i.e. column wise) to make a single array. In the following example, the numpy matrix is reshaped into a vector using the reshape function with .reshape((-1, 1) to convert the array into a single column matrix.
###Code
test_examples = np.hstack((x_test,y_test.reshape(-1,1)))
###Output
_____no_output_____
###Markdown
Using the What-if Tool to interpret our modelWith our test examples ready, we can now connect our model to the What-if Tool using the `WitWidget`. To use the What-if Tool with Cloud AI Platform, we need to send it:* A Python list of our test features + ground truth labels* Optionally, the names of our columns* Our Cloud project, model, and version name (we've created a public one for you to play around with)See the next cell for some exploration ideas in the What-if Tool. Create a What-if Tool visualizationThis prediction adjustment function is needed as this xgboost model's prediction returns just a score for the positive class of the binary classification, whereas the What-If Tool expects a list of scores for each class (in this case, both the negative class and the positive class). **NOTE:** The WIT may take a minute to load. While it is loading, review the parameters that are defined in the next cell, BUT NOT RUN IT, it is simply for reference.
###Code
# ******** DO NOT RUN THIS CELL ********
# TODO 1
PROJECT_ID = 'YOUR_PROJECT_ID'
MODEL_NAME = 'YOUR_MODEL_NAME'
VERSION_NAME = 'YOUR_VERSION_NAME'
TARGET_FEATURE = 'mortgage_status'
LABEL_VOCAB = ['denied', 'approved']
# TODO 1a
config_builder = (WitConfigBuilder(test_examples.tolist(), features.columns.tolist() + ['mortgage_status'])
.set_ai_platform_model(PROJECT_ID, MODEL_NAME, VERSION_NAME, adjust_prediction=adjust_prediction)
.set_target_feature(TARGET_FEATURE)
.set_label_vocab(LABEL_VOCAB))
###Output
_____no_output_____
###Markdown
Run this cell to load the WIT config builder. **NOTE:** The WIT may take a minute to load
###Code
# TODO 1b
def adjust_prediction(pred):
return [1 - pred, pred]
config_builder = (WitConfigBuilder(test_examples.tolist(), features.columns.tolist() + ['mortgage_status'])
.set_ai_platform_model('wit-caip-demos', 'xgb_mortgage', 'v1', adjust_prediction=adjust_prediction)
.set_target_feature('mortgage_status')
.set_label_vocab(['denied', 'approved']))
WitWidget(config_builder, height=800)
###Output
_____no_output_____ |
terra-notebooks-playground/R - How to emit markdown from code cells.ipynb | ###Markdown
How to emit markdown from code cellsThe code in this notebook is based on https://cran.r-project.org/web/packages/qwraps2/vignettes/summary-statistics.html It is a convenient way to create nicely formatted summary statistics.Due to Jupyter's [security model](https://ipython.org/ipython-doc/3/notebook/security.html) we have to take a few extra steps to have results from a code cell be displayed as markdown.* The Jupyter extension Python Markdown https://stackoverflow.com/a/43913035/4138705 can be added and that works but the results are only transient. When someone else opens the notebook, the code in the markdown cell is not run because the notebook is 'not trusted' and the reader just sees 'undefined'.* Using `IRdisplay::display_markdown` behaves similarly and that is what we use in this notebook.* For more detail, see https://ipython.org/ipython-doc/3/notebook/security.html Setup
###Code
lapply(c('qwraps2'),
function(pkg) { if(! pkg %in% installed.packages()) { install.packages(pkg)} } )
library(qwraps2)
library(tidyverse)
###Output
── [1mAttaching packages[22m ─────────────────────────────────────── tidyverse 1.3.1 ──
[32m✔[39m [34mggplot2[39m 3.3.3 [32m✔[39m [34mpurrr [39m 0.3.4
[32m✔[39m [34mtibble [39m 3.1.1 [32m✔[39m [34mdplyr [39m 1.0.6
[32m✔[39m [34mtidyr [39m 1.1.3 [32m✔[39m [34mstringr[39m 1.4.0
[32m✔[39m [34mreadr [39m 1.4.0 [32m✔[39m [34mforcats[39m 0.5.1
── [1mConflicts[22m ────────────────────────────────────────── tidyverse_conflicts() ──
[31m✖[39m [34mdplyr[39m::[32mfilter()[39m masks [34mstats[39m::filter()
[31m✖[39m [34mdplyr[39m::[32mlag()[39m masks [34mstats[39m::lag()
###Markdown
mtcars example
###Code
data(mtcars)
mtcars2 <-
dplyr::mutate(mtcars,
cyl_factor = factor(cyl,
levels = c(6, 4, 8),
labels = paste(c(6, 4, 8), "cylinders")),
cyl_character = paste(cyl, "cylinders"))
our_summary1 <-
list("Miles Per Gallon" =
list("min" = ~ min(mpg),
"max" = ~ max(mpg),
"mean (sd)" = ~ qwraps2::mean_sd(mpg)),
"Displacement" =
list("min" = ~ min(disp),
"max" = ~ max(disp),
"mean (sd)" = ~ qwraps2::mean_sd(disp)),
"Weight (1000 lbs)" =
list("min" = ~ min(wt),
"max" = ~ max(wt),
"mean (sd)" = ~ qwraps2::mean_sd(wt)),
"Forward Gears" =
list("Three" = ~ qwraps2::n_perc0(gear == 3),
"Four" = ~ qwraps2::n_perc0(gear == 4),
"Five" = ~ qwraps2::n_perc0(gear == 5))
)
table1 <- summary_table(mtcars2, our_summary1)
###Output
_____no_output_____
###Markdown
**If you do not see the table in the next cell**, click on the 'Not Trusted' button in the upper right hand corner of the screen.
###Code
IRdisplay::display_markdown(str_c(capture.output(print(summary_table(mtcars2, our_summary1), rtitle = 'TABLE 1', markup = 'markdown')),
collapse = '\n'))
###Output
_____no_output_____
###Markdown
1000 Genomes metadata example
###Code
sampleData <- read_csv(
"http://storage.googleapis.com/genomics-public-data/1000-genomes/other/sample_info/sample_info.csv",
guess_max = 3000)
dim(sampleData)
super_populations <- sampleData %>%
group_by(Super_Population) %>%
mutate(mean_Total_LC_Sequence = mean(Total_LC_Sequence, na.rm=TRUE))
our_summary2 <-
list("Total Low Coverage Sequence" =
list("min" = ~ min(mean_Total_LC_Sequence, na.rm=TRUE),
"max" = ~ max(mean_Total_LC_Sequence, na.rm=TRUE),
"mean (sd)" = ~ qwraps2::mean_sd(mean_Total_LC_Sequence, na_rm=TRUE)))
###Output
_____no_output_____
###Markdown
**If you do not see the table in the next cell**, click on the 'Not Trusted' button in the upper right hand corner of the screen.
###Code
IRdisplay::display_markdown(str_c(capture.output(print(summary_table(super_populations, our_summary2),
rtitle = 'TABLE 1', markup = 'markdown')),
collapse = '\n'))
###Output
_____no_output_____
###Markdown
Provenance
###Code
devtools::session_info()
###Output
_____no_output_____ |
week_7/in_class_review.ipynb | ###Markdown
Let's make our own custom module called Comparable. Our module will have the following methods:```def compare_num( Params: num1 -> float, num2 -> float): Compares two numbers and returns the larger number If equal, returns Truedef add_num( Params: num1 -> float, num2 -> float): Adds two numbers and returns valuedef subtract_num( Params: num1 -> float, num2 -> float): Subtracts two numbers and returns valuedef multiply_num( Params: num1 -> float, num2 -> float): Multiplies two nums and returns valuedef divide_num( Params: num1 -> float, num2 -> float): Divides two nums and returns valuedef modulo_num( Params: num1 -> float, num2 -> float): Modulos two nums and returns value```
###Code
# use the import keyword to import our custom module
# Let's use our add_num method to add our two numbers
# Our subtract_num method
# Our multiply method
# Our divide method
# Our module method
# Our average method
###Output
_____no_output_____
###Markdown
Now let's import some libraries already installed with Python We will be using Pandas, Names, NumPy, and Random
###Code
# Let's install these modules into our system, it will come handy soon
!pip install names
!pip install pandas
!pip install random
!pip install numpy
# use the import keyword to import our pandas.
# We'll also use a names library to create some random psuedo names and random library to import random numbers
# Let's also use numpy for easier manipulation of numbers and arrays
# Let's make a quick dataframe using pandas
# But first, let's make a list of random names for 100 students
# Now let's make random grades for each student
# to do that we need to use the random library
# Let's make some Faculty members in our school
# Let's make the list larger with duplicates of the first 20 names
# We can use the shuffle method from the random library to shuffle our list and randomize it
# Let's create a dictionary of our school
# Now let's make a Database using our dictionary
###Output
_____no_output_____
###Markdown
Now, let's use our custom made Comparable library and create a new column that takes the average of all the grades for a student in a year
###Code
# We must use our get_average method
# To create a new column, we simply call the dataframe and type in the new column name in brackets
###Output
_____no_output_____ |
notebooks/.ipynb_checkpoints/n3_feature_extraction-checkpoint.ipynb | ###Markdown
The first objective of this notebook is to implement the next function (to extract sample intervals from the total period).
###Code
def generate_train_intervals(data_df, train_time, base_time, step, days_ahead, today):
pass
###Output
_____no_output_____
###Markdown
Let's define the parameters as constants, just to do some scratch work.
###Code
# I will try to keep the convention to name with the "days" suffix,
# to all the variables that represent "market days". The ones that
# represent real time will be named more arbitrarily.
train_time = 365 # In real time days
base_days = 7 # In market days
step_days = 7 # market days
ahead_days = 1 # market days
today = data_df.index[-1] # Real date
today
###Output
_____no_output_____
###Markdown
The amount of samples to be generated would be (train_time - base_time) * num_companies / step. There are days_ahead market days left, only for target values, so the total "used" period is train_time + days_ahead. The option of training with all, one, or some companies can be done by the user when it inputs the data (just filter data_df to get the companies you want). Anyway, one interesting choice would be to allow the training with multiple companies, targeting only one. That would multiply the features by the number of available companies, but would reduce the samples a lot. By now, I want to keep the complexity low, so I won't implement that idea, yet. A many to many approach could also be implemented (the target would be the vector with all the companies data). I will start with the simple "one to one".
###Code
data_df.index[data_df.index <= today][-(ahead_days + 1)]
def add_market_days(base, delta, data_df):
"""
base is in real time.
delta is in market days.
"""
market_days = data_df.index
if base not in market_days:
raise Exception('The base date is not in the market days list.')
base_index = market_days.tolist().index(base)
if base_index + delta >= len(market_days):
return market_days[-1]
if base_index + delta < 0:
return market_days[0]
return market_days[base_index + delta]
# Remember the last target days are not used for training, but that is a "market days" period.
end_of_training_date = add_market_days(today, -ahead_days, data_df)
start_date = end_of_training_date - dt.timedelta(train_time)
print('Start date: %s. End of training date: %s.' % (start_date, end_of_training_date))
TARGET_FEATURE = 'Close'
###Output
_____no_output_____
###Markdown
One important thing to note: the base time is in "market days", that means that it doesn't represent a period of "real" time (the real time may vary with each base interval).
###Code
def print_period(data_df):
print('Period: %s to %s.' % (data_df.index[0], data_df.index[-1]))
data_train_df = data_df[start_date:end_of_training_date]
print_period(data_train_df)
data_train_df.shape
start_target_date = add_market_days(start_date, base_days + ahead_days - 1, data_df)
data_target_df = data_df.loc[start_target_date: today,TARGET_FEATURE]
print_period(data_target_df)
data_target_df.shape
###Output
Period: 2014-01-09 00:00:00 to 2014-12-31 00:00:00.
###Markdown
Is that initial date correct?
###Code
data_train_df.index[:10]
###Output
_____no_output_____
###Markdown
Ok, it looks so. Let's split now! I should allow for different feature extraction functions to be used, after the time divisions.
###Code
date_base_ini = start_date
date_base_end = add_market_days(date_base_ini, base_days - 1, data_df)
date_target = add_market_days(date_base_end, ahead_days, data_df)
sample_blob = (data_train_df[date_base_ini: date_base_end], pd.DataFrame(data_target_df.loc[date_target]))
sample_blob[0]
target = sample_blob[1].T
target
###Output
_____no_output_____
###Markdown
Let's define a function that takes a "sample blob" and produces one sample per symbol, only for the "Close" feature (looks like the easiest to do first). The dates in the base period should be substituted by an index, and the symbols shuffled later (along with their labels).
###Code
feat_close = sample_blob[0][TARGET_FEATURE]
feat_close.index = np.arange(base_days)
feat_close
target.index = ['target']
target
x_y_samples = feat_close.append(target)
x_y_samples
x_y_samples_shuffled = x_y_samples.T.sample(frac=1).reset_index(drop=True)
x_y_samples_shuffled.head()
###Output
_____no_output_____
###Markdown
It is important to take care of the NaN values. Possibly at this sample_blob level is a good point to do so; just discard too bad samples.
###Code
x_y_samples_shuffled.isnull().sum()
x_y_samples_filtered = x_y_samples_shuffled.dropna(axis=0, how='any')
print(x_y_samples_filtered.shape)
x_y_samples_filtered.isnull().sum()
# At some point I will have to standarize those values... (not now, but just as a reminder...)
std_samples = x_y_samples_shuffled.apply(lambda x: x / np.mean(x), axis=1)
std_samples.head()
features = std_samples.iloc[:,:-1]
features.head()
target = pd.DataFrame(std_samples.iloc[:,-1])
target.head()
###Output
_____no_output_____
###Markdown
Let's create the samples divider function
###Code
TARGET_FEATURE = 'Close'
def feature_close_one_to_one(sample_blob):
target = sample_blob[1].T
feat_close = sample_blob[0][TARGET_FEATURE]
feat_close.index = np.arange(base_days)
target.index = ['target']
x_y_samples = feat_close.append(target)
x_y_samples_shuffled = x_y_samples.T.sample(frac=1).reset_index(drop=True)
x_y_samples_filtered = x_y_samples_shuffled.dropna(axis=0, how='any')
return x_y_samples_filtered
feature_close_one_to_one(sample_blob).head()
date_base_ini = start_date
date_base_end = add_market_days(date_base_ini, base_days - 1, data_df)
feat_tgt_df = pd.DataFrame()
while date_base_end < end_of_training_date:
sample_blob = (data_train_df[date_base_ini: date_base_end],
pd.DataFrame(data_target_df.loc[date_target]))
feat_tgt_blob = feature_close_one_to_one(sample_blob) # TODO: Change for a generic function
feat_tgt_df = feat_tgt_df.append(feat_tgt_blob, ignore_index=True)
date_base_ini = add_market_days(date_base_ini, step_days, data_df)
date_base_end = add_market_days(date_base_ini, base_days - 1, data_df)
# print('Start: %s, End:%s' % (date_base_ini, date_base_end))
feat_tgt_df = feat_tgt_df.sample(frac=1).reset_index(drop=True)
X_df = feat_tgt_df.iloc[:,:-1]
y_df = pd.DataFrame(feat_tgt_df.iloc[:,-1])
print(X_df.shape)
X_df.head()
print(y_df.shape)
y_df.head()
###Output
(17028, 1)
###Markdown
So, I have everything to define the final function of this notebook
###Code
def generate_train_intervals(data_df, train_time, base_time, step, days_ahead, today, blob_fun):
end_of_training_date = add_market_days(today, -ahead_days, data_df)
start_date = end_of_training_date - dt.timedelta(train_time)
start_target_date = add_market_days(start_date, base_days + ahead_days - 1, data_df)
data_train_df = data_df[start_date:end_of_training_date]
data_target_df = data_df.loc[start_target_date: today,TARGET_FEATURE]
date_base_ini = start_date
date_base_end = add_market_days(date_base_ini, base_days - 1, data_df)
feat_tgt_df = pd.DataFrame()
while date_base_end < end_of_training_date:
sample_blob = (data_train_df[date_base_ini: date_base_end],
pd.DataFrame(data_target_df.loc[date_target]))
feat_tgt_blob = blob_fun(sample_blob)
feat_tgt_df = feat_tgt_df.append(feat_tgt_blob, ignore_index=True)
date_base_ini = add_market_days(date_base_ini, step_days, data_df)
date_base_end = add_market_days(date_base_ini, base_days - 1, data_df)
# print('Start: %s, End:%s' % (date_base_ini, date_base_end))
feat_tgt_df = feat_tgt_df.sample(frac=1).reset_index(drop=True)
X_df = feat_tgt_df.iloc[:,:-1]
y_df = pd.DataFrame(feat_tgt_df.iloc[:,-1])
return X_df, y_df
train_time = 365 # In real time days
base_days = 7 # In market days
step_days = 7 # market days
ahead_days = 1 # market days
today = data_df.index[-1] # Real date
X, y = generate_train_intervals(data_df, train_time, base_days, step_days, ahead_days, today, feature_close_one_to_one)
print(X.shape)
X.head()
print(y.shape)
y.head()
###Output
(17028, 1)
|
sort_thou_email.ipynb | ###Markdown
###Code
words = 'His e-mail is [email protected]'
pieces = words.split()
parts = pieces[3].split('-')
n = parts[1]
print(n)
###Output
[email protected]
|
notebooks/.ipynb_checkpoints/20190624-piecewise-charfunc-checkpoint.ipynb | ###Markdown
Major goal here is to get time-dependent characteristic function clarified and working.
###Code
import os
os.chdir(r'/Users/rmccrickerd/desktop/jdheston')
import numpy as np
import pandas as pd
from jdheston import jdheston as jdh
from jdheston import utils as uts
from jdheston import config as cfg
from matplotlib import pyplot as plt
from scipy.stats import norm
from scipy.special import gamma
# import mpl
# %matplotlib inline
nx = np.newaxis
cfg.config(scale=1.5,print_keys=False)
x = 0.5
y = 0.5
uts.log_cosh_sinh(x,y), np.log(np.cosh(x) + y*np.sinh(x))
uts.tanh_frac(x,y), (y + np.tanh(x))/(1 + y*np.tanh(x))
T = np.array([1/12,3/12,6/12,1])[:,nx]
# M = ['1W','1M','3M','6M','9M','1Y']
Δ = np.linspace(5,95,19)[nx,:]/100
k = norm.ppf(Δ)*0.1*np.sqrt(T)
pd.DataFrame(k,index=T[:,0],columns=np.round(Δ[0,:],2))
###Output
_____no_output_____
###Markdown
Forward variance appears to scale fine for low epsilon but not high. Feels like implicit SDE is not parameterised as want -- to give the right expectation.
###Code
times = np.array([0,1/12,3/12,6/12])
sigma = np.array([ 0.1])*np.ones_like(times)
rho = np.array([ 0.0])*np.ones_like(times)
vee = np.array([ 1])*np.ones_like(times)
epsilon = np.array([ 1])*np.ones_like(times)
epsilon[-1] = 0
np.sqrt(np.mean([0.1**2, 0.2**2]))
params = np.array([times, sigma, rho, vee, epsilon]).T
np.round(params,2)
np.round(jdh.parameter_steps(params,1),2)
maturities = T
logstrikes = k
call_prices = jdh.jdh_pricer(maturities, logstrikes, params)
implied_vols = jdh.surface(maturities, logstrikes, call_prices)
pd.DataFrame(implied_vols,index=T[:,0],columns=Δ[0,:])
# plt.rcParams['figure.figsize'] = [2*1.618*2,2*3]
# plt.rcParams['legend.loc'] = 'lower left'
plot,axes = plt.subplots()
for i in range(len(T[:,0])):
axes.plot(k[i,:],100*implied_vols[i,:])
axes.set_xlabel(r'$k$')
axes.set_ylabel(r'$\bar{\sigma}(k,\tau)$')
# plt.savefig('temp')
###Output
_____no_output_____ |
logistic_regression_sparsity_and_l1_regularization.ipynb | ###Markdown
[View in Colaboratory](https://colab.research.google.com/github/douglaswchung/california-housing-value/blob/master/logistic_regression_sparsity_and_l1_regularization.ipynb) Copyright 2017 Google LLC.
###Code
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###Output
_____no_output_____
###Markdown
Sparsity and L1 Regularization **Learning Objectives:** * Calculate the size of a model * Apply L1 regularization to reduce the size of a model by increasing sparsity One way to reduce complexity is to use a regularization function that encourages weights to be exactly zero. For linear models such as regression, a zero weight is equivalent to not using the corresponding feature at all. In addition to avoiding overfitting, the resulting model will be more efficient.L1 regularization is a good way to increase sparsity. SetupRun the cells below to load the data and create feature definitions.
###Code
import math
from IPython import display
from matplotlib import cm
from matplotlib import gridspec
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
from sklearn import metrics
import tensorflow as tf
from tensorflow.python.data import Dataset
tf.logging.set_verbosity(tf.logging.ERROR)
pd.options.display.max_rows = 10
pd.options.display.float_format = '{:.1f}'.format
california_housing_dataframe = pd.read_csv("https://storage.googleapis.com/mledu-datasets/california_housing_train.csv", sep=",")
california_housing_dataframe = california_housing_dataframe.reindex(
np.random.permutation(california_housing_dataframe.index))
def preprocess_features(california_housing_dataframe):
"""Prepares input features from California housing data set.
Args:
california_housing_dataframe: A Pandas DataFrame expected to contain data
from the California housing data set.
Returns:
A DataFrame that contains the features to be used for the model, including
synthetic features.
"""
selected_features = california_housing_dataframe[
["latitude",
"longitude",
"housing_median_age",
"total_rooms",
"total_bedrooms",
"population",
"households",
"median_income"]]
processed_features = selected_features.copy()
# Create a synthetic feature.
processed_features["rooms_per_person"] = (
california_housing_dataframe["total_rooms"] /
california_housing_dataframe["population"])
return processed_features
def preprocess_targets(california_housing_dataframe):
"""Prepares target features (i.e., labels) from California housing data set.
Args:
california_housing_dataframe: A Pandas DataFrame expected to contain data
from the California housing data set.
Returns:
A DataFrame that contains the target feature.
"""
output_targets = pd.DataFrame()
# Create a boolean categorical feature representing whether the
# median_house_value is above a set threshold.
output_targets["median_house_value_is_high"] = (
california_housing_dataframe["median_house_value"] > 265000).astype(float)
return output_targets
# Choose the first 12000 (out of 17000) examples for training.
training_examples = preprocess_features(california_housing_dataframe.head(12000))
training_targets = preprocess_targets(california_housing_dataframe.head(12000))
# Choose the last 5000 (out of 17000) examples for validation.
validation_examples = preprocess_features(california_housing_dataframe.tail(5000))
validation_targets = preprocess_targets(california_housing_dataframe.tail(5000))
# Double-check that we've done the right thing.
print "Training examples summary:"
display.display(training_examples.describe())
print "Validation examples summary:"
display.display(validation_examples.describe())
print "Training targets summary:"
display.display(training_targets.describe())
print "Validation targets summary:"
display.display(validation_targets.describe())
def my_input_fn(features, targets, batch_size=1, shuffle=True, num_epochs=None):
"""Trains a linear regression model.
Args:
features: pandas DataFrame of features
targets: pandas DataFrame of targets
batch_size: Size of batches to be passed to the model
shuffle: True or False. Whether to shuffle the data.
num_epochs: Number of epochs for which data should be repeated. None = repeat indefinitely
Returns:
Tuple of (features, labels) for next data batch
"""
# Convert pandas data into a dict of np arrays.
features = {key:np.array(value) for key,value in dict(features).items()}
# Construct a dataset, and configure batching/repeating.
ds = Dataset.from_tensor_slices((features,targets)) # warning: 2GB limit
ds = ds.batch(batch_size).repeat(num_epochs)
# Shuffle the data, if specified.
if shuffle:
ds = ds.shuffle(10000)
# Return the next batch of data.
features, labels = ds.make_one_shot_iterator().get_next()
return features, labels
def get_quantile_based_buckets(feature_values, num_buckets):
quantiles = feature_values.quantile(
[(i+1.)/(num_buckets + 1.) for i in xrange(num_buckets)])
return [quantiles[q] for q in quantiles.keys()]
def construct_feature_columns():
"""Construct the TensorFlow Feature Columns.
Returns:
A set of feature columns
"""
bucketized_households = tf.feature_column.bucketized_column(
tf.feature_column.numeric_column("households"),
boundaries=get_quantile_based_buckets(training_examples["households"], 10))
bucketized_longitude = tf.feature_column.bucketized_column(
tf.feature_column.numeric_column("longitude"),
boundaries=get_quantile_based_buckets(training_examples["longitude"], 50))
bucketized_latitude = tf.feature_column.bucketized_column(
tf.feature_column.numeric_column("latitude"),
boundaries=get_quantile_based_buckets(training_examples["latitude"], 50))
bucketized_housing_median_age = tf.feature_column.bucketized_column(
tf.feature_column.numeric_column("housing_median_age"),
boundaries=get_quantile_based_buckets(
training_examples["housing_median_age"], 10))
bucketized_total_rooms = tf.feature_column.bucketized_column(
tf.feature_column.numeric_column("total_rooms"),
boundaries=get_quantile_based_buckets(training_examples["total_rooms"], 10))
bucketized_total_bedrooms = tf.feature_column.bucketized_column(
tf.feature_column.numeric_column("total_bedrooms"),
boundaries=get_quantile_based_buckets(training_examples["total_bedrooms"], 10))
bucketized_population = tf.feature_column.bucketized_column(
tf.feature_column.numeric_column("population"),
boundaries=get_quantile_based_buckets(training_examples["population"], 10))
bucketized_median_income = tf.feature_column.bucketized_column(
tf.feature_column.numeric_column("median_income"),
boundaries=get_quantile_based_buckets(training_examples["median_income"], 10))
bucketized_rooms_per_person = tf.feature_column.bucketized_column(
tf.feature_column.numeric_column("rooms_per_person"),
boundaries=get_quantile_based_buckets(
training_examples["rooms_per_person"], 10))
long_x_lat = tf.feature_column.crossed_column(
set([bucketized_longitude, bucketized_latitude]), hash_bucket_size=1000)
feature_columns = set([
long_x_lat,
bucketized_longitude,
bucketized_latitude,
bucketized_housing_median_age,
bucketized_total_rooms,
bucketized_total_bedrooms,
bucketized_population,
bucketized_households,
bucketized_median_income,
bucketized_rooms_per_person])
return feature_columns
###Output
_____no_output_____
###Markdown
Calculate the Model SizeTo calculate the model size, we simply count the number of parameters that are non-zero. We provide a helper function below to do that. The function uses intimate knowledge of the Estimators API - don't worry about understanding how it works.
###Code
def model_size(estimator):
variables = estimator.get_variable_names()
size = 0
for variable in variables:
if not any(x in variable
for x in ['global_step',
'centered_bias_weight',
'bias_weight',
'Ftrl']
):
size += np.count_nonzero(estimator.get_variable_value(variable))
return size
###Output
_____no_output_____
###Markdown
Reduce the Model SizeYour team needs to build a highly accurate Logistic Regression model on the *SmartRing*, a ring that is so smart it can sense the demographics of a city block ('median_income', 'avg_rooms', 'households', ..., etc.) and tell you whether the given city block is high cost city block or not.Since the SmartRing is small, the engineering team has determined that it can only handle a model that has **no more than 600 parameters**. On the other hand, the product management team has determined that the model is not launchable unless the **LogLoss is less than 0.35** on the holdout test set.Can you use your secret weapon—L1 regularization—to tune the model to satisfy both the size and accuracy constraints? Task 1: Find a good regularization coefficient.**Find an L1 regularization strength parameter which satisfies both constraints — model size is less than 600 and log-loss is less than 0.35 on validation set.**The following code will help you get started. There are many ways to apply regularization to your model. Here, we chose to do it using `FtrlOptimizer`, which is designed to give better results with L1 regularization than standard gradient descent.Again, the model will train on the entire data set, so expect it to run slower than normal.
###Code
def train_linear_classifier_model(
learning_rate,
regularization_strength,
steps,
batch_size,
feature_columns,
training_examples,
training_targets,
validation_examples,
validation_targets):
"""Trains a linear regression model.
In addition to training, this function also prints training progress information,
as well as a plot of the training and validation loss over time.
Args:
learning_rate: A `float`, the learning rate.
regularization_strength: A `float` that indicates the strength of the L1
regularization. A value of `0.0` means no regularization.
steps: A non-zero `int`, the total number of training steps. A training step
consists of a forward and backward pass using a single batch.
feature_columns: A `set` specifying the input feature columns to use.
training_examples: A `DataFrame` containing one or more columns from
`california_housing_dataframe` to use as input features for training.
training_targets: A `DataFrame` containing exactly one column from
`california_housing_dataframe` to use as target for training.
validation_examples: A `DataFrame` containing one or more columns from
`california_housing_dataframe` to use as input features for validation.
validation_targets: A `DataFrame` containing exactly one column from
`california_housing_dataframe` to use as target for validation.
Returns:
A `LinearClassifier` object trained on the training data.
"""
periods = 10
steps_per_period = steps / periods
# Create a linear classifier object.
my_optimizer = tf.train.FtrlOptimizer(learning_rate=learning_rate, l1_regularization_strength=regularization_strength)
my_optimizer = tf.contrib.estimator.clip_gradients_by_norm(my_optimizer, 5.0)
linear_classifier = tf.estimator.LinearClassifier(
feature_columns=feature_columns,
optimizer=my_optimizer
)
# Create input functions.
training_input_fn = lambda: my_input_fn(training_examples,
training_targets["median_house_value_is_high"],
batch_size=batch_size)
predict_training_input_fn = lambda: my_input_fn(training_examples,
training_targets["median_house_value_is_high"],
num_epochs=1,
shuffle=False)
predict_validation_input_fn = lambda: my_input_fn(validation_examples,
validation_targets["median_house_value_is_high"],
num_epochs=1,
shuffle=False)
# Train the model, but do so inside a loop so that we can periodically assess
# loss metrics.
print "Training model..."
print "LogLoss (on validation data):"
training_log_losses = []
validation_log_losses = []
for period in range (0, periods):
# Train the model, starting from the prior state.
linear_classifier.train(
input_fn=training_input_fn,
steps=steps_per_period
)
# Take a break and compute predictions.
training_probabilities = linear_classifier.predict(input_fn=predict_training_input_fn)
training_probabilities = np.array([item['probabilities'] for item in training_probabilities])
validation_probabilities = linear_classifier.predict(input_fn=predict_validation_input_fn)
validation_probabilities = np.array([item['probabilities'] for item in validation_probabilities])
# Compute training and validation loss.
training_log_loss = metrics.log_loss(training_targets, training_probabilities)
validation_log_loss = metrics.log_loss(validation_targets, validation_probabilities)
# Occasionally print the current loss.
print " period %02d : %0.2f" % (period, validation_log_loss)
# Add the loss metrics from this period to our list.
training_log_losses.append(training_log_loss)
validation_log_losses.append(validation_log_loss)
print "Model training finished."
# Output a graph of loss metrics over periods.
plt.ylabel("LogLoss")
plt.xlabel("Periods")
plt.title("LogLoss vs. Periods")
plt.tight_layout()
plt.plot(training_log_losses, label="training")
plt.plot(validation_log_losses, label="validation")
plt.legend()
return linear_classifier
linear_classifier = train_linear_classifier_model(
learning_rate=0.3,
# TWEAK THE REGULARIZATION VALUE BELOW
regularization_strength=0.9,
steps=500,
batch_size=100,
feature_columns=construct_feature_columns(),
training_examples=training_examples,
training_targets=training_targets,
validation_examples=validation_examples,
validation_targets=validation_targets)
print "Model size:", model_size(linear_classifier)
predict_validation_input_fn = lambda: my_input_fn(validation_examples,
validation_targets["median_house_value_is_high"],
num_epochs=1,
shuffle=False)
validation_probabilities = linear_classifier.predict(input_fn=predict_validation_input_fn)
# Get just the probabilities for the positive class.
validation_probabilities = np.array([item['probabilities'][1] for item in validation_probabilities])
false_positive_rate, true_positive_rate, thresholds = metrics.roc_curve(
validation_targets, validation_probabilities)
plt.plot(false_positive_rate, true_positive_rate, label="our model")
plt.plot([0, 1], [0, 1], label="random classifier")
_ = plt.legend(loc=2)
evaluation_metrics = linear_classifier.evaluate(input_fn=predict_validation_input_fn)
print "AUC on the validation set: %0.2f" % evaluation_metrics['auc']
print "Accuracy on the validation set: %0.2f" % evaluation_metrics['accuracy']
###Output
AUC on the validation set: 0.95
Accuracy on the validation set: 0.91
###Markdown
SolutionClick below to see a possible solution. A regularization strength of 0.1 should be sufficient. Note that there is a compromise to be struck:stronger regularization gives us smaller models, but can affect the classification loss.
###Code
linear_classifier = train_linear_classifier_model(
learning_rate=0.1,
regularization_strength=0.1,
steps=300,
batch_size=100,
feature_columns=construct_feature_columns(),
training_examples=training_examples,
training_targets=training_targets,
validation_examples=validation_examples,
validation_targets=validation_targets)
print "Model size:", model_size(linear_classifier)
###Output
_____no_output_____ |
Guided Project - Programming a Quantum Computer with Qiskit - IBM SDK/Task 1/Task 1 - Fundamentals of Quantum Computation.ipynb | ###Markdown
Task One : Fundamentals of Quantum Computation Basic Arithmetic Operations & Complex Numbers
###Code
#Adding Two Numbers
x=2+5
print(x)
#Subtracting Two Numbers
y=8-5
print(y)
#Multiplying Two Numbers
a=3*5
print(a)
#Dividing Two Numbers
b=8/4
print(b)
#Calculate the Remainder
r=4%3
print(r)
#Exponent of a Number
e=5**3
print(e)
###Output
125
###Markdown
Complex numbers are always of the form\begin{align}\alpha = a + bi\end{align}
###Code
c1=1j*1j
print(c1)
#Initialize two complex numbers
z=4+8j
w=5-5j
import numpy as np
print("Real part of z is:", np.real(z))
print("Imaginary part of w is:", np.imag(w))
#Add two complex numbers
add=z+w
print(add)
#Subtract two complex numbers
sub=z-w
print(sub)
###Output
(-1+13j)
###Markdown
Complex conjugate
###Code
#complex conjugate of w
print(w)
print("Complex conjugate of w is:", np.conj(w))
###Output
(5-5j)
Complex conjugate of w is: (5+5j)
###Markdown
Norms/Absolute Values\begin{align} ||z|| &= \sqrt{zz^*} = \sqrt{|z|^2},\\ ||w|| &= \sqrt{ww^*} = \sqrt{|w|^2}, \end{align}
###Code
#Calculating absolute values for z and w
print(z)
print("Norm/Absolute value of z is:", np.abs(z))
print(w)
print("Norm/Absolute value of w is:", np.abs(w))
###Output
(4+8j)
Norm/Absolute value of z is: 8.94427190999916
(5-5j)
Norm/Absolute value of w is: 7.0710678118654755
###Markdown
Row Vectors, Column Vectors, and Bra-Ket Notation \begin{align} \text{Column Vector:} \ \begin{pmatrix}a_1 \\ a_2 \\ \vdots \\ a_n\end{pmatrix} \quad \quad \text{Row Vector:} \ \begin{pmatrix}a_1, & a_2, & \cdots, & a_n\end{pmatrix} \end{align}
###Code
#Initialize a row vector
row_vector=np.array([1, 2+2j, 3])
print(row_vector)
#Initialize a column vector
column_vector=np.array([[1],[2+2j],[3j]])
print(column_vector)
###Output
[[1.+0.j]
[2.+2.j]
[0.+3.j]]
###Markdown
Row vectors in quantum mechanics are also called **bra-vectors**, and are denoted as follows:\begin{align} \langle A| = \begin{pmatrix}a_1, & a_2, \cdots, & a_n\end{pmatrix} \end{align}Column vectors are also called **ket-vectors** in quantum mechanics denoted as follows:\begin{align} |B\rangle = \begin{pmatrix}b_1 \\ b_2 \\ \vdots \\ b_n\end{pmatrix} \end{align}In general, if we have a column vector, i.e. a ket-vector:\begin{align} |A\rangle = \begin{pmatrix}a_1 \\ a_2 \\ \vdots \\ a_n\end{pmatrix} \end{align}the corresponding bra-vector:\begin{align} \langle A| = \begin{pmatrix}a_1^*, & a_2^*, & \cdots, & a_n^*\end{pmatrix} \end{align} Inner Product\begin{align} \langle A| = \begin{pmatrix}a_1, & a_2, & \cdots, & a_n\end{pmatrix}, \quad \quad|B\rangle = \begin{pmatrix}b_1 \\ b_2 \\ \vdots \\ b_n\end{pmatrix} \end{align}Taking the inner product of $\langle A|$ and $|B\rangle$ gives the following:\begin{align} \langle A| B \rangle &= \begin{pmatrix} a_1, & a_2, & \cdots, & a_n\end{pmatrix}\begin{pmatrix}b_1 \\ b_2 \\ \vdots \\ b_n\end{pmatrix}\\&= a_1b_1 + a_2b_2 + \cdots + a_nb_n\\&= \sum_{i=1}^n a_ib_i\end{align}
###Code
# Define the 4x1 matrix version of a column vector
A=np.array([[1],[4-5j],[5],[-3]])
# Define B as a 1x4 matrix
B=np.array([1, 5, -4j, -1j])
# Compute <B|A>
np.dot(B,A)
###Output
_____no_output_____
###Markdown
Matrices \begin{align}M = \begin{pmatrix}2-i & -3 \\-5i & 2\end{pmatrix}\end{align}
###Code
M=np.array([[2-1j, -3], [-5j, 2]])
#Note how the brackets are placed!
print(M)
M=np.matrix([[2-1j, 3],[-5j, 2]])
print(M)
###Output
[[ 2.-1.j 3.+0.j]
[-0.-5.j 2.+0.j]]
###Markdown
Hermitian conjugates are given by taking the conjugate transpose of the matrix
###Code
#To calculate hermitian matrix simple follow: <your matrix>.H
hermitian = M.H
print(hermitian)
###Output
[[ 2.+1.j -0.+5.j]
[ 3.-0.j 2.-0.j]]
###Markdown
Tensor Products of Matrices \begin{align}\begin{pmatrix}a & b \\c & d\end{pmatrix} \otimes \begin{pmatrix}x & y \\z & w\end{pmatrix} = \begin{pmatrix}a \begin{pmatrix}x & y \\z & w\end{pmatrix} & b \begin{pmatrix}x & y \\z & w\end{pmatrix} \\c \begin{pmatrix}x & y \\z & w\end{pmatrix} & d \begin{pmatrix}x & y \\z & w\end{pmatrix}\end{pmatrix} = \begin{pmatrix}ax & ay & bx & by \\az & aw & bz & bw \\cx & cy & dx & dy \\cz & cw & dz & dw\end{pmatrix}\end{align}
###Code
#Use the np.kron method
np.kron(M,M)
###Output
_____no_output_____ |
Python_Projects/Global_Model/Working/calculation_noinv.ipynb | ###Markdown
ion, neutral 들은 0.05eV로 고정
###Code
kB = 1.38e-23 #[J/K] [m2 kg K-1 s-2] Boltzmann constant
e = 1.602e-19 #[C] electronic charge
M = 1.67e-27 #[kg] mass of H atom
m = 9.1e-31 #[kg] mass of electorn
# ro = 100e-3 #[m] radius of chamber
# l = 312e-3 #[m] chamber length
# ro_min = 25e-3
# l_min = 200e-3
# a_cf = 0.33 #magnetic confinement parameter (0~1) if 1, B-field is absent.
ro = 100e-3 #[m]
l = 400e-3 #[m]
a_cf = 1
Tg = 300 #[K] room temperature
sigma_i = 5e-19 #[m2]
rec = 0.1 #Recombination Factor
V = np.pi*ro**2*l #[m^3] discharge volume
v0 = (8*Tg*kB/(M*np.pi))**0.5 #[m/s] mean velocity of H atom
LAMBDAeff = ((2.405/ro)**2+(np.pi/l)**2)**-0.5 #[m]
D_Kn = v0 * LAMBDAeff/3 #[m2/s]
Deff = D_Kn
T1 = LAMBDAeff**2/Deff #[s]
class Model:
def __init__(self, p, input_power, duty, period, time_resolution=1e-8):
self.p = p
self.input_power = input_power*6.241509e18 # [J/s] to [eV/s]
self.duty = duty
self.period = period
self.time_resolution = time_resolution
self.ng = (p/7.5)/(Tg*kB) #[m^-3]
lambda_i = 1/(self.ng*sigma_i) #[m] ion-neutral mean free path
hl = 0.86*(3+l/2/lambda_i)**-0.5
hR = 0.8*(4+ro/lambda_i)**-0.5
self.Aeff = 2*np.pi*ro*(a_cf*l*hR+ro*hl) #[m^2] effective area
#self.Aeff = 2*np.pi*ro*(a_cf*l*hR+ro*hl)+2*np.pi*ro_min*l_min*hR #[m^2] effective area
self.rec = 0.1 # recombination factor
self.routine_time_interval = np.linspace(0, self.period, int(self.period/self.time_resolution))
print('Condition : {}mTorr, {}W, {}ms, {}'.format(self.p, self.input_power/6.241509e18, self.period*1000, self.duty))
def balance_equations(self,calculation_array, t, power):
Te, nH, nH_2s, nH2_v1, nH2_v2, nH2_v3, nH2_v4, nH2_v5, nH2_v6, nH2_v7, nH2_v8, nH2_v9, nHp, nH2p, nH3p, nHm = calculation_array
#Quasi-Neutrality eqn 완료
ne = nHp + nH2p + nH3p - nHm
#Hydrogen atom conservation eqn 완료
nH2_v0 = self.ng - (0.5*(nH + nHp + nH_2s + nHm) + sum(calculation_array[3:12]) + nH2p + 1.5*nH3p)
uB = np.sqrt(e*Te/M) #[m/s]
uB2 = np.sqrt(e*Te/2/M)
uB3 = np.sqrt(e*Te/3/M)
Vs = -Te*np.log(4/ne/np.sqrt(8*e*Te/np.pi/m)*(nHp*uB+nH2p*uB2+nH3p*uB3))
#print('complex Vs: ',Vs)
#Vs = Te*np.log(np.sqrt(M/(2*np.pi*m)))
#print('simple Vs: ',Vs)
t0 = V/self.Aeff*np.sqrt(M/(e*Te)) #[s] Characteristic transit time of H+ ion
##### Rate coefficient calculation ##### 전부 m3/s로
k1_0 = xs.quick_rate_constant_with_analytic_xs(Te, 'reaction1_0')
k1_1 = xs.quick_rate_constant_with_analytic_xs(Te, 'reaction1_1')
k1_2 = xs.quick_rate_constant_with_analytic_xs(Te, 'reaction1_2')
k1_3 = xs.quick_rate_constant_with_analytic_xs(Te, 'reaction1_3')
k1_4 = xs.quick_rate_constant_with_analytic_xs(Te, 'reaction1_4')
k2 = np.exp(-2.858072836568e+01+1.038543976082e+01*np.log(Te)-5.383825026583e+00*(np.log(Te))**2+1.950636494405e+00*(np.log(Te))**3-5.393666392407e-01*(np.log(Te))**4+1.006916814453e-01*(np.log(Te))**5-1.160758573972e-02*(np.log(Te))**6+7.411623859122e-04*(np.log(Te))**7-2.001369618807e-05*(np.log(Te))**8)*1e-6
k3_1 = xs.quick_rate_constant_with_analytic_xs(Te, 'reaction3_1')
k3_2 = xs.quick_rate_constant_with_analytic_xs(Te, 'reaction3_2')
k3_3 = xs.quick_rate_constant_with_analytic_xs(Te, 'reaction3_3')
k3_4 = xs.quick_rate_constant_with_analytic_xs(Te, 'reaction3_4')
k3_5 = xs.quick_rate_constant_with_analytic_xs(Te, 'reaction3_5')
k3_6 = xs.quick_rate_constant_with_analytic_xs(Te, 'reaction3_6')
k4_0 = xs.quick_rate_constant_with_analytic_xs(Te, 'reaction4_0')
k4_1 = xs.quick_rate_constant_with_analytic_xs(Te, 'reaction4_1')
k4_2 = xs.quick_rate_constant_with_analytic_xs(Te, 'reaction4_2')
k4_3 = xs.quick_rate_constant_with_analytic_xs(Te, 'reaction4_3')
k4_4 = xs.quick_rate_constant_with_analytic_xs(Te, 'reaction4_4')
k4_5 = xs.quick_rate_constant_with_analytic_xs(Te, 'reaction4_5')
k4_6 = xs.quick_rate_constant_with_analytic_xs(Te, 'reaction4_6')
k4_7 = xs.quick_rate_constant_with_analytic_xs(Te, 'reaction4_7')
k4_8 = xs.quick_rate_constant_with_analytic_xs(Te, 'reaction4_8')
k5_0 = xs.quick_rate_constant_with_analytic_xs(Te, 'reaction5_0')
k5_1 = xs.quick_rate_constant_with_analytic_xs(Te, 'reaction5_1')
k5_2 = xs.quick_rate_constant_with_analytic_xs(Te, 'reaction5_2')
k5_3 = xs.quick_rate_constant_with_analytic_xs(Te, 'reaction5_3')
k5_4 = xs.quick_rate_constant_with_analytic_xs(Te, 'reaction5_4')
k5_5 = xs.quick_rate_constant_with_analytic_xs(Te, 'reaction5_5')
k5_6 = xs.quick_rate_constant_with_analytic_xs(Te, 'reaction5_6')
k5_7 = xs.quick_rate_constant_with_analytic_xs(Te, 'reaction5_7')
k5_8 = xs.quick_rate_constant_with_analytic_xs(Te, 'reaction5_8')
k5_9 = xs.quick_rate_constant_with_analytic_xs(Te, 'reaction5_9')
k6_0 = xs.quick_rate_constant_with_analytic_xs(Te, 'reaction6_0')
k6_1 = xs.quick_rate_constant_with_analytic_xs(Te, 'reaction6_1')
k6_2 = xs.quick_rate_constant_with_analytic_xs(Te, 'reaction6_2')
k6_3 = xs.quick_rate_constant_with_analytic_xs(Te, 'reaction6_2') #xs 데이터 보완 必
k6_4 = xs.quick_rate_constant_with_analytic_xs(Te, 'reaction6_5') #xs 데이터 보완 必
k6_5 = xs.quick_rate_constant_with_analytic_xs(Te, 'reaction6_5')
k6_6 = xs.quick_rate_constant_with_analytic_xs(Te, 'reaction6_6')
k6_7 = xs.quick_rate_constant_with_analytic_xs(Te, 'reaction6_7')
k6_8 = xs.quick_rate_constant_with_analytic_xs(Te, 'reaction6_8')
k6_9 = xs.quick_rate_constant_with_analytic_xs(Te, 'reaction6_9')
k7 = np.exp(-3.834597006782e+01+1.426322356722e+01*np.log(Te)-5.826468569506e+00*(np.log(Te))**2+1.727940947913e+00*(np.log(Te))**3-3.598120866343e-01*(np.log(Te))**4+4.822199350494e-02*(np.log(Te))**5-3.909402993006e-03*(np.log(Te))**6+1.738776657690e-04*(np.log(Te))**7-3.252844486351e-06*(np.log(Te))**8)*1e-6
k8 = np.exp(-3.271396786375e+01+1.353655609057e+01*np.log(Te)-5.739328757388e+00*(np.log(Te))**2+1.563154982022e+00*(np.log(Te))**3-2.877056004391e-01*(np.log(Te))**4+3.482559773737e-02*(np.log(Te))**5-2.631976175590e-03*(np.log(Te))**6+1.119543953861e-04*(np.log(Te))**7-2.039149852002e-06*(np.log(Te))**8)*1e-6
k9 = np.exp(-1.781416067709e+01+2.277799785711e+00*np.log(Te)-1.266868411626e+00*(np.log(Te))**2+4.296170447419e-01*(np.log(Te))**3-9.609908013189e-02*(np.log(Te))**4+1.387958040699e-02*(np.log(Te))**5-1.231349039470e-03*(np.log(Te))**6+6.042383126281e-05*(np.log(Te))**7-1.247521040900e-06*(np.log(Te))**8)*1e-6
k10 = 2.11e-9*1e-6
k11 = np.exp(-1.700270758355e+01-4.050073042947e-01*np.log(Te)+1.018733477232e-08*(np.log(Te))**2-1.695586285687e-08*(np.log(Te))**3+1.564311217508e-10*(np.log(Te))**4+1.979725412288e-09*(np.log(Te))**5-4.395545994733e-10*(np.log(Te))**6+3.584926377078e-11*(np.log(Te))**7-1.024189019465e-12*(np.log(Te))**8)*1e-6
k12 = np.exp(-3.078408636631e+01+1.509421488513e+01*np.log(Te)-7.349167207324e+00*(np.log(Te))**2+2.320966107642e+00*(np.log(Te))**3-4.818077551719e-01*(np.log(Te))**4+6.389229162737e-02*(np.log(Te))**5-5.161880953089e-03*(np.log(Te))**6+2.303985092606e-04*(np.log(Te))**7-4.344846146197e-06*(np.log(Te))**8)*1e-6
k13 = xs.quick_rate_constant_with_analytic_xs(Te, 'reaction13')
k14 = np.exp(-1.801849334273e+01+2.360852208681e+00*np.log(Te)-2.827443061704e-01*(np.log(Te))**2+1.623316639567e-02*(np.log(Te))**3-3.365012031363e-02*(np.log(Te))**4+1.178329782711e-02*(np.log(Te))**5-1.656194699504e-03*(np.log(Te))**6+1.068275202678e-04*(np.log(Te))**7-2.631285809207e-06*(np.log(Te))**8)*1e-6
k15 = 3e-10*1e-6 # Janev
k16 = 9e-14 #3e-10*1e-6 #ion 0.1eV
k17 = 7e-13 #3e-10*1e-6 # at ion Janev 94page
k18 = 7e-13 #3e-10*1e-6 # Assumption
k19 = np.exp(-3.454175591367e+01+1.412655911280e+01*np.log(Te)-6.004466156761e+00*(np.log(Te))**2+1.589476697488e+00*(np.log(Te))**3-2.775796909649e-01*(np.log(Te))**4+3.152736888124e-02*(np.log(Te))**5-2.229578042005e-03*(np.log(Te))**6+8.890114963166e-05*(np.log(Te))**7-1.523912962346e-06*(np.log(Te))**8)*1e-6
k20 = np.exp(-2.833259375256e+01+9.587356325603e+00*np.log(Te)-4.833579851041e+00*(np.log(Te))**2+1.415863373520e+00*(np.log(Te))**3-2.537887918825e-01*(np.log(Te))**4+2.800713977946e-02*(np.log(Te))**5-1.871408172571e-03*(np.log(Te))**6+6.986668318407e-05*(np.log(Te))**7-1.123758504195e-06*(np.log(Te))**8)*1e-6
k21 = np.exp(-1.973476726029e+01+3.992702671457e+00*np.log(Te)-1.773436308973e+00*(np.log(Te))**2+5.331949621358e-01*(np.log(Te))**3-1.181042453190e-01*(np.log(Te))**4+1.763136575032e-02*(np.log(Te))**5-1.616005335321e-03*(np.log(Te))**6+8.093908992682e-05*(np.log(Te))**7-1.686664454913e-06*(np.log(Te))**8)*1e-6
k22_1_0 = 0.42e-13*1e-6 #non-reactive assumption
k22_2_0 = 0.59e-12*1e-6
k22_2_1 = 0.30e-12*1e-6
k22_3_0 = 0.15e-11*1e-6
k22_3_1 = 0.16e-11*1e-6
k22_3_2 = 0.20e-11*1e-6
k22_4_0 = 0.43e-11*1e-6
k22_4_1 = 0.42e-11*1e-6
k22_4_2 = 0.49e-11*1e-6
k22_4_3 = 0.55e-11*1e-6
k22_5_0 = 0.16e-11*1e-6
k22_5_1 = 0.37e-11*1e-6
k22_5_2 = 0.69e-11*1e-6
k22_5_3 = 0.74e-11*1e-6
k22_5_4 = 0.89e-11*1e-6
k22_6_0 = 0.33e-11*1e-6
k22_6_1 = 0.51e-11*1e-6
k22_6_2 = 0.53e-11*1e-6
k22_6_3 = 0.69e-11*1e-6
k22_6_4 = 0.11e-10*1e-6
k22_6_5 = 0.12e-10*1e-6
k22_7_0 = 0.24e-11*1e-6
k22_7_1 = 0.38e-11*1e-6
k22_7_2 = 0.68e-11*1e-6
k22_7_3 = 0.57e-11*1e-6
k22_7_4 = 0.70e-11*1e-6
k22_7_5 = 0.11e-10*1e-6
k22_7_6 = 0.12e-10*1e-6
k22_8_0 = 0.30e-11*1e-6
k22_8_1 = 0.29e-11*1e-6
k22_8_2 = 0.29e-11*1e-6
k22_8_3 = 0.35e-11*1e-6
k22_8_4 = 0.56e-11*1e-6
k22_8_5 = 0.82e-11*1e-6
k22_8_6 = 0.12e-10*1e-6
k22_8_7 = 0.14e-10*1e-6
k22_9_0 = 0.52e-12*1e-6
k22_9_1 = 0.14e-11*1e-6
k22_9_2 = 0.30e-11*1e-6
k22_9_3 = 0.37e-11*1e-6
k22_9_4 = 0.48e-11*1e-6
k22_9_5 = 0.53e-11*1e-6
k22_9_6 = 0.92e-11*1e-6
k22_9_7 = 0.13e-10*1e-6
k22_9_8 = 0.14e-10*1e-6
k23 = rec*Deff/LAMBDAeff**2
k24 = uB*self.Aeff/V
k25 = uB2*self.Aeff/V
k26 = uB3*self.Aeff/V
k27 = Deff/LAMBDAeff**2
k28_1_0 = 1*Deff/LAMBDAeff**2
k28_2_0 = 0.6535*Deff/LAMBDAeff**2
k28_2_1 = 0.35*Deff/LAMBDAeff**2
k28_3_0 = 0.30023*Deff/LAMBDAeff**2
k28_3_1 = 0.40221*Deff/LAMBDAeff**2
k28_3_2 = 0.30023*Deff/LAMBDAeff**2
k28_4_0 = 0.17949*Deff/LAMBDAeff**2
k28_4_1 = 0.25373*Deff/LAMBDAeff**2
k28_4_2 = 0.32389*Deff/LAMBDAeff**2
k28_4_3 = 0.24312*Deff/LAMBDAeff**2
k28_5_0 = 0.15093*Deff/LAMBDAeff**2
k28_5_1 = 0.17867*Deff/LAMBDAeff**2
k28_5_2 = 0.22844*Deff/LAMBDAeff**2
k28_5_3 = 0.23986*Deff/LAMBDAeff**2
k28_5_4 = 0.19662*Deff/LAMBDAeff**2
k28_6_0 = 0.12483*Deff/LAMBDAeff**2
k28_6_1 = 0.13462*Deff/LAMBDAeff**2
k28_6_2 = 0.16399*Deff/LAMBDAeff**2
k28_6_3 = 0.1958*Deff/LAMBDAeff**2
k28_6_4 = 0.20478*Deff/LAMBDAeff**2
k28_6_5 = 0.17541*Deff/LAMBDAeff**2
k28_7_0 = 0.10035*Deff/LAMBDAeff**2
k28_7_1 = 0.11096*Deff/LAMBDAeff**2
k28_7_2 = 0.13054*Deff/LAMBDAeff**2
k28_7_3 = 0.15991*Deff/LAMBDAeff**2
k28_7_4 = 0.17949*Deff/LAMBDAeff**2
k28_7_5 = 0.17051*Deff/LAMBDAeff**2
k28_7_6 = 0.15093*Deff/LAMBDAeff**2
k28_8_0 = 0.08648*Deff/LAMBDAeff**2
k28_8_1 = 0.09056*Deff/LAMBDAeff**2
k28_8_2 = 0.10688*Deff/LAMBDAeff**2
k28_8_3 = 0.12483*Deff/LAMBDAeff**2
k28_8_4 = 0.16888*Deff/LAMBDAeff**2
k28_8_5 = 0.15991*Deff/LAMBDAeff**2
k28_8_6 = 0.14033*Deff/LAMBDAeff**2
k28_8_7 = 0.12564*Deff/LAMBDAeff**2
k28_9_0 = 0.07506*Deff/LAMBDAeff**2
k28_9_1 = 0.07832*Deff/LAMBDAeff**2
k28_9_2 = 0.08974*Deff/LAMBDAeff**2
k28_9_3 = 0.11014*Deff/LAMBDAeff**2
k28_9_4 = 0.13951*Deff/LAMBDAeff**2
k28_9_5 = 0.14359*Deff/LAMBDAeff**2
k28_9_6 = 0.12483*Deff/LAMBDAeff**2
k28_9_7 = 0.12238*Deff/LAMBDAeff**2
k28_9_8 = 0.11503*Deff/LAMBDAeff**2
##### Energy Loss per Reaction #####
E1_0 = 15.42
E1_1 = 15.42
E1_2 = 15.42
E1_3 = 15.42
E1_4 = 15.42
E2 = 8.5
E3_1 = 0.5
E3_2 = 1 # Assumption (E3_2 = E3_1*2)
E3_3 = 1.5
E3_4 = 2
E3_5 = 2.5
E3_6 = 3
E4_0 = 0.5
E4_1 = 0.5
E4_2 = 0.5
E4_3 = 0.5
E4_4 = 0.5
E4_5 = 0.5
E4_6 = 0.5
E4_7 = 0.5
E4_8 = 0.5
E5_0 = Te
E5_1 = Te
E5_2 = Te
E5_3 = Te
E5_4 = Te
E5_5 = Te
E5_6 = Te
E5_7 = Te
E5_8 = Te
E5_9 = Te
E6_0 = 20 # XS데이터가 다 20부터 시작임
E6_1 = 20
E6_2 = 20
E6_3 = 20
E6_4 = 20
E6_5 = 20
E6_6 = 20
E6_7 = 20
E6_8 = 20
E6_9 = 20
E7 = 18
E8 = 13.6
E9 = 10.5
E11 = Te
E12 = 14
E13 = Te
E14 = 0.75
E19 = 15.3
E20 = 10.2
E21 = 3.4
#Particle balance eqn for electron 완료
dne_dt = (k1_0*ne*nH2_v0) + (k1_1*ne*nH2_v1) + (k1_2*ne*nH2_v2) + (k1_3*ne*nH2_v3) + (k1_4*ne*nH2_v4) - (k5_0*ne*nH2_v0) - (k5_1*ne*nH2_v1) - (k5_2*ne*nH2_v2) - (k5_3*ne*nH2_v3) - (k5_4*ne*nH2_v4) - (k5_5*ne*nH2_v5) - (k5_6*ne*nH2_v6) - (k5_7*ne*nH2_v7) - (k5_8*ne*nH2_v8) - (k5_9*ne*nH2_v9) + (k7*ne*nH2_v0) + (k8*ne*nH) - (k11*ne*nH3p) - (k13*ne*nH3p) + (k14*ne*nHm) + (k15*nH*nHm) + (k21*ne*nH_2s) - ne*uB*self.Aeff/V
# print('-----------------------------------------')
# print('ne: ', ne)
# print('dne_dt: ',dne_dt)
# print('k1(production): ',(k1_0*ne*nH2_v0) + (k1_1*ne*nH2_v1) + (k1_2*ne*nH2_v2) + (k1_3*ne*nH2_v3) + (k1_4*ne*nH2_v4))
# print('k5(loss): ', - (k5_0*ne*nH2_v0) - (k5_1*ne*nH2_v1) - (k5_2*ne*nH2_v2) - (k5_3*ne*nH2_v3) - (k5_4*ne*nH2_v4) - (k5_5*ne*nH2_v5) - (k5_6*ne*nH2_v6) - (k5_7*ne*nH2_v7) - (k5_8*ne*nH2_v8) - (k5_9*ne*nH2_v9))
# print('k7(production): ', (k7*ne*nH2_v0))
# print('k8(production): ', (k8*ne*nH))
# print('k11(loss): ', - (k11*ne*nH3p))
# print('k13(loss): ', - (k13*ne*nH3p))
# print('k14(production): ',(k14*ne*nHm) )
# print('k15(production): ', (k15*nH*nHm))
# print('k21(production): ', (k21*ne*nH_2s))
# print('Wall(loss): ', - ne*uB*self.Aeff/V)
# print('-----------------------------------------')
#Power balance eqn for electron 완료
dTe_dt = 2/(3*ne)*(self.pulse_power(t)/V - (Vs+2.5*Te)*ne*uB*self.Aeff/V - 3/2*Te*dne_dt - 3/2*((E1_0*k1_0*ne*nH2_v0) + (E1_1*k1_1*ne*nH2_v1) + (E1_2*k1_2*ne*nH2_v2) + (E1_3*k1_3*ne*nH2_v3) + (E1_4*k1_4*ne*nH2_v4) + (E2*k2*ne*nH2_v0) + (E3_1*k3_1*ne*nH2_v0) + (E3_2*k3_2*ne*nH2_v0) + (E3_3*k3_3*ne*nH2_v0) + (E3_4*k3_4*ne*nH2_v0) + (E3_5*k3_5*ne*nH2_v0) + (E3_6*k3_6*ne*nH2_v0) + (E4_1*k4_1*ne*nH2_v1) + (E4_2*k4_2*ne*nH2_v2) + (E4_3*k4_3*ne*nH2_v3) + (E4_4*k4_4*ne*nH2_v4) + (E4_5*k4_5*ne*nH2_v5) + (E4_6*k4_6*ne*nH2_v6) + (E4_7*k4_7*ne*nH2_v7) + (E4_8*k4_8*ne*nH2_v8) + (E5_0*k5_0*ne*nH2_v0) + (E5_1*k5_1*ne*nH2_v1) + (E5_2*k5_2*ne*nH2_v2) + (E5_3*k5_3*ne*nH2_v3) + (E5_4*k5_4*ne*nH2_v4) + (E5_5*k5_5*ne*nH2_v5) + (E5_6*k5_6*ne*nH2_v6) + (E5_7*k5_7*ne*nH2_v7) + (E5_8*k5_8*ne*nH2_v8) + (E5_9*k5_9*ne*nH2_v9) + (E6_0*k6_0*ne*nH2_v0) + (E6_1*k6_1*ne*nH2_v0) + (E6_2*k6_2*ne*nH2_v0) + (E6_3*k6_3*ne*nH2_v0) + (E6_4*k6_4*ne*nH2_v0) + (E6_5*k6_5*ne*nH2_v0) + (E6_6*k6_6*ne*nH2_v0) + (E6_7*k6_7*ne*nH2_v0) + (E6_8*k6_8*ne*nH2_v0) + (E6_9*k6_9*ne*nH2_v0) + (E7*k7*ne*nH2_v0) + (E8*k8*ne*nH) + (E9*k9*ne*nH2p) + (E11*k11*ne*nH3p) + (E12*k12*ne*nH3p) + (E13*k13*ne*nH3p) + (E14*k14*ne*nHm) + (E19*k19*ne*nH2_v0) + (E20*k20*ne*nH) + (E21*k21*ne*nH_2s)))
# print('Te: ', Te)
# print('dTe_dt: ',dTe_dt)
# print('self.pulse_power(t)/V: ',self.pulse_power(t)/V)
# print('(Vs+2.5*Te)*ne*uB*self.Aeff/V: ',-(Vs+2.5*Te)*ne*uB*self.Aeff/V)
# print('3/2*Te*dne_dt: ',-3/2*Te*dne_dt)
# print('electron energy loss: ',-3/2*((E1_0*k1_0*ne*nH2_v0) + (E1_1*k1_1*ne*nH2_v1) + (E1_2*k1_2*ne*nH2_v2) + (E1_3*k1_3*ne*nH2_v3) + (E1_4*k1_4*ne*nH2_v4) + (E2*k2*ne*nH2_v0) + (E3_1*k3_1*ne*nH2_v0) + (E3_2*k3_2*ne*nH2_v0) + (E3_3*k3_3*ne*nH2_v0) + (E3_4*k3_4*ne*nH2_v0) + (E3_5*k3_5*ne*nH2_v0) + (E3_6*k3_6*ne*nH2_v0) + (E4_1*k4_1*ne*nH2_v1) + (E4_2*k4_2*ne*nH2_v2) + (E4_3*k4_3*ne*nH2_v3) + (E4_4*k4_4*ne*nH2_v4) + (E4_5*k4_5*ne*nH2_v5) + (E4_6*k4_6*ne*nH2_v6) + (E4_7*k4_7*ne*nH2_v7) + (E4_8*k4_8*ne*nH2_v8) + (E5_0*k5_0*ne*nH2_v0) + (E5_1*k5_1*ne*nH2_v1) + (E5_2*k5_2*ne*nH2_v2) + (E5_3*k5_3*ne*nH2_v3) + (E5_4*k5_4*ne*nH2_v4) + (E5_5*k5_5*ne*nH2_v5) + (E5_6*k5_6*ne*nH2_v6) + (E5_7*k5_7*ne*nH2_v7) + (E5_8*k5_8*ne*nH2_v8) + (E5_9*k5_9*ne*nH2_v9) + (E6_0*k6_0*ne*nH2_v0) + (E6_1*k6_1*ne*nH2_v0) + (E6_2*k6_2*ne*nH2_v0) + (E6_3*k6_3*ne*nH2_v0) + (E6_4*k6_4*ne*nH2_v0) + (E6_5*k6_5*ne*nH2_v0) + (E6_6*k6_6*ne*nH2_v0) + (E6_7*k6_7*ne*nH2_v0) + (E6_8*k6_8*ne*nH2_v0) + (E6_9*k6_9*ne*nH2_v0) + (E7*k7*ne*nH2_v0) + (E8*k8*ne*nH) + (E9*k9*ne*nH2p) + (E11*k11*ne*nH3p) + (E12*k12*ne*nH3p) + (E13*k13*ne*nH3p) + (E14*k14*ne*nHm) + (E19*k19*ne*nH2_v0) + (E20*k20*ne*nH) + (E21*k21*ne*nH_2s)))
# print('-----------------------------------------')
#Particle balance eqn for other species except electron 완료
dnH_dt = 2*(k2*ne*nH2_v0) + (k5_0*ne*nH2_v0) + (k5_1*ne*nH2_v1) + (k5_2*ne*nH2_v2) + (k5_3*ne*nH2_v3) + (k5_4*ne*nH2_v4) + (k5_5*ne*nH2_v5) + (k5_6*ne*nH2_v6) + (k5_7*ne*nH2_v7) + (k5_8*ne*nH2_v8) + (k5_9*ne*nH2_v9) + (k7*ne*nH2_v0) - (k8*ne*nH) + (k9*ne*nH2p) + (k10*nH2p*nH2_v0) + (k11*ne*nH3p) + 2*(k12*ne*nH3p) + (k14*ne*nHm) - (k15*nH*nHm) + (k16*nHp*nHm) + (k17*nH2p*nHm) + 2*(k18*nH3p*nHm) + (k19*ne*nH2_v0) - (k20*ne*nH) - (k23*nH) + (k24*nHp) + (k26*nH3p) + (k27*nH_2s) #완료
dnH_2s_dt = (k16*nHp*nHm) + (k19*ne*nH2_v0) + (k20*ne*nH) - (k21*ne*nH_2s) - (k27*nH_2s) #완료
dnH2_v1_dt = - (k1_1*ne*nH2_v1) + (k3_1*ne*nH2_v0) - (k5_1*ne*nH2_v1) + (k6_1*ne*nH2_v0) - (k22_1_0*nH*nH2_v1) + (k22_9_1*nH*nH2_v9) + (k22_9_1*nH*nH2_v9) + (k22_8_1*nH*nH2_v8) + (k22_7_1*nH*nH2_v7) + (k22_6_1*nH*nH2_v6) + (k22_5_1*nH*nH2_v5) + (k22_4_1*nH*nH2_v4) + (k22_3_1*nH*nH2_v3) + (k22_2_1*nH*nH2_v2) - (k28_1_0*nH2_v1) + (k28_9_1*nH2_v9) + (k28_8_1*nH2_v8) + (k28_7_1*nH2_v7) + (k28_6_1*nH2_v6) + (k28_5_1*nH2_v5) + (k28_4_1*nH2_v4) + (k28_3_1*nH2_v3) + (k28_2_1*nH2_v2) #완료
dnH2_v2_dt = - (k1_2*ne*nH2_v2) + (k3_2*ne*nH2_v0) + (k4_1*ne*nH2_v1) - (k5_2*ne*nH2_v2) + (k6_2*ne*nH2_v0) - (k22_2_0*nH*nH2_v2) - (k22_2_1*nH*nH2_v2) + (k22_9_2*nH*nH2_v9) + (k22_8_2*nH*nH2_v8) + (k22_7_2*nH*nH2_v7) + (k22_6_2*nH*nH2_v6) + (k22_5_2*nH*nH2_v5) + (k22_4_2*nH*nH2_v4) + (k22_3_2*nH*nH2_v3) - (k28_2_0*nH2_v2) - (k28_2_1*nH2_v2) + (k28_9_2*nH2_v9) + (k28_8_2*nH2_v8) + (k28_7_2*nH2_v7) + (k28_6_2*nH2_v6) + (k28_5_2*nH2_v5) + (k28_4_2*nH2_v4) + (k28_3_2*nH2_v3) #완료
dnH2_v3_dt = - (k1_3*ne*nH2_v3) + (k3_3*ne*nH2_v0) + (k4_2*ne*nH2_v2) - (k5_3*ne*nH2_v3) + (k6_3*ne*nH2_v0) - (k22_3_0*nH*nH2_v3) - (k22_3_1*nH*nH2_v3) - (k22_3_2*nH*nH2_v3) + (k22_9_3*nH*nH2_v9) + (k22_8_3*nH*nH2_v8) + (k22_7_3*nH*nH2_v7) + (k22_6_3*nH*nH2_v6) + (k22_5_3*nH*nH2_v5) + (k22_4_3*nH*nH2_v4) - (k28_3_0*nH2_v3) - (k28_3_1*nH2_v3) - (k28_3_2*nH2_v3) + (k28_9_3*nH2_v9) + (k28_8_3*nH2_v8) + (k28_7_3*nH2_v7) + (k28_6_3*nH2_v6) + (k28_5_3*nH2_v5) + (k28_4_3*nH2_v4) #완료
dnH2_v4_dt = - (k1_4*ne*nH2_v4) + (k3_4*ne*nH2_v0) + (k4_3*ne*nH2_v3) - (k5_4*ne*nH2_v4) + (k6_4*ne*nH2_v0) - (k22_4_0*nH*nH2_v4) - (k22_4_1*nH*nH2_v4) - (k22_4_2*nH*nH2_v4) - (k22_4_3*nH*nH2_v4) + (k22_9_4*nH*nH2_v9) + (k22_8_4*nH*nH2_v8) + (k22_7_4*nH*nH2_v7) + (k22_6_4*nH*nH2_v6) + (k22_5_4*nH*nH2_v5) - (k28_4_0*nH2_v4) - (k28_4_1*nH2_v4) - (k28_4_2*nH2_v4) - (k28_4_3*nH2_v4) + (k28_9_4*nH2_v9) + (k28_8_4*nH2_v8) + (k28_7_4*nH2_v7) + (k28_6_4*nH2_v6) + (k28_5_4*nH2_v5) #완료
dnH2_v5_dt = (k3_5*ne*nH2_v0) + (k4_4*ne*nH2_v4) - (k5_5*ne*nH2_v5) + (k6_5*ne*nH2_v0) - (k22_5_0*nH*nH2_v5) - (k22_5_1*nH*nH2_v5) - (k22_5_2*nH*nH2_v5) - (k22_5_3*nH*nH2_v5) - (k22_5_4*nH*nH2_v5) + (k22_9_5*nH*nH2_v9) + (k22_8_5*nH*nH2_v9) + (k22_7_5*nH*nH2_v9) + (k22_6_5*nH*nH2_v9) - (k28_5_0*nH2_v5) - (k28_5_1*nH2_v5) - (k28_5_2*nH2_v5) - (k28_5_3*nH2_v5) - (k28_5_4*nH2_v5) + (k28_9_5*nH2_v9) + (k28_8_5*nH2_v8) + (k28_7_5*nH2_v7) + (k28_6_5*nH2_v6) #완료
dnH2_v6_dt = (k3_6*ne*nH2_v0) + (k4_5*ne*nH2_v5) - (k5_6*ne*nH2_v6) + (k6_6*ne*nH2_v0) - (k22_6_0*nH*nH2_v6) - (k22_6_1*nH*nH2_v6) - (k22_6_2*nH*nH2_v6) - (k22_6_3*nH*nH2_v6) - (k22_6_4*nH*nH2_v6) - (k22_6_5*nH*nH2_v6) + (k22_9_6*nH*nH2_v9) + (k22_8_6*nH*nH2_v8) + (k22_7_6*nH*nH2_v7) - (k28_6_0*nH2_v6) - (k28_6_1*nH2_v6) - (k28_6_2*nH2_v6) - (k28_6_3*nH2_v6) - (k28_6_4*nH2_v6) - (k28_6_5*nH2_v6) + (k28_9_6*nH2_v9) + (k28_8_6*nH2_v8) + (k28_7_6*nH2_v7) #완료
dnH2_v7_dt = (k4_6*ne*nH2_v6) - (k5_7*ne*nH2_v7) + (k6_7*ne*nH2_v0) - (k22_7_0*nH*nH2_v7) - (k22_7_1*nH*nH2_v7) - (k22_7_2*nH*nH2_v7) - (k22_7_3*nH*nH2_v7) - (k22_7_4*nH*nH2_v7) - (k22_7_5*nH*nH2_v7) - (k22_7_6*nH*nH2_v7) + (k22_9_7*nH*nH2_v9) + (k22_8_7*nH*nH2_v8) - (k28_7_0*nH2_v7) - (k28_7_1*nH2_v7) - (k28_7_2*nH2_v7) - (k28_7_3*nH2_v7) - (k28_7_4*nH2_v7) - (k28_7_5*nH2_v7) - (k28_7_6*nH2_v7) + (k28_9_7*nH2_v9) + (k28_8_7*nH2_v8) #완료
dnH2_v8_dt = (k4_7*ne*nH2_v7) - (k5_8*ne*nH2_v8) + (k6_8*ne*nH2_v0) - (k22_8_0*nH*nH2_v8) - (k22_8_1*nH*nH2_v8) - (k22_8_2*nH*nH2_v8) - (k22_8_3*nH*nH2_v8) - (k22_8_4*nH*nH2_v8) - (k22_8_5*nH*nH2_v8) - (k22_8_6*nH*nH2_v8) - (k22_8_7*nH*nH2_v8) + (k22_9_8*nH*nH2_v9) - (k28_8_0*nH2_v8) - (k28_8_1*nH2_v8) - (k28_8_2*nH2_v8) - (k28_8_3*nH2_v8) - (k28_8_4*nH2_v8) - (k28_8_5*nH2_v8) - (k28_8_6*nH2_v8) - (k28_8_7*nH2_v8) + (k28_9_8*nH2_v9) #완료
dnH2_v9_dt = (k4_8*ne*nH2_v8) - (k5_9*ne*nH2_v9) + (k6_9*ne*nH2_v0) - (k22_9_0*nH*nH2_v9) - (k22_9_1*nH*nH2_v9) - (k22_9_2*nH*nH2_v9) - (k22_9_3*nH*nH2_v9) - (k22_9_4*nH*nH2_v9) - (k22_9_5*nH*nH2_v9) - (k22_9_6*nH*nH2_v9) - (k22_9_7*nH*nH2_v9) - (k22_9_8*nH*nH2_v9) - (k28_9_0*nH2_v9) - (k28_9_1*nH2_v9) - (k28_9_2*nH2_v9) - (k28_9_3*nH2_v9) - (k28_9_4*nH2_v9) - (k28_9_5*nH2_v9) - (k28_9_6*nH2_v9) - (k28_9_7*nH2_v9) - (k28_9_8*nH2_v9) #완료
dnHp_dt = (k7*ne*nH2_v0) + (k8*ne*nH) + (k9*ne*nH2p) + (k12*ne*nH3p) - (k16*nHp*nHm) + (k21*ne*nH_2s) - (k24*nHp) #완료
dnH2p_dt = (k1_0*ne*nH2_v0) + (k1_1*ne*nH2_v1) + (k1_2*ne*nH2_v2) + (k1_3*ne*nH2_v3) + (k1_4*ne*nH2_v4) - (k9*ne*nH2p) - (k10*nH2p*nH2_v0) + (k13*ne*nH3p) - (k17*nH2p*nHm) - (k25*nH2p) #완료
dnH3p_dt = (k10*nH2p*nH2_v0) - (k11*ne*nH3p) - (k12*ne*nH3p) - (k13*ne*nH3p) - (k18*nH3p*nHm) - (k26*nH3p) #완료
dnHm_dt = (k5_1*ne*nH2_v1) + (k5_2*ne*nH2_v2) + (k5_3*ne*nH2_v3) + (k5_4*ne*nH2_v4) + (k5_5*ne*nH2_v5) + (k5_6*ne*nH2_v6) + (k5_7*ne*nH2_v7) + (k5_8*ne*nH2_v8) + (k5_9*ne*nH2_v9) + (k13*ne*nH3p) - (k14*ne*nHm) - (k15*nH*nHm) - (k16*nHp*nHm) - (k17*nH2p*nHm) - (k18*nH3p*nHm) #완료
return np.array([dTe_dt, dnH_dt, dnH_2s_dt, dnH2_v1_dt, dnH2_v2_dt, dnH2_v3_dt, dnH2_v4_dt, dnH2_v5_dt, dnH2_v6_dt, dnH2_v7_dt, dnH2_v8_dt, dnH2_v9_dt, dnHp_dt, dnH2p_dt, dnH3p_dt, dnHm_dt])
#Pulsed power generate function
def pulse_power(self,t):
if t <= self.duty*self.period:
return self.input_power
else:
return 0
#Temperature & Density Calculation
def routine(self,init_value):
routine_result = odeint(self.balance_equations, init_value, self.routine_time_interval, args=(self.pulse_power,), rtol = 1e-4, mxstep=10**6)
return routine_result
def calculation(self):
species_list = ['Te', 'ne', 'nH', 'nH_2s', 'nH2_v0', 'nH2_v1', 'nH2_v2', 'nH2_v3', 'nH2_v4', 'nH2_v5', 'nH2_v6', 'nH2_v7', 'nH2_v8', 'nH2_v9', 'nHp', 'nH2p', 'nH3p', 'nHm']
#init_value = np.ones((16))*1e16 #[성공]
init_value = np.ones((16))*1e16 #[]
#init_value[1] = 1e20
init_value[0] = 2
print(init_value)
routine_result = self.routine(init_value)
print(routine_result)
count = 0
Hm_compare = 1
print('start_iteration')
while True:
init_value = routine_result[-1]
if not isclose(routine_result[:,15][-1], Hm_compare, rel_tol=5e-3): #iteration stop condition
if count > 100:
print('did not converge')
break
Hm_compare = routine_result[:,15][-1]
print('Hm: ',format(Hm_compare,"E"))
routine_result = self.routine(init_value)
count += 1
print(count)
continue
print('Hm: ',routine_result[:,15][-1])
print('---------calculation complete!---------')
print('iteration count : {}'.format(count))
print('---------------------------------------')
routine_result = np.transpose(routine_result)
Te, nH, nH_2s, nH2_v1, nH2_v2, nH2_v3, nH2_v4, nH2_v5, nH2_v6, nH2_v7, nH2_v8, nH2_v9, nHp, nH2p, nH3p, nHm = routine_result
ne = nHp + nH2p + nH3p - nHm
nH2_v0 = self.ng - (0.5*(nH + nHp + nH_2s + nHm) + sum(routine_result[3:12]) + nH2p + 1.5*nH3p)
break
calculation_result = np.array([Te, ne, nH, nH_2s, nH2_v0, nH2_v1, nH2_v2, nH2_v3, nH2_v4, nH2_v5, nH2_v6, nH2_v7, nH2_v8, nH2_v9, nHp, nH2p, nH3p, nHm])
return [dict(zip(species_list, calculation_result)), (self.p, self.input_power, self.duty, self.period, self.time_resolution)]
add_path = 'Our_experiment/'
duty_list=[0.5,1]
for duty in duty_list:
start = timeit.default_timer()
# [Te, ne, nH, nH_2s, nH2_v0, nH2_v1, nH2_v2, nH2_v3, nH2_v4, nH2_v5, nH2_v6, nH2_v7, nH2_v8, nH2_v9, nHp, nH2p, nH3p, nHm]
#np.seterr(all='ignore')
model = Model(10,1000,duty,1e-3,time_resolution=1e-7)
Model_Result = model.calculation()
#Result_list = Result_list.append(Model_Result)
end = timeit.default_timer()
print('Running time : {}s'.format(end-start))
graph.result_to_csv(Model_Result, add_path)
#graph.result_to_csv_select_quick(Model_Result, 'nH2_v0,nH2_v1,nH2_v2,nH2_v3,nH2_v4,nH2_v5,nH2_v6,nH2_v7,nH2_v8,nH2_v9',add_path)
#graph.result_to_csv_select_quick(Model_Result, 'nHp,nH2p,nH3p',add_path)
#graph.result_to_csv_select_quick(Model_Result, 'nH,nH_2s,nH2_v0,nH2_v1,nH2_v2',add_path)
graph.result_to_csv_select_quick(Model_Result, 'Te',add_path)
graph.result_to_csv_select_quick(Model_Result, 'ne,nHm',add_path)
graph.plot(Model_Result, 'Te', add_path, file_save = False)
graph.plot(Model_Result, 'ne', add_path, file_save = False)
graph.plot(Model_Result, 'ne,nHm', add_path, file_save = False, xlim=(400,600),ylim=(1e14,1e18))
graph.plot(Model_Result, 'alpha',add_path, file_save = False)
#graph.plot(Model_Result, 'nHm',add_path, file_save = False)
#graph.plot(Model_Result, 'ne,nHm,nHp,nH2p,nH3p',add_path, file_save = False)
#graph.plot(Model_Result, 'nH2_v0,nH2_v1,nH2_v2,nH2_v3,nH2_v4,nH2_v5,nH2_v6,nH2_v7,nH2_v8,nH2_v9',add_path, file_save = False)
#graph.plot(Model_Result, 'nH2_v0,nH2_v1,nH2_v2,nH,nH_2s',add_path, file_save = False)
###Output
Condition : 10mTorr, 1000.0W, 1.0ms, 0.5
[2.e+00 1.e+16 1.e+16 1.e+16 1.e+16 1.e+16 1.e+16 1.e+16 1.e+16 1.e+16
1.e+16 1.e+16 1.e+16 1.e+16 1.e+16 1.e+16]
[[2.00000000e+00 1.00000000e+16 1.00000000e+16 ... 1.00000000e+16
1.00000000e+16 1.00000000e+16]
[3.21965408e+00 1.11368290e+16 9.98762123e+15 ... 9.29232782e+15
1.06065551e+16 9.98311387e+15]
[3.98039187e+00 1.28062306e+16 1.00042494e+16 ... 8.63541010e+15
1.11566035e+16 9.96474182e+15]
...
[9.98080263e-04 2.13378419e+18 1.94560112e+12 ... 8.36210433e-01
1.45358395e+15 5.20703453e+13]
[9.97705177e-04 2.13333241e+18 1.94165227e+12 ... 8.36054173e-01
1.45329356e+15 5.20615457e+13]
[9.97330303e-04 2.13288073e+18 1.93771174e+12 ... 8.35897962e-01
1.45300326e+15 5.20527493e+13]]
start_iteration
Hm: 5.205275E+13
1
Hm: 4.625440E+13
2
Hm: 4.585150E+13
3
Hm: 45872373376528.02
---------calculation complete!---------
iteration count : 3
---------------------------------------
Running time : 29.066257099999802s
|
Iris dataset/.ipynb_checkpoints/Iris-Jupyter file-checkpoint.ipynb | ###Markdown
Iris Dataset Labels :Iris Setosa, Iris Versicolour, andIris Virginica
###Code
# from RadViz import main
from RadViz.main import RadViz2D
from RadViz.main import RadViz3D
import pandas as pd
import time
import plotly.io as pio
pio.renderers.default='iframe'
data= pd.read_csv('iris.csv')
y=data['Species']
X=data.drop(['Species'], axis=1)
BPs=10000
time_start = time.time()
RadViz3D(y,X,BPs)
print( 'RadViz3D done! Time elapsed: {} seconds'.format(time.time()-time_start))
BPs=1000
time_start = time.time()
RadViz2D(y,X,BPs)
print( 'RadViz2D done! Time elapsed: {} seconds'.format(time.time()-time_start))
###Output
_____no_output_____ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.