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 follo... | 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 th... | 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 Fun... | 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"... | 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... | 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 (Logi... | 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]
- Th... | # 根据建议修改的方法,很赞!
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,... | 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_e... | # 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
# ... | 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_stat... | 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, ProbsTen... | 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 ... | 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: Impleme... | 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')
loa... | 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.su... | 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()/10... | 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... | 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'
d... | 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.ara... | 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 ... | # %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 + rp... | 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 )
tes... | 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 ... | ## 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()[... | 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 ... | 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 functi... | 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.sp... | 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... | 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['label... | 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 fu... | # 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),... | 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.axe... | 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 w... | 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 ti... | %%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... | 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. ... | 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/{}:pr... | 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... | 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:/... | 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 you... | 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 t... | 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 whe... | 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_l... | 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... | 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 = Fals... | 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) laye... | 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 sampl... | 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 imag... | 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 aspec... | 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(augmen... | 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 wh... | 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(s... | 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... | # 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
m... | 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' # Y... | 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,ya... | 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',
... | 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... | 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... | 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-o... | 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:
b... | 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... | 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... | 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)(... | 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
tw... | 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, ',', use... | 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 logsu... | 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)... | 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:], a... | 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( \... | 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 ... | 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))... | 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... | 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()
... | 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 ObservedR... | 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.... | 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)
%ti... | 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.
-... | # 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_p... | 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_c... | 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='Last... | 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/Recomm... | 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.