markdown
stringlengths 0
37k
| code
stringlengths 1
33.3k
| path
stringlengths 8
215
| repo_name
stringlengths 6
77
| license
stringclasses 15
values |
---|---|---|---|---|
Build RNN Cell and Initialize
Stack one or more BasicLSTMCells in a MultiRNNCell.
- The Rnn size should be set using rnn_size
- Initalize Cell State using the MultiRNNCell's zero_state() function
- Apply the name "initial_state" to the initial state using tf.identity()
Return the cell and initial state in the following tuple (Cell, InitialState) | def get_init_cell(batch_size, rnn_size):
"""
Create an RNN Cell and initialize it.
:param batch_size: Size of batches
:param rnn_size: Size of RNNs
:return: Tuple (cell, initialize state)
"""
# TODO: Implement Function
lstm = tf.contrib.rnn.BasicLSTMCell(rnn_size)
# Add dropout to the cell
# drop = tf.contrib.rnn.DropoutWrapper(lstm, output_keep_prob=keep_prob)
# Stack up multiple LSTM layers, for deep learning
lstm_layers = 5
cell = tf.contrib.rnn.MultiRNNCell([lstm] * lstm_layers)
# Getting an initial state of all zeros
initial_state = cell.zero_state(batch_size, tf.float32)
return cell, tf.identity(initial_state,name='initial_state')
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_get_init_cell(get_init_cell) | tv-script-generation/dlnd_tv_script_generation.ipynb | zhuanxuhit/deep-learning | mit |
Word Embedding
Apply embedding to input_data using TensorFlow. Return the embedded sequence. | def get_embed(input_data, vocab_size, embed_dim):
"""
Create embedding for <input_data>.
:param input_data: TF placeholder for text input.
:param vocab_size: Number of words in vocabulary.
:param embed_dim: Number of embedding dimensions
:return: Embedded input.
"""
# TODO: Implement Function
embedding = tf.Variable(tf.random_uniform((vocab_size, embed_dim), -1, 1))
embed = tf.nn.embedding_lookup(embedding, input_data)
return embed
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_get_embed(get_embed) | tv-script-generation/dlnd_tv_script_generation.ipynb | zhuanxuhit/deep-learning | mit |
Build RNN
You created a RNN Cell in the get_init_cell() function. Time to use the cell to create a RNN.
- Build the RNN using the tf.nn.dynamic_rnn()
- Apply the name "final_state" to the final state using tf.identity()
Return the outputs and final_state state in the following tuple (Outputs, FinalState) | def build_rnn(cell, inputs):
"""
Create a RNN using a RNN Cell
:param cell: RNN Cell
:param inputs: Input text data
:return: Tuple (Outputs, Final State)
"""
outputs, final_state = tf.nn.dynamic_rnn(cell, inputs,dtype=tf.float32)
return outputs, tf.identity(final_state,name="final_state")
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_build_rnn(build_rnn) | tv-script-generation/dlnd_tv_script_generation.ipynb | zhuanxuhit/deep-learning | mit |
Build the Neural Network
Apply the functions you implemented above to:
- Apply embedding to input_data using your get_embed(input_data, vocab_size, embed_dim) function.
- Build RNN using cell and your build_rnn(cell, inputs) function.
- Apply a fully connected layer with a linear activation and vocab_size as the number of outputs.
Return the logits and final state in the following tuple (Logits, FinalState) | def build_nn(cell, rnn_size, input_data, vocab_size, embed_dim):
"""
Build part of the neural network
:param cell: RNN cell
:param rnn_size: Size of rnns
:param input_data: Input data
:param vocab_size: Vocabulary size
:param embed_dim: Number of embedding dimensions
:return: Tuple (Logits, FinalState)
"""
# TODO: Implement Function
embed_dim = 300;
embed = get_embed(input_data,vocab_size,embed_dim)
outputs, final_state = build_rnn(cell,embed)
# print(outputs) # Tensor("rnn/transpose:0", shape=(128, 5, 256), dtype=float32)
# print(final_state) # Tensor("final_state:0", shape=(2, 2, ?, 256), dtype=float32)
# !!! it is really import to have a good weigh init
logits = tf.contrib.layers.fully_connected(outputs,vocab_size,activation_fn=None, #tf.nn.relu
weights_initializer = tf.truncated_normal_initializer(stddev=0.1),
biases_initializer=tf.zeros_initializer())
# print(logits) # Tensor("fully_connected/Relu:0", shape=(128, 5, 27), dtype=float32)
return logits, final_state
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_build_nn(build_nn) | tv-script-generation/dlnd_tv_script_generation.ipynb | zhuanxuhit/deep-learning | mit |
Batches
Implement get_batches to create batches of input and targets using int_text. The batches should be a Numpy array with the shape (number of batches, 2, batch size, sequence length). Each batch contains two elements:
- The first element is a single batch of input with the shape [batch size, sequence length]
- The second element is a single batch of targets with the shape [batch size, sequence length]
If you can't fill the last batch with enough data, drop the last batch.
For exmple, get_batches([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], 3, 2) would return a Numpy array of the following:
```
[
# First Batch
[
# Batch of Input
[[ 1 2], [ 7 8], [13 14]]
# Batch of targets
[[ 2 3], [ 8 9], [14 15]]
]
# Second Batch
[
# Batch of Input
[[ 3 4], [ 9 10], [15 16]]
# Batch of targets
[[ 4 5], [10 11], [16 17]]
]
# Third Batch
[
# Batch of Input
[[ 5 6], [11 12], [17 18]]
# Batch of targets
[[ 6 7], [12 13], [18 1]]
]
]
```
Notice that the last target value in the last batch is the first input value of the first batch. In this case, 1. This is a common technique used when creating sequence batches, although it is rather unintuitive. | # 根据建议修改的方法,很赞!
def get_batches(int_text, batch_size, seq_length):
n_batches = int(len(int_text) / (batch_size * seq_length))
x_data = np.array(int_text[: n_batches * batch_size * seq_length])
y_data = np.array(int_text[1: n_batches * batch_size * seq_length + 1])
x = np.split(xdata.reshape(batch_size, -1), n_batches, 1)
y = np.split(ydata.reshape(batch_size, -1), n_batches, 1)
return np.array(list(zip(x, y)))
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_get_batches(get_batches)
# def get_batches(int_text, batch_size, seq_length):
# """
# Return batches of input and target
# :param int_text: Text with the words replaced by their ids
# :param batch_size: The size of batch
# :param seq_length: The length of sequence
# :return: Batches as a Numpy array
# """
# # TODO: Implement Function
# batches = []
# n_batchs = (len(int_text)-1) // (batch_size * seq_length)
# # int_text = int_text[:n_batchs*batch_size * seq_length+1]
# for i in range(0,n_batchs*seq_length,seq_length):
# x = []
# y = []
# for j in range(i,i+batch_size * seq_length,seq_length):
# x.append(int_text[j:j+seq_length])
# y.append(int_text[j+1:j+1+seq_length])
# batches.append([x,y])
# return np.array(batches)
# #print(get_batches([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], 2, 3))
# """
# DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
# """
# tests.test_get_batches(get_batches) | tv-script-generation/dlnd_tv_script_generation.ipynb | zhuanxuhit/deep-learning | mit |
Neural Network Training
Hyperparameters
Tune the following parameters:
Set num_epochs to the number of epochs.
Set batch_size to the batch size.
Set rnn_size to the size of the RNNs.
Set embed_dim to the size of the embedding.
Set seq_length to the length of sequence.
Set learning_rate to the learning rate.
Set show_every_n_batches to the number of batches the neural network should print progress. | # 4257 line ,average 11 words
# Number of Epochs
num_epochs = 50
# Batch Size
batch_size = 200
# RNN Size
rnn_size = None
# Embedding Dimension Size
embed_dim = None
# Sequence Length
seq_length = 10 # !!! when i increase the seq_length from 5 to 10,it really helps,如果继续增加会怎么样呢?
# Learning Rate
learning_rate = 0.01
# Show stats for every n number of batches
show_every_n_batches = 40
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
save_dir = './save' | tv-script-generation/dlnd_tv_script_generation.ipynb | zhuanxuhit/deep-learning | mit |
Build the Graph
Build the graph using the neural network you implemented. | """
DON'T MODIFY ANYTHING IN THIS CELL
"""
from tensorflow.contrib import seq2seq
train_graph = tf.Graph()
with train_graph.as_default():
vocab_size = len(int_to_vocab)
input_text, targets, lr = get_inputs()
input_data_shape = tf.shape(input_text)
# input_data_shape[0] batch size
cell, initial_state = get_init_cell(input_data_shape[0], rnn_size)
logits, final_state = build_nn(cell, rnn_size, input_text, vocab_size, embed_dim)
# Probabilities for generating words
probs = tf.nn.softmax(logits, name='probs')
# Loss function
cost = seq2seq.sequence_loss(
logits,
targets,
tf.ones([input_data_shape[0], input_data_shape[1]]))
# Optimizer
optimizer = tf.train.AdamOptimizer(lr)
# Gradient Clipping
gradients = optimizer.compute_gradients(cost)
capped_gradients = [(tf.clip_by_value(grad, -1., 1.), var) for grad, var in gradients if grad is not None]
train_op = optimizer.apply_gradients(capped_gradients) | tv-script-generation/dlnd_tv_script_generation.ipynb | zhuanxuhit/deep-learning | mit |
Implement Generate Functions
Get Tensors
Get tensors from loaded_graph using the function get_tensor_by_name(). Get the tensors using the following names:
- "input:0"
- "initial_state:0"
- "final_state:0"
- "probs:0"
Return the tensors in the following tuple (InputTensor, InitialStateTensor, FinalStateTensor, ProbsTensor) | def get_tensors(loaded_graph):
"""
Get input, initial state, final state, and probabilities tensor from <loaded_graph>
:param loaded_graph: TensorFlow graph loaded from file
:return: Tuple (InputTensor, InitialStateTensor, FinalStateTensor, ProbsTensor)
"""
# TODO: Implement Function
return loaded_graph.get_tensor_by_name("input:0"), loaded_graph.get_tensor_by_name("initial_state:0"), loaded_graph.get_tensor_by_name("final_state:0"), loaded_graph.get_tensor_by_name("probs:0")
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_get_tensors(get_tensors) | tv-script-generation/dlnd_tv_script_generation.ipynb | zhuanxuhit/deep-learning | mit |
Choose Word
Implement the pick_word() function to select the next word using probabilities. | import random
def pick_word(probabilities, int_to_vocab):
"""
Pick the next word in the generated text
:param probabilities: Probabilites of the next word
:param int_to_vocab: Dictionary of word ids as the keys and words as the values
:return: String of the predicted word
"""
# TODO: Implement Function
r = random.uniform(0,1)
#store prediction char
s = 0
#since length > indices starting at 0
char_id = len(probabilities) - 1
#for each char prediction probabilty
for i in range(len(probabilities)):
#assign it to S
s += probabilities[i]
#check if probability greater than our randomly generated one
if s >= r:
#if it is, thats the likely next char
char_id = i
break
return int_to_vocab[char_id]
# 另一种简单方法,对于为什么这么选择,可以参考一篇文章:
# http://yanyiwu.com/work/2014/01/30/simhash-shi-xian-xiang-jie.html
rand = np.sum(probabilities) * np.random.rand(1)
pred_word = int_to_vocab[int(np.searchsorted(np.cumsum(probabilities), rand))]
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
tests.test_pick_word(pick_word) | tv-script-generation/dlnd_tv_script_generation.ipynb | zhuanxuhit/deep-learning | mit |
Generate TV Script
This will generate the TV script for you. Set gen_length to the length of TV script you want to generate. | gen_length = 200
# homer_simpson, moe_szyslak, or Barney_Gumble
prime_word = 'moe_szyslak'
"""
DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE
"""
loaded_graph = tf.Graph()
with tf.Session(graph=loaded_graph) as sess:
# Load saved model
loader = tf.train.import_meta_graph(load_dir + '.meta')
loader.restore(sess, load_dir)
# Get Tensors from loaded model
input_text, initial_state, final_state, probs = get_tensors(loaded_graph)
# Sentences generation setup
gen_sentences = [prime_word + ':']
prev_state = sess.run(initial_state, {input_text: np.array([[1]])})
# Generate sentences
for n in range(gen_length):
# Dynamic Input
dyn_input = [[vocab_to_int[word] for word in gen_sentences[-seq_length:]]]
dyn_seq_length = len(dyn_input[0])
# Get Prediction
probabilities, prev_state = sess.run(
[probs, final_state],
{input_text: dyn_input, initial_state: prev_state})
pred_word = pick_word(probabilities[dyn_seq_length-1], int_to_vocab)
gen_sentences.append(pred_word)
# Remove tokens
tv_script = ' '.join(gen_sentences)
for key, token in token_dict.items():
ending = ' ' if key in ['\n', '(', '"'] else ''
tv_script = tv_script.replace(' ' + token.lower(), key)
tv_script = tv_script.replace('\n ', '\n')
tv_script = tv_script.replace('( ', '(')
print(tv_script) | tv-script-generation/dlnd_tv_script_generation.ipynb | zhuanxuhit/deep-learning | mit |
# Overall Summary | daily_stats[['count_click', 'count_booking_train', 'count_booking_test']].sum()/1000
print 'booking ratio for train set: ', daily_stats.count_booking_train.sum() * 1.0 \
/ (daily_stats.count_click.sum() + daily_stats.count_booking_train.sum())
print 'daily booking in train set: ', daily_stats.count_booking_train.sum() * 1.0 \
/ len(daily_stats[daily_stats.count_booking_train != 0])
print 'daily click in train set: ', daily_stats.count_click.sum() * 1.0 \
/ len(daily_stats[daily_stats.count_click != 0])
print 'daily booking in test set: ', daily_stats.count_booking_test.sum() * 1.0 \
/ len(daily_stats[daily_stats.count_booking_test != 0]) | notebooks/time_based_anlaysis.ipynb | parkerzf/kaggle-expedia | bsd-3-clause |
Monthly stats | monthly_number_stats_booking_train = (daily_stats.groupby(("year", "month"))["count_booking_train"].sum()/1000)
monthly_number_stats_click_train = (daily_stats.groupby(("year", "month"))["count_click"].sum()/1000)
monthly_number_stats_booking_test = (daily_stats.groupby(("year", "month"))["count_booking_test"].sum()/1000)
fig = monthly_number_stats_booking_train.plot(kind='bar', alpha=0.5, figsize=(14, 8))
monthly_number_stats_click_train.plot(kind='bar', alpha=0.3, color = 'r', figsize=(14, 8))
monthly_number_stats_booking_test.plot(kind='bar', alpha=0.5, color = 'y', figsize=(14, 8))
fig.legend()
fig.set_title("Total Booking per Month")
fig.set_ylabel("Thousands of Bookings/Clicks")
fig.set_xlabel("(Year , Month)" ) | notebooks/time_based_anlaysis.ipynb | parkerzf/kaggle-expedia | bsd-3-clause |
Daily stats -- weekdays | import locale, calendar
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
fig, axes = plt.subplots(nrows=1, ncols=2)
fig.tight_layout()
fig.set_size_inches(18.5,5.5)
dow = map(lambda x: calendar.day_abbr[x].capitalize(), daily_stats.index.dayofweek)
dow_order = map(lambda x: calendar.day_abbr[x].capitalize(), np.arange(0,7))
sns.boxplot(daily_stats.count_booking/1000, groupby=dow, order=dow_order, ax=axes[0])
axes[0].set_title("Total number of bookings by Week day")
axes[0].set_ylabel("Nubmer of bookings (Thousands)")
dow_clicks = map(lambda x: calendar.day_abbr[x].capitalize(), daily_stats[daily_stats.count_click!=0].index.dayofweek)
dow_clicks_order = map(lambda x: calendar.day_abbr[x].capitalize(), np.arange(0,7))
sns.boxplot(daily_stats[daily_stats.count_click!=0].count_click/1000., groupby=dow_clicks, order=dow_clicks_order, ax=axes[1])
axes[1].set_title("Total number of clicks by Week day")
axes[1].set_ylabel("Nubmer of clicks (Thousands)") | notebooks/time_based_anlaysis.ipynb | parkerzf/kaggle-expedia | bsd-3-clause |
There are weekly pattern in booking time, high from Monday to Fri, low in the Friday and weekend.
Monthly stats (Checkin and Checkout) | table = 'public.srch_ci_daily_stats'
daily_stats_ci = get_dataframe(
'''select * from %s where year between 2013 and 2016''' % table
)
daily_stats_ci.index = pd.to_datetime(daily_stats_ci.year*10000 + daily_stats_ci.month*100 + daily_stats_ci.day, format='%Y%m%d')
table = 'public.srch_co_daily_stats'
daily_stats_co = get_dataframe(
'''select * from %s where year between 2013 and 2016''' % table
)
daily_stats_co.index = pd.to_datetime(daily_stats_co.year*10000 + daily_stats_co.month*100 + daily_stats_co.day, format='%Y%m%d')
monthly_number_stats_ci_booking_train = (daily_stats_ci.groupby(("year", "month"))["count_booking_train"].sum()/1000)
monthly_number_stats_ci_click_train = (daily_stats_ci.groupby(("year", "month"))["count_click"].sum()/1000)
monthly_number_stats_ci_booking_test = (daily_stats_ci.groupby(("year", "month"))["count_booking_test"].sum()/1000)
monthly_number_stats_co_booking_train = (daily_stats_co.groupby(("year", "month"))["count_booking_train"].sum()/1000)
monthly_number_stats_co_click_train = (daily_stats_co.groupby(("year", "month"))["count_click"].sum()/1000)
monthly_number_stats_co_booking_test = (daily_stats_co.groupby(("year", "month"))["count_booking_test"].sum()/1000)
fig = monthly_number_stats_ci_booking_train.plot(kind='bar', alpha=0.5, figsize=(14, 8))
monthly_number_stats_ci_click_train.plot(kind='bar', alpha=0.3, color = 'r', figsize=(14, 8))
monthly_number_stats_ci_booking_test.plot(kind='bar', alpha=0.5, color = 'y', figsize=(14, 8))
fig.legend()
fig.set_title("Total Booking per Month (Checkin)")
fig.set_ylabel("Thousands of Bookings/Clicks")
fig.set_xlabel("(Year , Month)" )
fig = monthly_number_stats_co_booking_train.plot(kind='bar', alpha=0.5, figsize=(14, 8))
monthly_number_stats_co_click_train.plot(kind='bar', alpha=0.3, color = 'r', figsize=(14, 8))
monthly_number_stats_co_booking_test.plot(kind='bar', alpha=0.5, color = 'y', figsize=(14, 8))
fig.legend()
fig.set_title("Total Booking per Month (Checkout)")
fig.set_ylabel("Thousands of Bookings/Clicks")
fig.set_xlabel("(Year , Month)" ) | notebooks/time_based_anlaysis.ipynb | parkerzf/kaggle-expedia | bsd-3-clause |
Daily stats -- weekdays (Checkin and Checkout) | import locale, calendar
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
fig, axes = plt.subplots(nrows=1, ncols=2)
fig.tight_layout()
fig.set_size_inches(18.5,5.5)
dow = map(lambda x: calendar.day_abbr[x].capitalize(), daily_stats_ci.index.dayofweek)
dow_order = map(lambda x: calendar.day_abbr[x].capitalize(), np.arange(0,7))
sns.boxplot(daily_stats_ci.count_booking/1000, groupby=dow, order=dow_order, ax=axes[0])
axes[0].set_title("Total number of bookings by Week day (Checkin)")
axes[0].set_ylabel("Nubmer of bookings (Thousands)")
dow_clicks = map(lambda x: calendar.day_abbr[x].capitalize(), daily_stats_ci[daily_stats_ci.count_click!=0].index.dayofweek)
dow_clicks_order = map(lambda x: calendar.day_abbr[x].capitalize(), np.arange(0,7))
sns.boxplot(daily_stats_ci[daily_stats_ci.count_click!=0].count_click/1000., groupby=dow_clicks, order=dow_clicks_order, ax=axes[1])
axes[1].set_title("Total number of clicks by Week day(Checkin)")
axes[1].set_ylabel("Nubmer of clicks (Thousands)")
import locale, calendar
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
fig, axes = plt.subplots(nrows=1, ncols=2)
fig.tight_layout()
fig.set_size_inches(18.5,5.5)
dow = map(lambda x: calendar.day_abbr[x].capitalize(), daily_stats_co.index.dayofweek)
dow_order = map(lambda x: calendar.day_abbr[x].capitalize(), np.arange(0,7))
sns.boxplot(daily_stats_co.count_booking/1000, groupby=dow, order=dow_order, ax=axes[0])
axes[0].set_title("Total number of bookings by Week day (Checkout)")
axes[0].set_ylabel("Nubmer of bookings (Thousands)")
dow_clicks = map(lambda x: calendar.day_abbr[x].capitalize(), daily_stats_co[daily_stats_co.count_click!=0].index.dayofweek)
dow_clicks_order = map(lambda x: calendar.day_abbr[x].capitalize(), np.arange(0,7))
sns.boxplot(daily_stats_co[daily_stats_co.count_click!=0].count_click/1000., groupby=dow_clicks, order=dow_clicks_order, ax=axes[1])
axes[1].set_title("Total number of clicks by Week day(Checkout)")
axes[1].set_ylabel("Nubmer of clicks (Thousands)") | notebooks/time_based_anlaysis.ipynb | parkerzf/kaggle-expedia | bsd-3-clause |
Data is always a numpy array (or sparse matrix) of shape (n_samples, n_features)
Split the data to get going | from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(digits.data,
digits.target, test_size=0.25, random_state=1)
digits.data.shape
X_train.shape
X_test.shape | notebooks/00 - Data Loading.ipynb | amueller/odsc-masterclass-2017-morning | mit |
Exercises
Load the iris dataset from the sklearn.datasets module using the load_iris function.
The function returns a dictionary-like object that has the same attributes as digits.
What is the number of classes, features and data points in this dataset?
Use a scatterplot to visualize the dataset.
You can look at DESCR attribute to learn more about the dataset.
Usually data doesn't come in that nice a format. You can find the csv file that contains the iris dataset at the following path:
python
import sklearn.datasets
import os
iris_path = os.path.join(sklearn.datasets.__path__[0], 'data', 'iris.csv')
Try loading the data from there using pandas pd.read_csv method. | # %load solutions/load_iris.py | notebooks/00 - Data Loading.ipynb | amueller/odsc-masterclass-2017-morning | mit |
Phone number parser
Mentioned in the tutorial
Grammer:
- number :: '0'.. '9'*
- phoneNumber :: [ '(' number ')' ] number '-' number | #Definitions of literals
dash = Literal( "-" )
lparen = Literal( "(" )
rparen = Literal( ")" )
#Variable lengths and patterns of number => Word token
digits = "0123456789"
number = Word( digits )
#Define phone number with And (+'s)
#Literals can also be defined with direct strings
phoneNumber = lparen + number + rparen + number + dash + number
#Create a results name for easy access
areacode = number.setResultsName("areacode")
#Make the area code optional
phoneNumber = Optional( "(" + areacode + ")" ) + number + "-" + number
#List of phone numbers
phoneNumberList = OneOrMore( phoneNumber )
#Using the grammer
inputString = "(978) 844-0961"
data = phoneNumber.parseString( inputString )
data.areacode
#Bad input
inputStringBad = "978) 844-0961"
data2 = phoneNumber.parseString( inputStringBad ) | ML-SQL/Pyparsing tutorial.ipynb | neeasthana/ML-SQL | gpl-3.0 |
Chemical Formula parser
Mentioned in the tutorial
Grammer
- integer :: '0'..'9'+
- cap :: 'A'..'Z'
- lower :: 'a'..'z'
- elementSymbol :: cap lower*
- elementRef :: elementSymbol [ integer ]
- formula :: elementRef+ | #Define Grammer
caps = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
lowers = caps.lower()
digits = "0123456789"
element = Word( caps, lowers )
#Groups elements so that element and numbers appear together
elementRef = Group( element + Optional( Word( digits ), default="1" ) )
formula = OneOrMore( elementRef )
testString = "CO2"
elements = formula.parseString( testString )
print(elements)
tests = [ "H2O", "C6H5OH", "NaCl" ]
for t in tests:
try:
results = formula.parseString( t )
print (t,"->", results)
except ParseException as pe:
print (pe)
else:
wt = sum( [atomicWeight[elem]*int(qty) for elem,qty in results] )
print ("(%.3f)" % wt) | ML-SQL/Pyparsing tutorial.ipynb | neeasthana/ML-SQL | gpl-3.0 |
Burgers Equation
Burgers’ equation is a partial differential equation that was originally proposed as a simplified model of turbulence as exhibited by the full-fledged Navier-Stokes equations. It is a nonlinear equation for which exact solutions are known and is therefore important as a benchmark problem for numerical methods. More Refrence
<br>
Here is the differential Equation we are trying to solve
$\begin{array}{l}
\ \ \ u_t + u u_x - (0.01/\pi) u_{xx} = 0,\ \ \ x \in [-1,1],\ \ \ t \in [0,1]
\end{array}$
<br>
Here are the initial conditions
$\ \ \ u(x, 0) = -\sin(\pi x),$
$\ \ \ u(-1, t) = u(1, t) = 0.0$
<br>
Now let us define:
$
\ \ \ f := u_t + u u_x - (0.01/\pi) u_{xx},
$
and we approximate $u(x, t)$ using Neural Network as $NN(\theta, x, t)$ where $\theta$ are the weights of neural networks
<br>
</br>
Now here are the three main data points that will be used for training our Neural Network to approximate $u(x,t)$
We will train points lying between $x \in [-1,1]$ and $t=0$ to follow as part of the L2 Loss
$min\ \ _\theta \ \ (NN(\theta, x, t) + \sin(\pi x))^2$
<br>
We will train points lying between $t \in [0,1]$ and $x= \pm1 $ as part of the L2 Loss
$min\ \ _\theta \ \ (NN(\theta, x, t) + \sin(\pi x))^2$
<br>
We will train points lying between $x \in [-1,1],\ \ \ t \in [0,1]$ as part of the regulariser loss
$f(\theta, x, t):= \ \ \frac{\partial NN(\theta, x, t)}{\partial t} + NN(\theta, x, t)\frac{\partial NN(\theta, x, t)}{\partial x} - (0.01/\pi)\frac{\partial^2 NN(\theta, x, t)}{\partial^2 x} $
$min\ \ _\theta \ \ f(\theta, x, t)$
</br>
In this tutorial, we will be combing data conditions 1 and 2 under the same L2Loss
Data Visualisation of the Burgers Equation
Now lets load the Burger's Data provided from the author. pre_process_shock_data is used to load the data in a format suitable for Neural Networks. Understanding this function is not neccesary for working through the tutorials. | ## Data Preprocessing
# Create Dataset
import scipy.io
from scipy.interpolate import griddata
from pyDOE import lhs
import numpy as np
import random
random.seed(0)
np.random.seed(0)
def pre_process_shock_data(N_u, N_f, t, x, Exact):
X, T = np.meshgrid(x,t)
X_star = np.hstack((X.flatten()[:,None], T.flatten()[:,None]))
u_star = Exact.flatten()[:,None]
# Doman bounds
lb = X_star.min(0)
ub = X_star.max(0)
xx1 = np.hstack((X[0:1,:].T, T[0:1,:].T))
uu1 = Exact[0:1,:].T
xx2 = np.hstack((X[:,0:1], T[:,0:1]))
uu2 = Exact[:,0:1]
xx3 = np.hstack((X[:,-1:], T[:,-1:]))
uu3 = Exact[:,-1:]
X_u_train = np.vstack([xx1, xx2, xx3])
X_f_train = lb + (ub-lb)*lhs(2, N_f)
X_f_train = np.vstack((X_f_train, X_u_train))
u_train = np.vstack([uu1, uu2, uu3])
idx = np.random.choice(X_u_train.shape[0], N_u, replace=False)
X_u_train = X_u_train[idx, :]
u_train = u_train[idx,:]
return X_u_train, u_train, X_f_train, X_star, (X, T)
mat_data = scipy.io.loadmat(os.path.join(os.getcwd(), 'PINNs/burgers_shock.mat'))
N_u = 100
N_f = 10000
t = mat_data['t'].flatten()[:,None]
x = mat_data['x'].flatten()[:,None]
Exact = np.real(mat_data['usol']).T
labeled_X, labeled_y, unlabeled_X, full_domain, meshgrid = pre_process_shock_data(N_u, N_f, t, x, Exact) | examples/tutorials/Physics_Informed_Neural_Networks.ipynb | deepchem/deepchem | mit |
We have three Numpy arrays labeled_X, labeled_y and unlabeled_X which will be used for training our neural network,
1) labeled_X consists of $x \in [-1,1]$ & $t=0$ and $t \in [0,1]$ & $x= \pm1 $. labeled_y has the value of $u(x, t)$:
Let us verify that labeled_X & labeled_y also consists of data points satisfying the condition of
$\ \ \ u(x, 0) = -\sin(\pi x), \quad \quad x \in [-1,1]$ & $t=0$ | import matplotlib.pyplot as plt
ind = labeled_X[:, 1] == 0.0
print(f"Number of Datapoints with with t = 0 is {len(labeled_X[labeled_X[:, 1] == 0.0])}")
plt.scatter(labeled_X[ind][:, 0], labeled_y[ind], color = 'red', marker = "o", alpha = 0.3)
| examples/tutorials/Physics_Informed_Neural_Networks.ipynb | deepchem/deepchem | mit |
Let us verify that at labeled_X & labeled_y also consists of datapoints satisfying the condition of
$\ \ \ u(-1, t) = u(1, t) = 0.0, \quad \quad t \in [0,1]$ & $x= \pm1$ | ind = np.abs(labeled_X[:, 0]) == 1.0
print(f"Number of Datapoints with with |x| = 1 is {len(labeled_X[np.abs(labeled_X[:, 0]) == 1.0])}")
np.max(labeled_y[ind]), np.min(labeled_y[ind]), np.mean(labeled_y[ind])
| examples/tutorials/Physics_Informed_Neural_Networks.ipynb | deepchem/deepchem | mit |
Explanation of the solution
We will be using Deepchem's PINNModel class to solve Burger's Equation which is based out of Jax library. We will approximate $u(x, t)$ using a Neural Network represented as $NN(\theta, x, t)$
For our purpose, we will be using the Haiku library for building neural networks. Due to the functional nature of Jax, we define neural network with two things
Parameters - which act as the weight matrices, upon which Backpropagation is applied for optimisation.
forward_fn - This defines how the weights are used for computing the outputs. Ex- Feedforward, Convolution, etc | import jax
import jax.numpy as jnp
import haiku as hk
def f(x, t):
x = jnp.hstack([x, t])
net = hk.nets.MLP(output_sizes = [20, 20, 20, 20, 20, 20, 20, 20, 1],
activation = jnp.tanh)
return net(x)
init_params, forward_fn = hk.transform(f)
rng = jax.random.PRNGKey(500)
x_init, t_init = jnp.split(labeled_X, 2, 1)
params = init_params(rng, x_init, t_init)
| examples/tutorials/Physics_Informed_Neural_Networks.ipynb | deepchem/deepchem | mit |
As per the docstrings of PINNModel, we require two additional functions in the given format -
Create a gradient_fn which tells us about how to compute the gradients of the function-
```
def gradient_fn(forward_fn, loss_outputs, initial_data):
def model_loss(params, target, weights, rng, ...):
# write code using the arguments.
# ... indicates the variable number of positional arguments.
return
return model_loss
```
And to understand more about PINNModel, you can see that the same gradient_fn gets called in the code for computing the gradients.
For our purpose, we have two variables $(x, t)$ and we need to tell the PINN Model how to compute the final gradient. For carrying out this process we will be using these main features from jax library for calculating the loss -
vmap - This for parallelising computations in batches. We will process each row of the dataset, but it will get batched automatically using this feature.
jacrev - This is used to calculate the jacobian matrix. In our case, the output is a single dimension and hence it can be thought of as the gradient function. We could directly use jax's grad function but using jacrev simplifies the array shapes and hence is easier.
We need to compute two losses for solving our differential equation-
Initial Loss
u_pred = forward_fn(params, rng, x_b, t_b)
initial_loss = jnp.mean((u_pred - boundary_target) ** 2)
Regulariser Loss
This is slightly complicated as we need to compute
$f(\theta, x, t):= \ \ \frac{\partial NN(\theta, x, t)}{\partial t} + NN(\theta, x, t)\frac{\partial NN(\theta, x, t)}{\partial x} - (0.01/\pi)\frac{\partial^2 NN(\theta, x, t)}{\partial^2 x} $
The partial derivative operation in the first and second terms can be calculated using jacrev function-
u_x, u_t = jacrev(forward_fn, argnums=(2, 3))(params, rng, x, t)
The second partial derivative operation in the third term can be applying jacrev twice-
u_xx = jacrev(jacrev(forward_fn, argnums=2), argnums=2)(params, rng, x, t) | from jax import jacrev
import functools
def gradient_fn(forward_fn, loss_outputs, initial_data):
"""
This function calls the gradient function, to implement the backpropogation
"""
boundary_data_x = initial_data['labeled_x']
boundary_data_t = initial_data['labeled_t']
boundary_target = initial_data['labeled_u']
@jax.jit
def model_loss(params, target, weights, rng, x_train, t_train):
@functools.partial(jax.vmap, in_axes=(None, 0, 0))
def small_loss(params, x, t):
u = forward_fn(params, rng, x, t)
u_x, u_t = jacrev(forward_fn, argnums=(2, 3))(params, rng, x, t)
u_xx = jacrev(jacrev(forward_fn, argnums=2), argnums=2)(params, rng, x, t)
con = 0.01/np.pi
return u_t + u * u_x - con * u_xx
u_pred = forward_fn(params, rng, boundary_data_x, boundary_data_t)
f_pred = small_loss(params, x_train, t_train)
loss_u = jnp.mean((u_pred - boundary_target) ** 2)
loss_f = jnp.mean((f_pred) ** 2)
return loss_u + loss_f
return model_loss
| examples/tutorials/Physics_Informed_Neural_Networks.ipynb | deepchem/deepchem | mit |
We also need to provide an eval_fn in the below-given format for computing the weights
```
def create_eval_fn(forward_fn, params):
def eval_model(..., rng=None):
# write code here using arguments
return
return eval_model
```
Like previously we have two arguments for our model $(x, t)$ which get passed in function | # Tells the neural network on how to perform calculation during inference
def create_eval_fn(forward_fn, params):
"""
Calls the function to evaluate the model
"""
@jax.jit
def eval_model(x, t, rng=None):
res = forward_fn(params, rng, x, t)
return jnp.squeeze(res)
return eval_model
| examples/tutorials/Physics_Informed_Neural_Networks.ipynb | deepchem/deepchem | mit |
Usage of PINN Model
We will be using optax library for performing the optimisations. PINNModel executes the codes for training the models. | import optax
from deepchem.models import PINNModel
scheduler = optax.piecewise_constant_schedule(
init_value=1e-2,
boundaries_and_scales={2500: 0.1, 5000: 0.1, 7500: 0.1})
opt = optax.chain(
optax.clip_by_global_norm(1.00),
optax.scale_by_adam(b1=0.9, b2=0.99),
optax.scale_by_schedule(scheduler),
optax.scale(-1.0))
labeled_x, labeled_t = jnp.split(labeled_X, 2, 1)
boundary_data = {
'labeled_x': labeled_x, 'labeled_t':labeled_t, 'labeled_u': labeled_y
}
j_m = PINNModel(
forward_fn = forward_fn,
params = params,
initial_data = boundary_data,
batch_size = 1000,
optimizer = opt,
grad_fn = gradient_fn,
eval_fn = create_eval_fn,
deterministic = True,
log_frequency = 1000
)
dataset = dc.data.NumpyDataset(unlabeled_X)
val = j_m.fit(dataset, nb_epochs=500)
| examples/tutorials/Physics_Informed_Neural_Networks.ipynb | deepchem/deepchem | mit |
Visualize the final results
Code taken from authors for visualisation
show both graphs | test_dataset = dc.data.NumpyDataset(full_domain)
u_pred = j_m.predict(test_dataset)
U_pred = griddata(full_domain, u_pred.flatten(), meshgrid, method='cubic')
Error = np.abs(Exact - U_pred)
import numpy as np
import matplotlib.pyplot as plt
import scipy.io
from scipy.interpolate import griddata
from mpl_toolkits.axes_grid1 import make_axes_locatable
import matplotlib.gridspec as gridspec
fig = plt.figure(figsize=(9, 5))
ax = fig.add_subplot(111)
h = ax.imshow(U_pred.T, interpolation='nearest', cmap='rainbow',
extent=[t.min(), t.max(), x.min(), x.max()],
origin='lower', aspect='auto')
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.10)
cbar = fig.colorbar(h, cax=cax)
cbar.ax.tick_params(labelsize=15)
ax.plot(
labeled_X[:,1],
labeled_X[:,0],
'kx', label = 'Data (%d points)' % (labeled_y.shape[0]),
markersize = 4, # marker size doubled
clip_on = False,
alpha=1.0
)
line = np.linspace(x.min(), x.max(), 2)[:,None]
ax.plot(t[25]*np.ones((2,1)), line, 'w-', linewidth = 1)
ax.plot(t[50]*np.ones((2,1)), line, 'w-', linewidth = 1)
ax.plot(t[75]*np.ones((2,1)), line, 'w-', linewidth = 1)
ax.set_xlabel('$t$', size=20)
ax.set_ylabel('$x$', size=20)
ax.legend(
loc='upper center',
bbox_to_anchor=(0.9, -0.05),
ncol=5,
frameon=False,
prop={'size': 15}
)
ax.set_title('$u(t,x)$', fontsize = 20) # font size doubled
ax.tick_params(labelsize=15)
plt.show()
fig = plt.figure(figsize=(14, 10))
ax = fig.add_subplot(111)
gs1 = gridspec.GridSpec(1, 3)
gs1.update(top=1-1.0/3.0-0.1, bottom=1.0-2.0/3.0, left=0.1, right=0.9, wspace=0.5)
ax = plt.subplot(gs1[0, 0])
ax.plot(x,Exact[25,:], 'b-', linewidth = 2, label = 'Exact')
ax.plot(x,U_pred[25,:], 'r--', linewidth = 2, label = 'Prediction')
ax.set_xlabel('$x$')
ax.set_ylabel('$u(t,x)$')
ax.set_title('$t = 0.25$', fontsize = 15)
ax.axis('square')
ax.set_xlim([-1.1,1.1])
ax.set_ylim([-1.1,1.1])
for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] +
ax.get_xticklabels() + ax.get_yticklabels()):
item.set_fontsize(15)
ax = plt.subplot(gs1[0, 1])
ax.plot(x,Exact[50,:], 'b-', linewidth = 2, label = 'Exact')
ax.plot(x,U_pred[50,:], 'r--', linewidth = 2, label = 'Prediction')
ax.set_xlabel('$x$')
ax.set_ylabel('$u(t,x)$')
ax.axis('square')
ax.set_xlim([-1.1,1.1])
ax.set_ylim([-1.1,1.1])
ax.set_title('$t = 0.50$', fontsize = 15)
ax.legend(
loc='upper center',
bbox_to_anchor=(0.5, -0.15),
ncol=5,
frameon=False,
prop={'size': 15}
)
for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] +
ax.get_xticklabels() + ax.get_yticklabels()):
item.set_fontsize(15)
ax = plt.subplot(gs1[0, 2])
ax.plot(x,Exact[75,:], 'b-', linewidth = 2, label = 'Exact')
ax.plot(x,U_pred[75,:], 'r--', linewidth = 2, label = 'Prediction')
ax.set_xlabel('$x$')
ax.set_ylabel('$u(t,x)$')
ax.axis('square')
ax.set_xlim([-1.1,1.1])
ax.set_ylim([-1.1,1.1])
ax.set_title('$t = 0.75$', fontsize = 15)
for item in ([ax.title, ax.xaxis.label, ax.yaxis.label] +
ax.get_xticklabels() + ax.get_yticklabels()):
item.set_fontsize(15)
plt.show()
| examples/tutorials/Physics_Informed_Neural_Networks.ipynb | deepchem/deepchem | mit |
Lab Task #1: Set environment variables.
Set environment variables so that we can use them throughout the entire lab. We will be using our project name for our bucket, so you only need to change your project and region. | %%bash
PROJECT=$(gcloud config list project --format "value(core.project)")
echo "Your current GCP Project Name is: "$PROJECT
# Change these to try this notebook out
PROJECT = "cloud-training-demos" # TODO 1: Replace with your PROJECT
BUCKET = PROJECT # defaults to PROJECT
REGION = "us-central1" # TODO 1: Replace with your REGION
os.environ["BUCKET"] = BUCKET
os.environ["REGION"] = REGION
os.environ["TFVERSION"] = "2.1"
%%bash
gcloud config set compute/region $REGION
gcloud config set ai_platform/region global | courses/machine_learning/deepdive2/end_to_end_ml/labs/deploy_keras_ai_platform_babyweight.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Check our trained model files
Let's check the directory structure of our outputs of our trained model in folder we exported the model to in our last lab. We'll want to deploy the saved_model.pb within the timestamped directory as well as the variable values in the variables folder. Therefore, we need the path of the timestamped directory so that everything within it can be found by Cloud AI Platform's model deployment service. | %%bash
gsutil ls gs://${BUCKET}/babyweight/trained_model
%%bash
MODEL_LOCATION=$(gsutil ls -ld -- gs://${BUCKET}/babyweight/trained_model/2* \
| tail -1)
gsutil ls ${MODEL_LOCATION} | courses/machine_learning/deepdive2/end_to_end_ml/labs/deploy_keras_ai_platform_babyweight.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Lab Task #2: Deploy trained model.
Deploying the trained model to act as a REST web service is a simple gcloud call. Complete #TODO by providing location of saved_model.pb file to Cloud AI Platform model deployment service. The deployment will take a few minutes. | %%bash
MODEL_NAME="babyweight"
MODEL_VERSION="ml_on_gcp"
MODEL_LOCATION=# TODO 2: Add GCS path to saved_model.pb file.
echo "Deleting and deploying $MODEL_NAME $MODEL_VERSION from $MODEL_LOCATION"
# gcloud ai-platform versions delete ${MODEL_VERSION} --model ${MODEL_NAME}
# gcloud ai-platform models delete ${MODEL_NAME}
gcloud ai-platform models create ${MODEL_NAME} --regions ${REGION}
gcloud ai-platform versions create ${MODEL_VERSION} \
--model=${MODEL_NAME} \
--origin=${MODEL_LOCATION} \
--runtime-version=2.1 \
--python-version=3.7 | courses/machine_learning/deepdive2/end_to_end_ml/labs/deploy_keras_ai_platform_babyweight.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Lab Task #3: Use model to make online prediction.
Complete __#TODO__s for both the Python and gcloud Shell API methods of calling our deployed model on Cloud AI Platform for online prediction.
Python API
We can use the Python API to send a JSON request to the endpoint of the service to make it predict a baby's weight. The order of the responses are the order of the instances. | from oauth2client.client import GoogleCredentials
import requests
import json
MODEL_NAME = # TODO 3a: Add model name
MODEL_VERSION = # TODO 3a: Add model version
token = GoogleCredentials.get_application_default().get_access_token().access_token
api = "https://ml.googleapis.com/v1/projects/{}/models/{}/versions/{}:predict" \
.format(PROJECT, MODEL_NAME, MODEL_VERSION)
headers = {"Authorization": "Bearer " + token }
data = {
"instances": [
{
"is_male": "True",
"mother_age": 26.0,
"plurality": "Single(1)",
"gestation_weeks": 39
},
{
"is_male": "False",
"mother_age": 29.0,
"plurality": "Single(1)",
"gestation_weeks": 38
},
{
"is_male": "True",
"mother_age": 26.0,
"plurality": "Triplets(3)",
"gestation_weeks": 39
},
# TODO 3a: Create another instance
]
}
response = requests.post(api, json=data, headers=headers)
print(response.content) | courses/machine_learning/deepdive2/end_to_end_ml/labs/deploy_keras_ai_platform_babyweight.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
The predictions for the four instances were: 5.33, 6.09, 2.50, and 5.86 pounds respectively when I ran it (your results might be different).
gcloud shell API
Instead we could use the gcloud shell API. Create a newline delimited JSON file with one instance per line and submit using gcloud. | %%writefile inputs.json
{"is_male": "True", "mother_age": 26.0, "plurality": "Single(1)", "gestation_weeks": 39}
{"is_male": "False", "mother_age": 26.0, "plurality": "Single(1)", "gestation_weeks": 39} | courses/machine_learning/deepdive2/end_to_end_ml/labs/deploy_keras_ai_platform_babyweight.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Now call gcloud ai-platform predict using the JSON we just created and point to our deployed model and version. | %%bash
gcloud ai-platform predict \
--model=babyweight \
--json-instances=inputs.json \
--version=# TODO 3b: Add model version | courses/machine_learning/deepdive2/end_to_end_ml/labs/deploy_keras_ai_platform_babyweight.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Lab Task #4: Use model to make batch prediction.
Batch prediction is commonly used when you have thousands to millions of predictions. It will create an actual Cloud AI Platform job for prediction. Complete __#TODO__s so we can call our deployed model on Cloud AI Platform for batch prediction. | %%bash
INPUT=gs://${BUCKET}/babyweight/batchpred/inputs.json
OUTPUT=gs://${BUCKET}/babyweight/batchpred/outputs
gsutil cp inputs.json $INPUT
gsutil -m rm -rf $OUTPUT
gcloud ai-platform jobs submit prediction babypred_$(date -u +%y%m%d_%H%M%S) \
--data-format=TEXT \
--region ${REGION} \
--input-paths=$INPUT \
--output-path=$OUTPUT \
--model=babyweight \
--version=# TODO 4: Add model version | courses/machine_learning/deepdive2/end_to_end_ml/labs/deploy_keras_ai_platform_babyweight.ipynb | GoogleCloudPlatform/training-data-analyst | apache-2.0 |
Transfer learning and fine-tuning
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://www.tensorflow.org/guide/keras/transfer_learning"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a>
</td>
<td>
<a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs/blob/snapshot-keras/site/en/guide/keras/transfer_learning.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png" />Run in Google Colab</a>
</td>
<td>
<a target="_blank" href="https://github.com/keras-team/keras-io/blob/master/guides/transfer_learning.py"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" />View source on GitHub</a>
</td>
<td>
<a href="https://storage.googleapis.com/tensorflow_docs/docs/site/en/guide/keras/transfer_learning.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png" />Download notebook</a>
</td>
</table>
Setup | import numpy as np
import tensorflow as tf
from tensorflow import keras | site/en-snapshot/guide/keras/transfer_learning.ipynb | tensorflow/docs-l10n | apache-2.0 |
Introduction
Transfer learning consists of taking features learned on one problem, and
leveraging them on a new, similar problem. For instance, features from a model that has
learned to identify racoons may be useful to kick-start a model meant to identify
tanukis.
Transfer learning is usually done for tasks where your dataset has too little data to
train a full-scale model from scratch.
The most common incarnation of transfer learning in the context of deep learning is the
following workflow:
Take layers from a previously trained model.
Freeze them, so as to avoid destroying any of the information they contain during
future training rounds.
Add some new, trainable layers on top of the frozen layers. They will learn to turn
the old features into predictions on a new dataset.
Train the new layers on your dataset.
A last, optional step, is fine-tuning, which consists of unfreezing the entire
model you obtained above (or part of it), and re-training it on the new data with a
very low learning rate. This can potentially achieve meaningful improvements, by
incrementally adapting the pretrained features to the new data.
First, we will go over the Keras trainable API in detail, which underlies most
transfer learning & fine-tuning workflows.
Then, we'll demonstrate the typical workflow by taking a model pretrained on the
ImageNet dataset, and retraining it on the Kaggle "cats vs dogs" classification
dataset.
This is adapted from
Deep Learning with Python
and the 2016 blog post
"building powerful image classification models using very little
data".
Freezing layers: understanding the trainable attribute
Layers & models have three weight attributes:
weights is the list of all weights variables of the layer.
trainable_weights is the list of those that are meant to be updated (via gradient
descent) to minimize the loss during training.
non_trainable_weights is the list of those that aren't meant to be trained.
Typically they are updated by the model during the forward pass.
Example: the Dense layer has 2 trainable weights (kernel & bias) | layer = keras.layers.Dense(3)
layer.build((None, 4)) # Create the weights
print("weights:", len(layer.weights))
print("trainable_weights:", len(layer.trainable_weights))
print("non_trainable_weights:", len(layer.non_trainable_weights)) | site/en-snapshot/guide/keras/transfer_learning.ipynb | tensorflow/docs-l10n | apache-2.0 |
In general, all weights are trainable weights. The only built-in layer that has
non-trainable weights is the BatchNormalization layer. It uses non-trainable weights
to keep track of the mean and variance of its inputs during training.
To learn how to use non-trainable weights in your own custom layers, see the
guide to writing new layers from scratch.
Example: the BatchNormalization layer has 2 trainable weights and 2 non-trainable
weights | layer = keras.layers.BatchNormalization()
layer.build((None, 4)) # Create the weights
print("weights:", len(layer.weights))
print("trainable_weights:", len(layer.trainable_weights))
print("non_trainable_weights:", len(layer.non_trainable_weights)) | site/en-snapshot/guide/keras/transfer_learning.ipynb | tensorflow/docs-l10n | apache-2.0 |
Layers & models also feature a boolean attribute trainable. Its value can be changed.
Setting layer.trainable to False moves all the layer's weights from trainable to
non-trainable. This is called "freezing" the layer: the state of a frozen layer won't
be updated during training (either when training with fit() or when training with
any custom loop that relies on trainable_weights to apply gradient updates).
Example: setting trainable to False | layer = keras.layers.Dense(3)
layer.build((None, 4)) # Create the weights
layer.trainable = False # Freeze the layer
print("weights:", len(layer.weights))
print("trainable_weights:", len(layer.trainable_weights))
print("non_trainable_weights:", len(layer.non_trainable_weights)) | site/en-snapshot/guide/keras/transfer_learning.ipynb | tensorflow/docs-l10n | apache-2.0 |
When a trainable weight becomes non-trainable, its value is no longer updated during
training. | # Make a model with 2 layers
layer1 = keras.layers.Dense(3, activation="relu")
layer2 = keras.layers.Dense(3, activation="sigmoid")
model = keras.Sequential([keras.Input(shape=(3,)), layer1, layer2])
# Freeze the first layer
layer1.trainable = False
# Keep a copy of the weights of layer1 for later reference
initial_layer1_weights_values = layer1.get_weights()
# Train the model
model.compile(optimizer="adam", loss="mse")
model.fit(np.random.random((2, 3)), np.random.random((2, 3)))
# Check that the weights of layer1 have not changed during training
final_layer1_weights_values = layer1.get_weights()
np.testing.assert_allclose(
initial_layer1_weights_values[0], final_layer1_weights_values[0]
)
np.testing.assert_allclose(
initial_layer1_weights_values[1], final_layer1_weights_values[1]
) | site/en-snapshot/guide/keras/transfer_learning.ipynb | tensorflow/docs-l10n | apache-2.0 |
Do not confuse the layer.trainable attribute with the argument training in
layer.__call__() (which controls whether the layer should run its forward pass in
inference mode or training mode). For more information, see the
Keras FAQ.
Recursive setting of the trainable attribute
If you set trainable = False on a model or on any layer that has sublayers,
all children layers become non-trainable as well.
Example: | inner_model = keras.Sequential(
[
keras.Input(shape=(3,)),
keras.layers.Dense(3, activation="relu"),
keras.layers.Dense(3, activation="relu"),
]
)
model = keras.Sequential(
[keras.Input(shape=(3,)), inner_model, keras.layers.Dense(3, activation="sigmoid"),]
)
model.trainable = False # Freeze the outer model
assert inner_model.trainable == False # All layers in `model` are now frozen
assert inner_model.layers[0].trainable == False # `trainable` is propagated recursively | site/en-snapshot/guide/keras/transfer_learning.ipynb | tensorflow/docs-l10n | apache-2.0 |
The typical transfer-learning workflow
This leads us to how a typical transfer learning workflow can be implemented in Keras:
Instantiate a base model and load pre-trained weights into it.
Freeze all layers in the base model by setting trainable = False.
Create a new model on top of the output of one (or several) layers from the base
model.
Train your new model on your new dataset.
Note that an alternative, more lightweight workflow could also be:
Instantiate a base model and load pre-trained weights into it.
Run your new dataset through it and record the output of one (or several) layers
from the base model. This is called feature extraction.
Use that output as input data for a new, smaller model.
A key advantage of that second workflow is that you only run the base model once on
your data, rather than once per epoch of training. So it's a lot faster & cheaper.
An issue with that second workflow, though, is that it doesn't allow you to dynamically
modify the input data of your new model during training, which is required when doing
data augmentation, for instance. Transfer learning is typically used for tasks when
your new dataset has too little data to train a full-scale model from scratch, and in
such scenarios data augmentation is very important. So in what follows, we will focus
on the first workflow.
Here's what the first workflow looks like in Keras:
First, instantiate a base model with pre-trained weights.
python
base_model = keras.applications.Xception(
weights='imagenet', # Load weights pre-trained on ImageNet.
input_shape=(150, 150, 3),
include_top=False) # Do not include the ImageNet classifier at the top.
Then, freeze the base model.
python
base_model.trainable = False
Create a new model on top.
```python
inputs = keras.Input(shape=(150, 150, 3))
We make sure that the base_model is running in inference mode here,
by passing training=False. This is important for fine-tuning, as you will
learn in a few paragraphs.
x = base_model(inputs, training=False)
Convert features of shape base_model.output_shape[1:] to vectors
x = keras.layers.GlobalAveragePooling2D()(x)
A Dense classifier with a single unit (binary classification)
outputs = keras.layers.Dense(1)(x)
model = keras.Model(inputs, outputs)
```
Train the model on new data.
python
model.compile(optimizer=keras.optimizers.Adam(),
loss=keras.losses.BinaryCrossentropy(from_logits=True),
metrics=[keras.metrics.BinaryAccuracy()])
model.fit(new_dataset, epochs=20, callbacks=..., validation_data=...)
Fine-tuning
Once your model has converged on the new data, you can try to unfreeze all or part of
the base model and retrain the whole model end-to-end with a very low learning rate.
This is an optional last step that can potentially give you incremental improvements.
It could also potentially lead to quick overfitting -- keep that in mind.
It is critical to only do this step after the model with frozen layers has been
trained to convergence. If you mix randomly-initialized trainable layers with
trainable layers that hold pre-trained features, the randomly-initialized layers will
cause very large gradient updates during training, which will destroy your pre-trained
features.
It's also critical to use a very low learning rate at this stage, because
you are training a much larger model than in the first round of training, on a dataset
that is typically very small.
As a result, you are at risk of overfitting very quickly if you apply large weight
updates. Here, you only want to readapt the pretrained weights in an incremental way.
This is how to implement fine-tuning of the whole base model:
```python
Unfreeze the base model
base_model.trainable = True
It's important to recompile your model after you make any changes
to the trainable attribute of any inner layer, so that your changes
are take into account
model.compile(optimizer=keras.optimizers.Adam(1e-5), # Very low learning rate
loss=keras.losses.BinaryCrossentropy(from_logits=True),
metrics=[keras.metrics.BinaryAccuracy()])
Train end-to-end. Be careful to stop before you overfit!
model.fit(new_dataset, epochs=10, callbacks=..., validation_data=...)
```
Important note about compile() and trainable
Calling compile() on a model is meant to "freeze" the behavior of that model. This
implies that the trainable
attribute values at the time the model is compiled should be preserved throughout the
lifetime of that model,
until compile is called again. Hence, if you change any trainable value, make sure
to call compile() again on your
model for your changes to be taken into account.
Important notes about BatchNormalization layer
Many image models contain BatchNormalization layers. That layer is a special case on
every imaginable count. Here are a few things to keep in mind.
BatchNormalization contains 2 non-trainable weights that get updated during
training. These are the variables tracking the mean and variance of the inputs.
When you set bn_layer.trainable = False, the BatchNormalization layer will
run in inference mode, and will not update its mean & variance statistics. This is not
the case for other layers in general, as
weight trainability & inference/training modes are two orthogonal concepts.
But the two are tied in the case of the BatchNormalization layer.
When you unfreeze a model that contains BatchNormalization layers in order to do
fine-tuning, you should keep the BatchNormalization layers in inference mode by
passing training=False when calling the base model.
Otherwise the updates applied to the non-trainable weights will suddenly destroy
what the model has learned.
You'll see this pattern in action in the end-to-end example at the end of this guide.
Transfer learning & fine-tuning with a custom training loop
If instead of fit(), you are using your own low-level training loop, the workflow
stays essentially the same. You should be careful to only take into account the list
model.trainable_weights when applying gradient updates:
```python
Create base model
base_model = keras.applications.Xception(
weights='imagenet',
input_shape=(150, 150, 3),
include_top=False)
Freeze base model
base_model.trainable = False
Create new model on top.
inputs = keras.Input(shape=(150, 150, 3))
x = base_model(inputs, training=False)
x = keras.layers.GlobalAveragePooling2D()(x)
outputs = keras.layers.Dense(1)(x)
model = keras.Model(inputs, outputs)
loss_fn = keras.losses.BinaryCrossentropy(from_logits=True)
optimizer = keras.optimizers.Adam()
Iterate over the batches of a dataset.
for inputs, targets in new_dataset:
# Open a GradientTape.
with tf.GradientTape() as tape:
# Forward pass.
predictions = model(inputs)
# Compute the loss value for this batch.
loss_value = loss_fn(targets, predictions)
# Get gradients of loss wrt the *trainable* weights.
gradients = tape.gradient(loss_value, model.trainable_weights)
# Update the weights of the model.
optimizer.apply_gradients(zip(gradients, model.trainable_weights))
```
Likewise for fine-tuning.
An end-to-end example: fine-tuning an image classification model on a cats vs. dogs dataset
To solidify these concepts, let's walk you through a concrete end-to-end transfer
learning & fine-tuning example. We will load the Xception model, pre-trained on
ImageNet, and use it on the Kaggle "cats vs. dogs" classification dataset.
Getting the data
First, let's fetch the cats vs. dogs dataset using TFDS. If you have your own dataset,
you'll probably want to use the utility
tf.keras.preprocessing.image_dataset_from_directory to generate similar labeled
dataset objects from a set of images on disk filed into class-specific folders.
Transfer learning is most useful when working with very small datasets. To keep our
dataset small, we will use 40% of the original training data (25,000 images) for
training, 10% for validation, and 10% for testing. | import tensorflow_datasets as tfds
tfds.disable_progress_bar()
train_ds, validation_ds, test_ds = tfds.load(
"cats_vs_dogs",
# Reserve 10% for validation and 10% for test
split=["train[:40%]", "train[40%:50%]", "train[50%:60%]"],
as_supervised=True, # Include labels
)
print("Number of training samples: %d" % tf.data.experimental.cardinality(train_ds))
print(
"Number of validation samples: %d" % tf.data.experimental.cardinality(validation_ds)
)
print("Number of test samples: %d" % tf.data.experimental.cardinality(test_ds)) | site/en-snapshot/guide/keras/transfer_learning.ipynb | tensorflow/docs-l10n | apache-2.0 |
These are the first 9 images in the training dataset -- as you can see, they're all
different sizes. | import matplotlib.pyplot as plt
plt.figure(figsize=(10, 10))
for i, (image, label) in enumerate(train_ds.take(9)):
ax = plt.subplot(3, 3, i + 1)
plt.imshow(image)
plt.title(int(label))
plt.axis("off") | site/en-snapshot/guide/keras/transfer_learning.ipynb | tensorflow/docs-l10n | apache-2.0 |
We can also see that label 1 is "dog" and label 0 is "cat".
Standardizing the data
Our raw images have a variety of sizes. In addition, each pixel consists of 3 integer
values between 0 and 255 (RGB level values). This isn't a great fit for feeding a
neural network. We need to do 2 things:
Standardize to a fixed image size. We pick 150x150.
Normalize pixel values between -1 and 1. We'll do this using a Normalization layer as
part of the model itself.
In general, it's a good practice to develop models that take raw data as input, as
opposed to models that take already-preprocessed data. The reason being that, if your
model expects preprocessed data, any time you export your model to use it elsewhere
(in a web browser, in a mobile app), you'll need to reimplement the exact same
preprocessing pipeline. This gets very tricky very quickly. So we should do the least
possible amount of preprocessing before hitting the model.
Here, we'll do image resizing in the data pipeline (because a deep neural network can
only process contiguous batches of data), and we'll do the input value scaling as part
of the model, when we create it.
Let's resize images to 150x150: | size = (150, 150)
train_ds = train_ds.map(lambda x, y: (tf.image.resize(x, size), y))
validation_ds = validation_ds.map(lambda x, y: (tf.image.resize(x, size), y))
test_ds = test_ds.map(lambda x, y: (tf.image.resize(x, size), y)) | site/en-snapshot/guide/keras/transfer_learning.ipynb | tensorflow/docs-l10n | apache-2.0 |
Besides, let's batch the data and use caching & prefetching to optimize loading speed. | batch_size = 32
train_ds = train_ds.cache().batch(batch_size).prefetch(buffer_size=10)
validation_ds = validation_ds.cache().batch(batch_size).prefetch(buffer_size=10)
test_ds = test_ds.cache().batch(batch_size).prefetch(buffer_size=10) | site/en-snapshot/guide/keras/transfer_learning.ipynb | tensorflow/docs-l10n | apache-2.0 |
Using random data augmentation
When you don't have a large image dataset, it's a good practice to artificially
introduce sample diversity by applying random yet realistic transformations to
the training images, such as random horizontal flipping or small random rotations. This
helps expose the model to different aspects of the training data while slowing down
overfitting. | from tensorflow import keras
from tensorflow.keras import layers
data_augmentation = keras.Sequential(
[layers.RandomFlip("horizontal"), layers.RandomRotation(0.1),]
) | site/en-snapshot/guide/keras/transfer_learning.ipynb | tensorflow/docs-l10n | apache-2.0 |
Let's visualize what the first image of the first batch looks like after various random
transformations: | import numpy as np
for images, labels in train_ds.take(1):
plt.figure(figsize=(10, 10))
first_image = images[0]
for i in range(9):
ax = plt.subplot(3, 3, i + 1)
augmented_image = data_augmentation(
tf.expand_dims(first_image, 0), training=True
)
plt.imshow(augmented_image[0].numpy().astype("int32"))
plt.title(int(labels[0]))
plt.axis("off") | site/en-snapshot/guide/keras/transfer_learning.ipynb | tensorflow/docs-l10n | apache-2.0 |
Build a model
Now let's built a model that follows the blueprint we've explained earlier.
Note that:
We add a Rescaling layer to scale input values (initially in the [0, 255]
range) to the [-1, 1] range.
We add a Dropout layer before the classification layer, for regularization.
We make sure to pass training=False when calling the base model, so that
it runs in inference mode, so that batchnorm statistics don't get updated
even after we unfreeze the base model for fine-tuning. | base_model = keras.applications.Xception(
weights="imagenet", # Load weights pre-trained on ImageNet.
input_shape=(150, 150, 3),
include_top=False,
) # Do not include the ImageNet classifier at the top.
# Freeze the base_model
base_model.trainable = False
# Create new model on top
inputs = keras.Input(shape=(150, 150, 3))
x = data_augmentation(inputs) # Apply random data augmentation
# Pre-trained Xception weights requires that input be scaled
# from (0, 255) to a range of (-1., +1.), the rescaling layer
# outputs: `(inputs * scale) + offset`
scale_layer = keras.layers.Rescaling(scale=1 / 127.5, offset=-1)
x = scale_layer(x)
# The base model contains batchnorm layers. We want to keep them in inference mode
# when we unfreeze the base model for fine-tuning, so we make sure that the
# base_model is running in inference mode here.
x = base_model(x, training=False)
x = keras.layers.GlobalAveragePooling2D()(x)
x = keras.layers.Dropout(0.2)(x) # Regularize with dropout
outputs = keras.layers.Dense(1)(x)
model = keras.Model(inputs, outputs)
model.summary() | site/en-snapshot/guide/keras/transfer_learning.ipynb | tensorflow/docs-l10n | apache-2.0 |
Train the top layer | model.compile(
optimizer=keras.optimizers.Adam(),
loss=keras.losses.BinaryCrossentropy(from_logits=True),
metrics=[keras.metrics.BinaryAccuracy()],
)
epochs = 20
model.fit(train_ds, epochs=epochs, validation_data=validation_ds) | site/en-snapshot/guide/keras/transfer_learning.ipynb | tensorflow/docs-l10n | apache-2.0 |
Do a round of fine-tuning of the entire model
Finally, let's unfreeze the base model and train the entire model end-to-end with a low
learning rate.
Importantly, although the base model becomes trainable, it is still running in
inference mode since we passed training=False when calling it when we built the
model. This means that the batch normalization layers inside won't update their batch
statistics. If they did, they would wreck havoc on the representations learned by the
model so far. | # Unfreeze the base_model. Note that it keeps running in inference mode
# since we passed `training=False` when calling it. This means that
# the batchnorm layers will not update their batch statistics.
# This prevents the batchnorm layers from undoing all the training
# we've done so far.
base_model.trainable = True
model.summary()
model.compile(
optimizer=keras.optimizers.Adam(1e-5), # Low learning rate
loss=keras.losses.BinaryCrossentropy(from_logits=True),
metrics=[keras.metrics.BinaryAccuracy()],
)
epochs = 10
model.fit(train_ds, epochs=epochs, validation_data=validation_ds) | site/en-snapshot/guide/keras/transfer_learning.ipynb | tensorflow/docs-l10n | apache-2.0 |
Simulation of the Milky Way | # OMEGA parameters for MW
mass_loading = 1 # How much mass is ejected from the galaxy per stellar mass formed
nb_1a_per_m = 3.0e-3 # Number of SNe Ia per stellar mass formed
sfe = 0.005 # Star formation efficiency, which sets the mass of gas
table = 'yield_tables/isotope_yield_table_MESA_only_ye.txt' # Yields for AGB and massive stars
#milky_way
o_mw = omega.omega(galaxy='milky_way',Z_trans=-1, table=table,sfe=sfe, DM_evolution=True,\
mass_loading=mass_loading, nb_1a_per_m=nb_1a_per_m, special_timesteps=60) | DOC/Teaching/.ipynb_checkpoints/Section2.1-checkpoint.ipynb | NuGrid/NuPyCEE | bsd-3-clause |
Comparison of chemical evolution prediction with observation | # Choose abundance ratios
%matplotlib nbagg
xaxis = '[Fe/H]'
yaxis = '[C/Fe]'
# Plot observational data points (Stellab)
stellab.plot_spectro(xaxis=xaxis, yaxis=yaxis,norm='Grevesse_Noels_1993',galaxy='milky_way',show_err=False)
# Extract the numerical predictions (OMEGA)
xy_f = o_mw.plot_spectro(fig=3,xaxis=xaxis,yaxis=yaxis,return_x_y=True)
# Overplot the numerical predictions (they are normalized according to Grevesse & Noels 1993)
plt.plot(xy_f[0],xy_f[1],linewidth=4,color='w')
plt.plot(xy_f[0],xy_f[1],linewidth=2,color='k',label='OMEGA')
# Update the existing legend
plt.legend(loc='center left', bbox_to_anchor=(1.01, 0.5), markerscale=0.8, fontsize=13)
# Choose X and Y limits
plt.xlim(-4.5,0.5)
plt.ylim(-1.4,1.6) | DOC/Teaching/.ipynb_checkpoints/Section2.1-checkpoint.ipynb | NuGrid/NuPyCEE | bsd-3-clause |
Tracing back to simple stellar populations. | s0p0001=sygma.sygma(iniZ=0.0001)
s0p006=sygma.sygma(iniZ=0.006) | DOC/Teaching/.ipynb_checkpoints/Section2.1-checkpoint.ipynb | NuGrid/NuPyCEE | bsd-3-clause |
What is [C/Fe] for two SSPs at Z=0.006 and Z=0.0001? | elem='[C/Fe]'
s0p0001.plot_spectro(fig=3,yaxis=elem,marker='D',color='b',label='Z=0.0001')
s0p006.plot_spectro(fig=3,yaxis=elem,label='Z=0.006') | DOC/Teaching/.ipynb_checkpoints/Section2.1-checkpoint.ipynb | NuGrid/NuPyCEE | bsd-3-clause |
Now lets focus on C. What is the evolution of the total mass of C? | # Plot the ejected mass of a certain element
elem='C'
s0p0001.plot_mass(fig=4,specie=elem,marker='D',color='b',label='Z=0.0001')
s0p006.plot_mass(fig=4,specie=elem,label='Z=0.006') | DOC/Teaching/.ipynb_checkpoints/Section2.1-checkpoint.ipynb | NuGrid/NuPyCEE | bsd-3-clause |
Which stars contribute the most to C? | elem='C'
s0p0001.plot_mass_range_contributions(specie=elem,marker='D',color='b',label='Z=0.0001')
s0p006.plot_mass_range_contributions(specie=elem,label='Z=0.006') | DOC/Teaching/.ipynb_checkpoints/Section2.1-checkpoint.ipynb | NuGrid/NuPyCEE | bsd-3-clause |
Which stellar yields are the most? | s0p0001.plot_table_yield(fig=6,iniZ=0.0001,table='yield_tables/isotope_yield_table.txt',yaxis='C-12',
masses=[1.0, 1.65, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0],marker='D',color='b',)
s0p006.plot_table_yield(fig=6,iniZ=0.006,table='yield_tables/isotope_yield_table.txt',yaxis='C-12',
masses=[1.0, 1.65, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0]) | DOC/Teaching/.ipynb_checkpoints/Section2.1-checkpoint.ipynb | NuGrid/NuPyCEE | bsd-3-clause |
Dataset Parameters
Let's create and add a mesh dataset to the Bundle. | b.add_dataset('mesh')
print b.filter(kind='mesh') | 2.1/tutorials/MESH.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
times | print b['times'] | 2.1/tutorials/MESH.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
include_times | print b['include_times'] | 2.1/tutorials/MESH.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
columns | print b['columns'] | 2.1/tutorials/MESH.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
Compute Options
Let's look at the compute options (for the default PHOEBE 2 backend) that relate to meshes | print b['compute'] | 2.1/tutorials/MESH.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
mesh_method | print b['mesh_method@primary'] | 2.1/tutorials/MESH.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
The 'mesh_method' parameter determines how each component in the system is discretized into its mesh, and has several options:
* marching (default): this is the new method introduced in PHOEBE 2. The star is discretized into triangles, with the attempt to make them each of equal-area and nearly equilateral. Although not as fast as 'wd', this method is more robust and will always form a closed surface (when possible).
* wd: this is a re-implementation of the Wilson-Devinney style meshing used in PHOEBE 1.0 (legacy), with the stars discretized into trapezoids in strips of latitude (we then split each trapezoid into two triangles). This is faster, but suffers from gaps between the surface elements, and is mainly meant for testing and comparison with legacy. See the WD-Style Meshing Example Script for more details.
ntriangles
The 'ntriangles' parameter is only relevenat if mesh_method=='marching' (so will not be available unless that is the case). | print b['ntriangles@primary'] | 2.1/tutorials/MESH.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
gridsize
The 'gridsize' parameter is only relevant if mesh_method=='wd' (so will not be available unless that is the case). | print b['gridsize@primary'] | 2.1/tutorials/MESH.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
Synthetics | b.set_value('times', [0])
b['columns'] = '*'
b.run_compute()
b['mesh@model'].twigs | 2.1/tutorials/MESH.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
Per-Mesh Parameters | print b['times@primary@mesh01@model'] | 2.1/tutorials/MESH.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
Per-Time Parameters | print b['volume@primary@mesh01@model'] | 2.1/tutorials/MESH.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
Per-Element Parameters | print b['uvw_elements@primary@mesh01@model']
print b['xyz_elements@primary@mesh01@model']
print b['us@primary@mesh01@model']
print b['rs@primary@mesh01@model']
print b['rprojs@primary@mesh01@model']
print b['nxs@primary@mesh01@model']
print b['mus@primary@mesh01@model']
print b['vxs@primary@mesh01@model']
print b['areas@primary@mesh01@model']
print b['loggs@primary@mesh01@model']
print b['teffs@primary@mesh01@model']
print b['visibilities@primary@mesh01@model'] | 2.1/tutorials/MESH.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
Plotting
By default, MESH datasets plot as 'vs' vx 'us' (plane of sky coordinates) of just the surface elements, taken from the uvw_elements vectors. | afig, mplfig = b['mesh@model'].plot(show=True) | 2.1/tutorials/MESH.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
Any of the 1-D fields (ie not vertices or normals) or matplotlib-recognized colornames can be used to color either the faces or edges of the triangles. Passing none for edgecolor or facecolor turns off the coloring (you may want to set edgecolor=None if setting facecolor to disable the black outline). | afig, mplfig = b['mesh@model'].plot(fc='teffs', ec='None', show=True) | 2.1/tutorials/MESH.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
Alternatively, if you provide simple 1-D fields to plot, a 2D x-y plot will be created using the values from each element (always for a single time - if meshes exist for multiple times in the model, you should provide a single time either in the twig or as a filter).
NOTE: providing z=0 will override the default of z-ordering the points by there "w" (line-of-sight distance) value, which can be expensive and take a while to draw. | afig, mplfig = b['mesh@model'].plot(x='mus', y='teffs', z=0, show=True) | 2.1/tutorials/MESH.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
The exception to needing to provide a time is for the per-time parameters mentioned above. For these, time can be the x-array (not very exciting in this case with only a single time).
For more examples see the following:
- Passband Luminosity Tutorial | afig, mplfig = b['mesh@model'].plot(x='times', y='volume', marker='s', show=True) | 2.1/tutorials/MESH.ipynb | phoebe-project/phoebe2-docs | gpl-3.0 |
2. 清洗错行的情况 | with open("/Users/chengjun/GitHub/cjc/data/ows_tweets_sample.txt", 'rb') as f:
lines = f.readlines()
# 总行数
len(lines)
# 查看第一行
lines[0] | data/06.data_cleaning_Tweets.ipynb | computational-class/cc2017 | mit |
问题: 第一行是变量名
1. 如何去掉换行符?
2. 如何获取每一个变量名? | varNames = lines[0].replace('\n', '').split(',')
varNames
len(varNames)
lines[1344] | data/06.data_cleaning_Tweets.ipynb | computational-class/cc2017 | mit |
如何来处理错误换行情况? | with open("/Users/chengjun/GitHub/cjc/data/ows_tweets_sample_clean.txt", 'w') as f:
right_line = '' # 正确的行,它是一个空字符串
blocks = [] # 确认为正确的行会被添加到blocks里面
for line in lines:
right_line += line.replace('\n', ' ')
line_length = len(right_line.split(','))
if line_length >= 14:
blocks.append(right_line)
right_line = ''
for i in blocks:
f.write(i + '\n')
len(blocks)
blocks[1344]
with open("/Users/chengjun/GitHub/cjc/data/ows_tweets_sample_clean4.txt", 'w') as f:
right_line = '' # 正确的行,它是一个空字符串
blocks = [] # 确认为正确的行会被添加到blocks里面
for line in lines:
right_line += line.replace('\n', ' ').replace('\r', ' ')
line_length = len(right_line.split(','))
if line_length >= 14:
blocks.append(right_line)
right_line = ''
for i in blocks:
f.write(i + '\n')
blocks[1344] | data/06.data_cleaning_Tweets.ipynb | computational-class/cc2017 | mit |
3. 读取数据、正确分列 | # 提示:你可能需要修改以下路径名
with open("/Users/chengjun/GitHub/cjc/data/ows_tweets_sample_clean.txt", 'rb') as f:
chunk = f.readlines()
len(chunk)
chunk[:3]
import csv
clean_lines = (line.replace('\x00','') \
for line in chunk[1:])
lines = csv.reader(clean_lines, delimiter=',', \
quotechar='"')
import pandas as pd
df = pd.read_csv("/Users/chengjun/GitHub/cjc/data/ows_tweets_sample_clean.txt",\
sep = ',', quotechar='"')
df[:3]
df.Text[1]
df['From User'] | data/06.data_cleaning_Tweets.ipynb | computational-class/cc2017 | mit |
4. 统计数量
统计发帖数量所对应的人数的分布
人数在发帖数量方面的分布情况 | from collections import defaultdict
data_dict = defaultdict(int)
line_num = 0
lines = csv.reader((line.replace('\x00','') for line in chunk[1:]), delimiter=',', quotechar='"')
for i in lines:
line_num +=1
data_dict[i[8]] +=1 # i[8] 是user
data_dict.items()[:5]
print line_num
%matplotlib inline
from matplotlib.font_manager import FontProperties
import matplotlib.pyplot as plt
import matplotlib
#matplotlib.rcParams['font.sans-serif'] = ['Microsoft YaHei'] #指定默认字体
matplotlib.rc("savefig", dpi=100)
font = FontProperties(fname=r'/Users/chengjun/github/cjc/data/msyh.ttf', size=14) # 注意:修改这里的路径名
plt.hist(data_dict.values())
#plt.yscale('log')
#plt.xscale('log')
plt.xlabel(u'发帖数', fontproperties=font)
plt.ylabel(u'人数', fontproperties=font)
plt.show()
tweet_dict = defaultdict(int)
for i in data_dict.values():
tweet_dict[i] += 1
plt.loglog(tweet_dict.keys(), tweet_dict.values(), 'ro',linewidth=2)
plt.xlabel(u'推特数', fontproperties=font)
plt.ylabel(u'人数', fontproperties=font )
plt.show()
import numpy as np
import statsmodels.api as sm
def powerPlot(d_value, d_freq, color, marker):
d_freq = [i + 1 for i in d_freq]
d_prob = [float(i)/sum(d_freq) for i in d_freq]
#d_rank = ss.rankdata(d_value).astype(int)
x = np.log(d_value)
y = np.log(d_prob)
xx = sm.add_constant(x, prepend=True)
res = sm.OLS(y,xx).fit()
constant,beta = res.params
r2 = res.rsquared
plt.plot(d_value, d_prob, linestyle = '', color = color, marker = marker)
plt.plot(d_value, np.exp(constant+x*beta),"red")
plt.xscale('log'); plt.yscale('log')
plt.text(max(d_value)/2,max(d_prob)/10,
r'$\beta$ = ' + str(round(beta,2)) +'\n' + r'$R^2$ = ' + str(round(r2, 2)))
histo, bin_edges = np.histogram(data_dict.values(), 15)
bin_center = 0.5*(bin_edges[1:] + bin_edges[:-1])
powerPlot(bin_center,histo, 'r', 'o')
#lg=plt.legend(labels = [u'Tweets', u'Fit'], loc=3, fontsize=20)
plt.ylabel(u'概率', fontproperties=font)
plt.xlabel(u'推特数', fontproperties=font)
plt.show()
import statsmodels.api as sm
from collections import defaultdict
import numpy as np
def powerPlot(data):
d = sorted(data, reverse = True )
d_table = defaultdict(int)
for k in d:
d_table[k] += 1
d_value = sorted(d_table)
d_value = [i+1 for i in d_value]
d_freq = [d_table[i]+1 for i in d_value]
d_prob = [float(i)/sum(d_freq) for i in d_freq]
#d_rank = ss.rankdata(d_value).astype(int)
x = np.log(d_value)
y = np.log(d_prob)
xx = sm.add_constant(x, prepend=True)
res = sm.OLS(y,xx).fit()
constant,beta = res.params
r2 = res.rsquared
plt.plot(d_value, d_prob, 'ro')
plt.plot(d_value, np.exp(constant+x*beta),"red")
plt.xscale('log'); plt.yscale('log')
plt.text(max(d_value)/2,max(d_prob)/5,
'Beta = ' + str(round(beta,2)) +'\n' + 'R squared = ' + str(round(r2, 2)))
plt.title('Distribution')
plt.ylabel('P(K)')
plt.xlabel('K')
plt.show()
powerPlot(data_dict.values())
import powerlaw
def plotPowerlaw(data,ax,col,xlab):
fit = powerlaw.Fit(data,xmin=2)
#fit = powerlaw.Fit(data)
fit.plot_pdf(color = col, linewidth = 2)
a,x = (fit.power_law.alpha,fit.power_law.xmin)
fit.power_law.plot_pdf(color = col, linestyle = 'dotted', ax = ax, \
label = r"$\alpha = %d \:\:, x_{min} = %d$" % (a,x))
ax.set_xlabel(xlab, fontsize = 20)
ax.set_ylabel('$Probability$', fontsize = 20)
plt.legend(loc = 0, frameon = False)
from collections import defaultdict
data_dict = defaultdict(int)
for i in df['From User']:
data_dict[i] += 1
import matplotlib.cm as cm
cmap = cm.get_cmap('rainbow_r',6)
fig = plt.figure(figsize=(6, 4),facecolor='white')
ax = fig.add_subplot(1, 1, 1)
plotPowerlaw(data_dict.values(), ax,cmap(1), '$Gold\;Metals$') | data/06.data_cleaning_Tweets.ipynb | computational-class/cc2017 | mit |
5. 清洗tweets文本 | tweet = '''RT @AnonKitsu: ALERT!!!!!!!!!!COPS ARE KETTLING PROTESTERS IN PARK W HELICOPTERS AND PADDYWAGONS!!!!
#OCCUPYWALLSTREET #OWS #OCCUPYNY PLEASE @chengjun @mili http://computational-communication.com
http://ccc.nju.edu.cn RT !!HELP!!!!'''
import re
import twitter_text
| data/06.data_cleaning_Tweets.ipynb | computational-class/cc2017 | mit |
安装twitter_text
pip install twitter-text-py
无法正常安装的同学
可以在spyder中打开terminal安装 | import re
tweet = '''RT @AnonKitsu: ALERT!!!!!!!!!!COPS ARE KETTLING PROTESTERS IN PARK W HELICOPTERS AND PADDYWAGONS!!!!
#OCCUPYWALLSTREET #OWS #OCCUPYNY PLEASE @chengjun @mili http://computational-communication.com
http://ccc.nju.edu.cn RT !!HELP!!!!'''
rt_patterns = re.compile(r"(RT|via)((?:\b\W*@\w+)+)", \
re.IGNORECASE)
rt_user_name = rt_patterns.findall(tweet)[0][1].strip(' @')
rt_user_name
import re
tweet = '''@AnonKitsu: ALERT!!!!!!!!!!COPS ARE KETTLING PROTESTERS IN PARK W HELICOPTERS AND PADDYWAGONS!!!!
#OCCUPYWALLSTREET #OWS #OCCUPYNY PLEASE @chengjun @mili http://computational-communication.com
http://ccc.nju.edu.cn RT !!HELP!!!!'''
rt_patterns = re.compile(r"(RT|via)((?:\b\W*@\w+)+)", re.IGNORECASE)
rt_user_name = rt_patterns.findall(tweet)
print rt_user_name
if rt_user_name:
print 'it exits.'
else:
print 'None'
import re
def extract_rt_user(tweet):
rt_patterns = re.compile(r"(RT|via)((?:\b\W*@\w+)+)", re.IGNORECASE)
rt_user_name = rt_patterns.findall(tweet)
if rt_user_name:
rt_user_name = rt_user_name[0][1].strip(' @')
else:
rt_user_name = None
return rt_user_name
tweet = '''@AnonKitsu: ALERT!!!!!!!!!!COPS ARE KETTLING PROTESTERS IN PARK W HELICOPTERS AND PADDYWAGONS!!!!
#OCCUPYWALLSTREET #OWS #OCCUPYNY PLEASE @chengjun @mili http://computational-communication.com
http://ccc.nju.edu.cn RT !!HELP!!!!'''
print extract_rt_user(tweet) | data/06.data_cleaning_Tweets.ipynb | computational-class/cc2017 | mit |
获得清洗过的推特文本
不含人名、url、各种符号(如RT @等) | def extract_tweet_text(tweet, at_names, urls):
for i in at_names:
tweet = tweet.replace(i, '')
for j in urls:
tweet = tweet.replace(j, '')
marks = ['RT @', '@', '"', '#', '\n', '\t', ' ']
for k in marks:
tweet = tweet.replace(k, '')
return tweet
import twitter_text
tweet = '''RT @AnonKitsu: ALERT!!!!!!!!!!COPS ARE KETTLING PROTESTERS IN PARK W HELICOPTERS AND PADDYWAGONS!!!!
#OCCUPYWALLSTREET #OWS #OCCUPYNY PLEASE @chengjun @mili http://computational-communication.com
http://ccc.nju.edu.cn RT !!HELP!!!!'''
ex = twitter_text.Extractor(tweet)
at_names = ex.extract_mentioned_screen_names()
urls = ex.extract_urls()
hashtags = ex.extract_hashtags()
rt_user = extract_rt_user(tweet)
tweet_text = extract_tweet_text(tweet, at_names, urls)
print at_names, urls, hashtags, rt_user,'-------->', tweet_text
import csv
lines = csv.reader((line.replace('\x00','') for line in chunk[1:]), delimiter=',', quotechar='"')
tweets = [i[1] for i in lines]
for tweet in tweets[:5]:
ex = twitter_text.Extractor(tweet)
at_names = ex.extract_mentioned_screen_names()
urls = ex.extract_urls()
hashtags = ex.extract_hashtags()
rt_user = extract_rt_user(tweet)
tweet_text = extract_tweet_text(tweet, at_names, urls)
print at_names, urls, hashtags, rt_user,
print tweet_text | data/06.data_cleaning_Tweets.ipynb | computational-class/cc2017 | mit |
思考:
提取出tweets中的rtuser与user的转发网络
格式:
rt_user1, user1
rt_user2, user3
rt_user2, user4
...
数据保存为csv格式 | import csv
lines = csv.reader((line.replace('\x00','') \
for line in chunk[1:]), \
delimiter=',', quotechar='"')
tweet_user_data = [(i[1], i[8]) for i in lines]
for tweet,user in tweet_user_data:
rt_user = extract_rt_user(tweet)
if rt_user:
print rt_user, ',', user | data/06.data_cleaning_Tweets.ipynb | computational-class/cc2017 | mit |
Gaussian mixture models are usually constructed with categorical random variables. However, any discrete rvs does not fit ADVI. Here, class assignment variables are marginalized out, giving weighted sum of the probability for the gaussian components. The log likelihood of the total probability is calculated using logsumexp, which is a standard technique for making this kind of calculation stable.
In the below code, DensityDist class is used as the likelihood term. The second argument, logp_gmix(mus, pi, np.eye(2)), is a python function which recieves observations (denoted by 'value') and returns the tensor representation of the log-likelihood. | from pymc3.math import logsumexp
# Log likelihood of normal distribution
def logp_normal(mu, tau, value):
# log probability of individual samples
k = tau.shape[0]
delta = lambda mu: value - mu
return (-1 / 2.) * (k * tt.log(2 * np.pi) + tt.log(1./det(tau)) +
(delta(mu).dot(tau) * delta(mu)).sum(axis=1))
# Log likelihood of Gaussian mixture distribution
def logp_gmix(mus, pi, tau):
def logp_(value):
logps = [tt.log(pi[i]) + logp_normal(mu, tau, value)
for i, mu in enumerate(mus)]
return tt.sum(logsumexp(tt.stacklists(logps)[:, :n_samples], axis=0))
return logp_
with pm.Model() as model:
mus = [MvNormal('mu_%d' % i, mu=np.zeros(2), tau=0.1 * np.eye(2), shape=(2,))
for i in range(2)]
pi = Dirichlet('pi', a=0.1 * np.ones(2), shape=(2,))
xs = DensityDist('x', logp_gmix(mus, pi, np.eye(2)), observed=data) | notebooks/gaussian-mixture-model-advi.ipynb | dolittle007/dolittle007.github.io | gpl-3.0 |
For comparison with ADVI, run MCMC. | with model:
start = find_MAP()
step = Metropolis()
trace = sample(1000, step, start=start) | notebooks/gaussian-mixture-model-advi.ipynb | dolittle007/dolittle007.github.io | gpl-3.0 |
Check posterior of component means and weights. We can see that the MCMC samples of the component mean for the lower-left component varied more than the upper-right due to the difference of the sample size of these clusters. | plt.figure(figsize=(5, 5))
plt.scatter(data[:, 0], data[:, 1], alpha=0.5, c='g')
mu_0, mu_1 = trace['mu_0'], trace['mu_1']
plt.scatter(mu_0[-500:, 0], mu_0[-500:, 1], c="r", s=10)
plt.scatter(mu_1[-500:, 0], mu_1[-500:, 1], c="b", s=10)
plt.xlim(-6, 6)
plt.ylim(-6, 6)
sns.barplot([1, 2], np.mean(trace['pi'][-5000:], axis=0),
palette=['red', 'blue']) | notebooks/gaussian-mixture-model-advi.ipynb | dolittle007/dolittle007.github.io | gpl-3.0 |
We can use the same model with ADVI as follows. | with pm.Model() as model:
mus = [MvNormal('mu_%d' % i, mu=np.zeros(2), tau=0.1 * np.eye(2), shape=(2,))
for i in range(2)]
pi = Dirichlet('pi', a=0.1 * np.ones(2), shape=(2,))
xs = DensityDist('x', logp_gmix(mus, pi, np.eye(2)), observed=data)
%time means, sds, elbos = pm.variational.advi( \
model=model, n=1000, learning_rate=1e-1) | notebooks/gaussian-mixture-model-advi.ipynb | dolittle007/dolittle007.github.io | gpl-3.0 |
The function returns three variables. 'means' and 'sds' are the mean and standart deviations of the variational posterior. Note that these values are in the transformed space, not in the original space. For random variables in the real line, e.g., means of the Gaussian components, no transformation is applied. Then we can see the variational posterior in the original space. | from copy import deepcopy
mu_0, sd_0 = means['mu_0'], sds['mu_0']
mu_1, sd_1 = means['mu_1'], sds['mu_1']
def logp_normal_np(mu, tau, value):
# log probability of individual samples
k = tau.shape[0]
delta = lambda mu: value - mu
return (-1 / 2.) * (k * np.log(2 * np.pi) + np.log(1./np.linalg.det(tau)) +
(delta(mu).dot(tau) * delta(mu)).sum(axis=1))
def threshold(zz):
zz_ = deepcopy(zz)
zz_[zz < np.max(zz) * 1e-2] = None
return zz_
def plot_logp_normal(ax, mu, sd, cmap):
f = lambda value: np.exp(logp_normal_np(mu, np.diag(1 / sd**2), value))
g = lambda mu, sd: np.arange(mu - 3, mu + 3, .1)
xx, yy = np.meshgrid(g(mu[0], sd[0]), g(mu[1], sd[1]))
zz = f(np.vstack((xx.reshape(-1), yy.reshape(-1))).T).reshape(xx.shape)
ax.contourf(xx, yy, threshold(zz), cmap=cmap, alpha=0.9)
fig, ax = plt.subplots(figsize=(5, 5))
plt.scatter(data[:, 0], data[:, 1], alpha=0.5, c='g')
plot_logp_normal(ax, mu_0, sd_0, cmap='Reds')
plot_logp_normal(ax, mu_1, sd_1, cmap='Blues')
plt.xlim(-6, 6)
plt.ylim(-6, 6) | notebooks/gaussian-mixture-model-advi.ipynb | dolittle007/dolittle007.github.io | gpl-3.0 |
TODO: We need to backward-transform 'pi', which is transformed by 'stick_breaking'.
'elbos' contains the trace of ELBO, showing stochastic convergence of the algorithm. | plt.plot(elbos) | notebooks/gaussian-mixture-model-advi.ipynb | dolittle007/dolittle007.github.io | gpl-3.0 |
To demonstrate that ADVI works for large dataset with mini-batch, let's create 100,000 samples from the same mixture distribution. | n_samples = 100000
zs = np.array([rng.multinomial(1, ps) for _ in range(n_samples)]).T
xs = [z[:, np.newaxis] * rng.multivariate_normal(m, np.eye(2), size=n_samples)
for z, m in zip(zs, ms)]
data = np.sum(np.dstack(xs), axis=2)
plt.figure(figsize=(5, 5))
plt.scatter(data[:, 0], data[:, 1], c='g', alpha=0.5)
plt.scatter(ms[0, 0], ms[0, 1], c='r', s=100)
plt.scatter(ms[1, 0], ms[1, 1], c='b', s=100)
plt.xlim(-6, 6)
plt.ylim(-6, 6) | notebooks/gaussian-mixture-model-advi.ipynb | dolittle007/dolittle007.github.io | gpl-3.0 |
MCMC took 55 seconds, 20 times longer than the small dataset. | with pm.Model() as model:
mus = [MvNormal('mu_%d' % i, mu=np.zeros(2), tau=0.1 * np.eye(2), shape=(2,))
for i in range(2)]
pi = Dirichlet('pi', a=0.1 * np.ones(2), shape=(2,))
xs = DensityDist('x', logp_gmix(mus, pi, np.eye(2)), observed=data)
start = find_MAP()
step = Metropolis()
trace = sample(1000, step, start=start) | notebooks/gaussian-mixture-model-advi.ipynb | dolittle007/dolittle007.github.io | gpl-3.0 |
Posterior samples are concentrated on the true means, so looks like single point for each component. | plt.figure(figsize=(5, 5))
plt.scatter(data[:, 0], data[:, 1], alpha=0.5, c='g')
mu_0, mu_1 = trace['mu_0'], trace['mu_1']
plt.scatter(mu_0[-500:, 0], mu_0[-500:, 1], c="r", s=50)
plt.scatter(mu_1[-500:, 0], mu_1[-500:, 1], c="b", s=50)
plt.xlim(-6, 6)
plt.ylim(-6, 6) | notebooks/gaussian-mixture-model-advi.ipynb | dolittle007/dolittle007.github.io | gpl-3.0 |
For ADVI with mini-batch, put theano tensor on the observed variable of the ObservedRV. The tensor will be replaced with mini-batches. Because of the difference of the size of mini-batch and whole samples, the log-likelihood term should be appropriately scaled. To tell the log-likelihood term, we need to give ObservedRV objects ('minibatch_RVs' below) where mini-batch is put. Also we should keep the tensor ('minibatch_tensors'). | data_t = tt.matrix()
data_t.tag.test_value = np.zeros((1, 2)).astype(float)
with pm.Model() as model:
mus = [MvNormal('mu_%d' % i, mu=np.zeros(2), tau=0.1 * np.eye(2), shape=(2,))
for i in range(2)]
pi = Dirichlet('pi', a=0.1 * np.ones(2), shape=(2,))
xs = DensityDist('x', logp_gmix(mus, pi, np.eye(2)), observed=data_t)
minibatch_tensors = [data_t]
minibatch_RVs = [xs] | notebooks/gaussian-mixture-model-advi.ipynb | dolittle007/dolittle007.github.io | gpl-3.0 |
Make a generator for mini-batches of size 200. Here, we take random sampling strategy to make mini-batches. | def create_minibatch(data):
rng = np.random.RandomState(0)
while True:
ixs = rng.randint(len(data), size=200)
yield [data[ixs]]
minibatches = create_minibatch(data)
total_size = len(data) | notebooks/gaussian-mixture-model-advi.ipynb | dolittle007/dolittle007.github.io | gpl-3.0 |
Run ADVI. It's much faster than MCMC, though the problem here is simple and it's not a fair comparison. | # Used only to write the function call in single line for using %time
# is there more smart way?
def f():
return pm.variational.advi_minibatch(
model=model, n=1000, minibatch_tensors=minibatch_tensors,
minibatch_RVs=minibatch_RVs, minibatches=minibatches,
total_size=total_size, learning_rate=1e-1)
%time means, sds, elbos = f() | notebooks/gaussian-mixture-model-advi.ipynb | dolittle007/dolittle007.github.io | gpl-3.0 |
The result is almost the same. | from copy import deepcopy
mu_0, sd_0 = means['mu_0'], sds['mu_0']
mu_1, sd_1 = means['mu_1'], sds['mu_1']
fig, ax = plt.subplots(figsize=(5, 5))
plt.scatter(data[:, 0], data[:, 1], alpha=0.5, c='g')
plt.scatter(mu_0[0], mu_0[1], c="r", s=50)
plt.scatter(mu_1[0], mu_1[1], c="b", s=50)
plt.xlim(-6, 6)
plt.ylim(-6, 6) | notebooks/gaussian-mixture-model-advi.ipynb | dolittle007/dolittle007.github.io | gpl-3.0 |
The variance of the trace of ELBO is larger than without mini-batch because of the subsampling from the whole samples. | plt.plot(elbos); | notebooks/gaussian-mixture-model-advi.ipynb | dolittle007/dolittle007.github.io | gpl-3.0 |
Recommendation Comparison
A more general framework for comparing different recommendation techniques
Evaluation DataSet
See notes in the creating_dataset_for_evaluation.ipynb
From full dataset
- removed rows with no nn features (for view or for buy)
- remove the items that have been viewed 20minutes before buying.
- sub-sampled a set of 1000 users | # load smaller user behavior dataset
user_profile = pd.read_pickle('../data_user_view_buy/user_profile_items_nonnull_features_20_mins_5_views_v2_sample1000.pkl')
user_sample = user_profile.user_id.unique()
print(len(user_profile))
print(len(user_sample))
user_profile.head()
# requires nn features
spu_fea = pd.read_pickle("../data_nn_features/spu_fea_sample1000.pkl")
# make sure all items have features ?? One missing
print(len(set(list(user_profile.buy_spu.unique())+list(user_profile.view_spu.unique()))))
print(len(spu_fea.spu_id.unique())) | notebooks/.ipynb_checkpoints/Recommendation_Compare_Methods-checkpoint.ipynb | walkon302/CDIPS_Recommender | apache-2.0 |
Load precalculated things for recommendations | # this might be faster #
# ## Precalculate average feature per user
# average_viewed_features_dict = {}
# for user_id in user_profile.user_id.unique():
# average_viewed_features_dict[user_id] = get_user_average_features(user_id,user_profile,spu_fea)
| notebooks/.ipynb_checkpoints/Recommendation_Compare_Methods-checkpoint.ipynb | walkon302/CDIPS_Recommender | apache-2.0 |
Loop through users and score function | def get_user_buy_ranks(users_sample,user_profile,spu_fea,method,randomize_scores=False):
user_buy_ranks = np.empty(len(users_sample))
no_ranks = np.empty(len(users_sample))
for ui,user_id in enumerate(users_sample):
print(ui)
# rank items
item_score_in_category = rank_candidates(user_id,user_profile,spu_fea,method=method,extra_inputs={},randomize_scores=randomize_scores)
# get bought item rank and store into array
user_buy_ranks[ui]=item_score_in_category.loc[item_score_in_category.buy==1,'rank'].as_matrix()[0]
# get number of ranks per category
no_ranks[ui]=item_score_in_category['rank'].max()
return(user_buy_ranks,no_ranks,item_score_in_category) | notebooks/.ipynb_checkpoints/Recommendation_Compare_Methods-checkpoint.ipynb | walkon302/CDIPS_Recommender | apache-2.0 |
Evaluate Different Algorithms | users_sample = np.random.choice(user_sample,size=50)
# nathan's
user_buy_ranks1,no_ranks1,item_score_in_category=get_user_buy_ranks(users_sample,user_profile,spu_fea,method='AverageFeatureSim')
# just taking the last item
user_buy_ranks2,no_ranks2,_=get_user_buy_ranks(users_sample,user_profile,spu_fea,method='LastItemSim')
# randomize
user_buy_ranks3,no_ranks3,_=get_user_buy_ranks(users_sample,user_profile,spu_fea,method='Randomize',randomize_scores=True)
# stack
rank_percent = np.vstack((user_buy_ranks1/no_ranks1,user_buy_ranks2/no_ranks2,user_buy_ranks3/no_ranks3))
print(rank_percent.shape)
# Plot
mean = rank_percent.mean(axis=1)
n = np.shape(rank_percent)[1]
m = np.shape(rank_percent)[0]
print(n)
print(m)
sem = rank_percent.std(axis=1)/np.sqrt(n)
plt.errorbar(np.arange(m),y=mean,yerr=sem,linestyle='None',marker='o')
plt.xticks(np.arange(m),['AvgFeatures','LastFeat','Random \n Guess'])
plt.xlim([-1,m+1])
plt.ylim(0,1)
sns.despine()
plt.title('Recommendor Comparison')
plt.ylabel('Average (Buy Rank / # in Buy Category)')
plt.axhline(y=0.5,linestyle='--')
savefile = '../figures/recommender_comparison_sample_1000_subsample50_v1.png'
plt.savefig(savefile,dpi=300)
from src import s3_data_management
s3_data_management.push_results_to_s3(os.path.basename(savefile),savefile) | notebooks/.ipynb_checkpoints/Recommendation_Compare_Methods-checkpoint.ipynb | walkon302/CDIPS_Recommender | apache-2.0 |
Save | %%bash
jupyter nbconvert --to slides Recommendation_Compare_Methods.ipynb && mv Recommendation_Compare_Methods.slides.html ../notebook_slides/Recommendation_Compare_Methods_v1.slides.html
jupyter nbconvert --to html Recommendation_Compare_Methods.ipynb && mv Recommendation_Compare_Methods.html ../notebook_htmls/Recommendation_Compare_Methods_v1.html
cp Recommendation_Compare_Methods.ipynb ../notebook_versions/Recommendation_Compare_Methods_v1.ipynb | notebooks/.ipynb_checkpoints/Recommendation_Compare_Methods-checkpoint.ipynb | walkon302/CDIPS_Recommender | apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.