markdown stringlengths 0 1.02M | code stringlengths 0 832k | output stringlengths 0 1.02M | license stringlengths 3 36 | path stringlengths 6 265 | repo_name stringlengths 6 127 |
|---|---|---|---|---|---|
LSTM cellNext, we'll create our LSTM cells to use in the recurrent network ([TensorFlow documentation](https://www.tensorflow.org/api_docs/python/tf/contrib/rnn)). Here we are just defining what the cells look like. This isn't actually building the graph, just defining the type of cells we want in our graph.To create ... | with graph.as_default():
# Your basic LSTM cell
lstm = tf.contrib.rnn.BasicLSTMCell(lstm_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
cell = tf.contrib.rnn.MultiRNNCell([drop] *... | _____no_output_____ | MIT | term-2-concentrations/lab-5-nlp-sentiment-analysis/Sentiment_RNN.ipynb | rstraker/ai-nanodegree-udacity |
RNN forward passNow we need to actually run the data through the RNN nodes. You can use [`tf.nn.dynamic_rnn`](https://www.tensorflow.org/api_docs/python/tf/nn/dynamic_rnn) to do this. You'd pass in the RNN cell you created (our multiple layered LSTM `cell` for instance), and the inputs to the network.```outputs, final... | with graph.as_default():
outputs, final_state = tf.nn.dynamic_rnn(cell, embed, initial_state=initial_state) | _____no_output_____ | MIT | term-2-concentrations/lab-5-nlp-sentiment-analysis/Sentiment_RNN.ipynb | rstraker/ai-nanodegree-udacity |
OutputWe only care about the final output, we'll be using that as our sentiment prediction. So we need to grab the last output with `outputs[:, -1]`, the calculate the cost from that and `labels_`. | with graph.as_default():
predictions = tf.contrib.layers.fully_connected(outputs[:, -1], 1, activation_fn=tf.sigmoid)
cost = tf.losses.mean_squared_error(labels_, predictions)
optimizer = tf.train.AdamOptimizer(learning_rate).minimize(cost) | _____no_output_____ | MIT | term-2-concentrations/lab-5-nlp-sentiment-analysis/Sentiment_RNN.ipynb | rstraker/ai-nanodegree-udacity |
Validation accuracyHere we can add a few nodes to calculate the accuracy which we'll use in the validation pass. | with graph.as_default():
correct_pred = tf.equal(tf.cast(tf.round(predictions), tf.int32), labels_)
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32)) | _____no_output_____ | MIT | term-2-concentrations/lab-5-nlp-sentiment-analysis/Sentiment_RNN.ipynb | rstraker/ai-nanodegree-udacity |
BatchingThis is a simple function for returning batches from our data. First it removes data such that we only have full batches. Then it iterates through the `x` and `y` arrays and returns slices out of those arrays with size `[batch_size]`. | def get_batches(x, y, batch_size=100):
n_batches = len(x)//batch_size
x, y = x[:n_batches*batch_size], y[:n_batches*batch_size]
for ii in range(0, len(x), batch_size):
yield x[ii:ii+batch_size], y[ii:ii+batch_size] | _____no_output_____ | MIT | term-2-concentrations/lab-5-nlp-sentiment-analysis/Sentiment_RNN.ipynb | rstraker/ai-nanodegree-udacity |
TrainingBelow is the typical training code. If you want to do this yourself, feel free to delete all this code and implement it yourself. Before you run this, make sure the `checkpoints` directory exists. | epochs = 10
with graph.as_default():
saver = tf.train.Saver()
with tf.Session(graph=graph) as sess:
sess.run(tf.global_variables_initializer())
iteration = 1
for e in range(epochs):
state = sess.run(initial_state)
for ii, (x, y) in enumerate(get_batches(train_x, train_y, batch... | Epoch: 0/10 Iteration: 5 Train loss: 0.240
Epoch: 0/10 Iteration: 10 Train loss: 0.240
Epoch: 0/10 Iteration: 15 Train loss: 0.221
Epoch: 0/10 Iteration: 20 Train loss: 0.184
Epoch: 0/10 Iteration: 25 Train loss: 0.230
Val acc: 0.629
Epoch: 0/10 Iteration: 30 Train loss: 0.235
Epoch: 0/10 Iteration: 35 Train loss: 0.23... | MIT | term-2-concentrations/lab-5-nlp-sentiment-analysis/Sentiment_RNN.ipynb | rstraker/ai-nanodegree-udacity |
Testing | test_acc = []
with tf.Session(graph=graph) as sess:
saver.restore(sess, tf.train.latest_checkpoint('checkpoints'))
test_state = sess.run(cell.zero_state(batch_size, tf.float32))
for ii, (x, y) in enumerate(get_batches(test_x, test_y, batch_size), 1):
feed = {inputs_: x,
labels_: y[:,... | INFO:tensorflow:Restoring parameters from checkpoints/sentiment.ckpt
Test accuracy: 0.776
| MIT | term-2-concentrations/lab-5-nlp-sentiment-analysis/Sentiment_RNN.ipynb | rstraker/ai-nanodegree-udacity |
Copyright 2018 Google LLC. | # Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the L... | _____no_output_____ | Apache-2.0 | ml/recommendation-systems/recommendation-systems.ipynb | howl-anderson/eng-edu |
Recommendation Systems with TensorFlowThis Colab notebook complements the course on [Recommendation Systems](https://developers.google.com/machine-learning/recommendation/). Specifically, we'll be using matrix factorization to learn user and movie embeddings. IntroductionWe will create a movie recommendation system b... | # @title Imports (run this cell)
from __future__ import print_function
import numpy as np
import pandas as pd
import collections
from mpl_toolkits.mplot3d import Axes3D
from IPython import display
from matplotlib import pyplot as plt
import sklearn
import sklearn.manifold
import tensorflow.compat.v1 as tf
tf.disable_v... | _____no_output_____ | Apache-2.0 | ml/recommendation-systems/recommendation-systems.ipynb | howl-anderson/eng-edu |
We then download the MovieLens Data, and create DataFrames containing movies, users, and ratings. | # @title Load the MovieLens data (run this cell).
# Download MovieLens data.
print("Downloading movielens data...")
from urllib.request import urlretrieve
import zipfile
urlretrieve("http://files.grouplens.org/datasets/movielens/ml-100k.zip", "movielens.zip")
zip_ref = zipfile.ZipFile('movielens.zip', "r")
zip_ref.ex... | _____no_output_____ | Apache-2.0 | ml/recommendation-systems/recommendation-systems.ipynb | howl-anderson/eng-edu |
I. Exploring the Movielens DataBefore we dive into model building, let's inspect our MovieLens dataset. It is usually helpful to understand the statistics of the dataset. UsersWe start by printing some basic statistics describing the numeric user features. | users.describe() | _____no_output_____ | Apache-2.0 | ml/recommendation-systems/recommendation-systems.ipynb | howl-anderson/eng-edu |
We can also print some basic statistics describing the categorical user features | users.describe(include=[np.object]) | _____no_output_____ | Apache-2.0 | ml/recommendation-systems/recommendation-systems.ipynb | howl-anderson/eng-edu |
We can also create histograms to further understand the distribution of the users. We use Altair to create an interactive chart. | # @title Altair visualization code (run this cell)
# The following functions are used to generate interactive Altair charts.
# We will display histograms of the data, sliced by a given attribute.
# Create filters to be used to slice the data.
occupation_filter = alt.selection_multi(fields=["occupation"])
occupation_ch... | _____no_output_____ | Apache-2.0 | ml/recommendation-systems/recommendation-systems.ipynb | howl-anderson/eng-edu |
Next, we look at the distribution of ratings per user. Clicking on an occupation in the right chart will filter the data by that occupation. The corresponding histogram is shown in blue, and superimposed with the histogram for the whole data (in light gray). You can use SHIFT+click to select multiple subsets.What do yo... | users_ratings = (
ratings
.groupby('user_id', as_index=False)
.agg({'rating': ['count', 'mean']})
.flatten_cols()
.merge(users, on='user_id')
)
# Create a chart for the count, and one for the mean.
alt.hconcat(
filtered_hist('rating count', '# ratings / user', occupation_filter),
filtered_h... | _____no_output_____ | Apache-2.0 | ml/recommendation-systems/recommendation-systems.ipynb | howl-anderson/eng-edu |
MoviesIt is also useful to look at information about the movies and their ratings. | movies_ratings = movies.merge(
ratings
.groupby('movie_id', as_index=False)
.agg({'rating': ['count', 'mean']})
.flatten_cols(),
on='movie_id')
genre_filter = alt.selection_multi(fields=['genre'])
genre_chart = alt.Chart().mark_bar().encode(
x="count()",
y=alt.Y('genre'),
color=alt.cond... | _____no_output_____ | Apache-2.0 | ml/recommendation-systems/recommendation-systems.ipynb | howl-anderson/eng-edu |
Finally, the last chart shows the distribution of the number of ratings and average rating. | # Display the number of ratings and average rating per movie.
alt.hconcat(
filtered_hist('rating count', '# ratings / movie', genre_filter),
filtered_hist('rating mean', 'mean movie rating', genre_filter),
genre_chart,
data=movies_ratings) | _____no_output_____ | Apache-2.0 | ml/recommendation-systems/recommendation-systems.ipynb | howl-anderson/eng-edu |
II. PreliminariesOur goal is to factorize the ratings matrix $A$ into the product of a user embedding matrix $U$ and movie embedding matrix $V$, such that $A \approx UV^\top$ with$U = \begin{bmatrix} u_{1} \\ \hline \vdots \\ \hline u_{N} \end{bmatrix}$ and$V = \begin{bmatrix} v_{1} \\ \hline \vdots \\ \hline v_{M} \e... | def build_rating_sparse_tensor(ratings_df):
"""
Args:
ratings_df: a pd.DataFrame with `user_id`, `movie_id` and `rating` columns.
Returns:
A tf.SparseTensor representing the ratings matrix.
"""
# ========================= Complete this section ============================
# indices =
# values =
... | _____no_output_____ | Apache-2.0 | ml/recommendation-systems/recommendation-systems.ipynb | howl-anderson/eng-edu |
Calculating the errorThe model approximates the ratings matrix $A$ by a low-rank product $UV^\top$. We need a way to measure the approximation error. We'll start by using the Mean Squared Error of observed entries only (we will revisit this later). It is defined as$$\begin{align*}\text{MSE}(A, UV^\top)&= \frac{1}{|\Om... | def sparse_mean_square_error(sparse_ratings, user_embeddings, movie_embeddings):
"""
Args:
sparse_ratings: A SparseTensor rating matrix, of dense_shape [N, M]
user_embeddings: A dense Tensor U of shape [N, k] where k is the embedding
dimension, such that U_i is the embedding of user i.
movie_embed... | _____no_output_____ | Apache-2.0 | ml/recommendation-systems/recommendation-systems.ipynb | howl-anderson/eng-edu |
Note: One approach is to compute the full prediction matrix $UV^\top$, then gather the entries corresponding to the observed pairs. The memory cost of this approach is $O(NM)$. For the MovieLens dataset, this is fine, as the dense $N \times M$ matrix is small enough to fit in memory ($N = 943$, $M = 1682$).Another appr... | #@title Alternate Solution
def sparse_mean_square_error(sparse_ratings, user_embeddings, movie_embeddings):
"""
Args:
sparse_ratings: A SparseTensor rating matrix, of dense_shape [N, M]
user_embeddings: A dense Tensor U of shape [N, k] where k is the embedding
dimension, such that U_i is the embedding... | _____no_output_____ | Apache-2.0 | ml/recommendation-systems/recommendation-systems.ipynb | howl-anderson/eng-edu |
Exercise 3 (Optional): adding your own ratings to the data set You have the option to add your own ratings to the data set. If you choose to do so, you will be able to see recommendations for yourself.Start by checking the box below. Running the next cell will authenticate you to your google Drive account, and create ... | USER_RATINGS = True #@param {type:"boolean"}
# @title Run to create a spreadsheet, then use it to enter your ratings.
# Authenticate user.
if USER_RATINGS:
auth.authenticate_user()
gc = gspread.authorize(GoogleCredentials.get_application_default())
# Create the spreadsheet and print a link to it.
try:
sh = ... | _____no_output_____ | Apache-2.0 | ml/recommendation-systems/recommendation-systems.ipynb | howl-anderson/eng-edu |
Run the next cell to load your ratings and add them to the main `ratings` DataFrame. | # @title Run to load your ratings.
# Load the ratings from the spreadsheet and create a DataFrame.
if USER_RATINGS:
my_ratings = pd.DataFrame.from_records(worksheet.get_all_values()).reset_index()
my_ratings = my_ratings[my_ratings[1] != '']
my_ratings = pd.DataFrame({
'user_id': "943",
'movie_id': li... | _____no_output_____ | Apache-2.0 | ml/recommendation-systems/recommendation-systems.ipynb | howl-anderson/eng-edu |
III. Training a Matrix Factorization model CFModel (Collaborative Filtering Model) helper classThis is a simple class to train a matrix factorization model using stochastic gradient descent.The class constructor takes- the user embeddings U (a `tf.Variable`).- the movie embeddings V, (a `tf.Variable`).- a loss to opti... | # @title CFModel helper class (run this cell)
class CFModel(object):
"""Simple class that represents a collaborative filtering model"""
def __init__(self, embedding_vars, loss, metrics=None):
"""Initializes a CFModel.
Args:
embedding_vars: A dictionary of tf.Variables.
loss: A float Tensor. The ... | _____no_output_____ | Apache-2.0 | ml/recommendation-systems/recommendation-systems.ipynb | howl-anderson/eng-edu |
Exercise 4: Build a Matrix Factorization model and train itUsing your `sparse_mean_square_error` function, write a function that builds a `CFModel` by creating the embedding variables and the train and test losses. | def build_model(ratings, embedding_dim=3, init_stddev=1.):
"""
Args:
ratings: a DataFrame of the ratings
embedding_dim: the dimension of the embedding vectors.
init_stddev: float, the standard deviation of the random initial embeddings.
Returns:
model: a CFModel.
"""
# Split the ratings DataFr... | _____no_output_____ | Apache-2.0 | ml/recommendation-systems/recommendation-systems.ipynb | howl-anderson/eng-edu |
Great, now it's time to train the model!Go ahead and run the next cell, trying different parameters (embedding dimension, learning rate, iterations). The training and test errors are plotted at the end of training. You can inspect these values to validate the hyper-parameters.Note: by calling `model.train` again, the m... | # Build the CF model and train it.
model = build_model(ratings, embedding_dim=30, init_stddev=0.5)
model.train(num_iterations=1000, learning_rate=10.) | _____no_output_____ | Apache-2.0 | ml/recommendation-systems/recommendation-systems.ipynb | howl-anderson/eng-edu |
The movie and user embeddings are also displayed in the right figure. When the embedding dimension is greater than 3, the embeddings are projected on the first 3 dimensions. The next section will have a more detailed look at the embeddings. IV. Inspecting the EmbeddingsIn this section, we take a closer look at the lea... | DOT = 'dot'
COSINE = 'cosine'
def compute_scores(query_embedding, item_embeddings, measure=DOT):
"""Computes the scores of the candidates given a query.
Args:
query_embedding: a vector of shape [k], representing the query embedding.
item_embeddings: a matrix of shape [N, k], such that row i is the embedding... | _____no_output_____ | Apache-2.0 | ml/recommendation-systems/recommendation-systems.ipynb | howl-anderson/eng-edu |
Equipped with this function, we can compute recommendations, where the query embedding can be either a user embedding or a movie embedding. | # @title User recommendations and nearest neighbors (run this cell)
def user_recommendations(model, measure=DOT, exclude_rated=False, k=6):
if USER_RATINGS:
scores = compute_scores(
model.embeddings["user_id"][943], model.embeddings["movie_id"], measure)
score_key = measure + ' score'
df = pd.Data... | _____no_output_____ | Apache-2.0 | ml/recommendation-systems/recommendation-systems.ipynb | howl-anderson/eng-edu |
Your recommendationsIf you chose to input your recommendations, you can run the next cell to generate recommendations for you. | user_recommendations(model, measure=COSINE, k=5) | _____no_output_____ | Apache-2.0 | ml/recommendation-systems/recommendation-systems.ipynb | howl-anderson/eng-edu |
How do the recommendations look? Movie Nearest neighborsLet's look at the neareast neighbors for some of the movies. | movie_neighbors(model, "Aladdin", DOT)
movie_neighbors(model, "Aladdin", COSINE) | _____no_output_____ | Apache-2.0 | ml/recommendation-systems/recommendation-systems.ipynb | howl-anderson/eng-edu |
It seems that the quality of learned embeddings may not be very good. This will be addressed in Section V by adding several regularization techniques. First, we will further inspect the embeddings. Movie Embedding NormWe can also observe that the recommendations with dot-product and cosine are different: with dot-prod... | # @title Embedding Visualization code (run this cell)
def movie_embedding_norm(models):
"""Visualizes the norm and number of ratings of the movie embeddings.
Args:
model: A MFModel object.
"""
if not isinstance(models, list):
models = [models]
df = pd.DataFrame({
'title': movies['title'],
... | _____no_output_____ | Apache-2.0 | ml/recommendation-systems/recommendation-systems.ipynb | howl-anderson/eng-edu |
Note: Depending on how the model is initialized, you may observe that some niche movies (ones with few ratings) have a high norm, leading to spurious recommendations. This can happen if the embedding of that movie happens to be initialized with a high norm. Then, because the movie has few ratings, it is infrequently up... | #@title Solution
model_lowinit = build_model(ratings, embedding_dim=30, init_stddev=0.05)
model_lowinit.train(num_iterations=1000, learning_rate=10.)
movie_neighbors(model_lowinit, "Aladdin", DOT)
movie_neighbors(model_lowinit, "Aladdin", COSINE)
movie_embedding_norm([model, model_lowinit]) | _____no_output_____ | Apache-2.0 | ml/recommendation-systems/recommendation-systems.ipynb | howl-anderson/eng-edu |
Embedding visualizationSince it is hard to visualize embeddings in a higher-dimensional space (when the embedding dimension $k > 3$), one approach is to project the embeddings to a lower dimensional space. T-SNE (T-distributed Stochastic Neighbor Embedding) is an algorithm that projects the embeddings while attempting... | tsne_movie_embeddings(model_lowinit) | _____no_output_____ | Apache-2.0 | ml/recommendation-systems/recommendation-systems.ipynb | howl-anderson/eng-edu |
You can highlight the embeddings of a given genre by clicking on the genres panel (SHIFT+click to select multiple genres).We can observe that the embeddings do not seem to have any notable structure, and the embeddings of a given genre are located all over the embedding space. This confirms the poor quality of the lear... | def gravity(U, V):
"""Creates a gravity loss given two embedding matrices."""
return 1. / (U.shape[0].value*V.shape[0].value) * tf.reduce_sum(
tf.matmul(U, U, transpose_a=True) * tf.matmul(V, V, transpose_a=True))
def build_regularized_model(
ratings, embedding_dim=3, regularization_coeff=.1, gravity_coe... | _____no_output_____ | Apache-2.0 | ml/recommendation-systems/recommendation-systems.ipynb | howl-anderson/eng-edu |
It is now time to train the regularized model! You can try different values of the regularization coefficients, and different embedding dimensions. | reg_model = build_regularized_model(
ratings, regularization_coeff=0.1, gravity_coeff=1.0, embedding_dim=35,
init_stddev=.05)
reg_model.train(num_iterations=2000, learning_rate=20.) | _____no_output_____ | Apache-2.0 | ml/recommendation-systems/recommendation-systems.ipynb | howl-anderson/eng-edu |
Observe that adding the regularization terms results in a higher MSE, both on the training and test set. However, as we will see, the quality of the recommendations improves. This highlights a tension between fitting the observed data and minimizing the regularization terms. Fitting the observed data often emphasizes l... | user_recommendations(reg_model, DOT, exclude_rated=True, k=10) | _____no_output_____ | Apache-2.0 | ml/recommendation-systems/recommendation-systems.ipynb | howl-anderson/eng-edu |
Hopefully, these recommendations look better. You can change the similarity measure from COSINE to DOT and observe how this affects the recommendations.Since the model is likely to recommend items that you rated highly, you have the option to exclude the items you rated, using `exclude_rated=True`.In the following cell... | movie_neighbors(reg_model, "Aladdin", DOT)
movie_neighbors(reg_model, "Aladdin", COSINE) | _____no_output_____ | Apache-2.0 | ml/recommendation-systems/recommendation-systems.ipynb | howl-anderson/eng-edu |
Here we compare the embedding norms for `model` and `reg_model`. Selecting a subset of the embeddings will highlight them on both charts simultaneously. | movie_embedding_norm([model, model_lowinit, reg_model])
# Visualize the embeddings
tsne_movie_embeddings(reg_model) | _____no_output_____ | Apache-2.0 | ml/recommendation-systems/recommendation-systems.ipynb | howl-anderson/eng-edu |
We should observe that the embeddings have a lot more structure than the unregularized case. Try selecting different genres and observe how they tend to form clusters (for example Horror, Animation and Children). ConclusionThis concludes this section on matrix factorization models. Note that while the scale of the prob... | rated_movies = (ratings[["user_id", "movie_id"]]
.groupby("user_id", as_index=False)
.aggregate(lambda x: list(x)))
rated_movies.head() | _____no_output_____ | Apache-2.0 | ml/recommendation-systems/recommendation-systems.ipynb | howl-anderson/eng-edu |
We then create a function that generates an example batch, such that each example contains the following features:- movie_id: A tensor of strings of the movie ids that the user rated.- genre: A tensor of strings of the genres of those movies- year: A tensor of strings of the release year. | #@title Batch generation code (run this cell)
years_dict = {
movie: year for movie, year in zip(movies["movie_id"], movies["year"])
}
genres_dict = {
movie: genres.split('-')
for movie, genres in zip(movies["movie_id"], movies["all_genres"])
}
def make_batch(ratings, batch_size):
"""Creates a batch of ex... | _____no_output_____ | Apache-2.0 | ml/recommendation-systems/recommendation-systems.ipynb | howl-anderson/eng-edu |
Loss functionRecall that the softmax model maps the input features $x$ to a user embedding $\psi(x) \in \mathbb R^d$, where $d$ is the embedding dimension. This vector is then multiplied by a movie embedding matrix $V \in \mathbb R^{m \times d}$ (where $m$ is the number of movies), and the final output of the model is... | def softmax_loss(user_embeddings, movie_embeddings, labels):
"""Returns the cross-entropy loss of the softmax model.
Args:
user_embeddings: A tensor of shape [batch_size, embedding_dim].
movie_embeddings: A tensor of shape [num_movies, embedding_dim].
labels: A sparse tensor of dense_shape [batch_size, ... | _____no_output_____ | Apache-2.0 | ml/recommendation-systems/recommendation-systems.ipynb | howl-anderson/eng-edu |
Exercise 8: Build a softmax model, train it, and inspect its embeddings.We are now ready to build a softmax CFModel. Complete the `build_softmax_model` function in the next cell. The architecture of the model is defined in the function `create_user_embeddings` and illustrated in the figure below. The input embeddings ... | def build_softmax_model(rated_movies, embedding_cols, hidden_dims):
"""Builds a Softmax model for MovieLens.
Args:
rated_movies: DataFrame of traing examples.
embedding_cols: A dictionary mapping feature names (string) to embedding
column objects. This will be used in tf.feature_column.input_layer() t... | _____no_output_____ | Apache-2.0 | ml/recommendation-systems/recommendation-systems.ipynb | howl-anderson/eng-edu |
Train the Softmax modelWe are now ready to train the softmax model. You can set the following hyperparameters:- learning rate- number of iterations. Note: you can run `softmax_model.train()` again to continue training the model from its current state.- input embedding dimensions (the `input_dims` argument)- number of ... | # Create feature embedding columns
def make_embedding_col(key, embedding_dim):
categorical_col = tf.feature_column.categorical_column_with_vocabulary_list(
key=key, vocabulary_list=list(set(movies[key].values)), num_oov_buckets=0)
return tf.feature_column.embedding_column(
categorical_column=categorical... | _____no_output_____ | Apache-2.0 | ml/recommendation-systems/recommendation-systems.ipynb | howl-anderson/eng-edu |
Inspect the embeddingsWe can inspect the movie embeddings as we did for the previous models. Note that in this case, the movie embeddings are used at the same time as input embeddings (for the bag of words representation of the user history), and as softmax weights. | movie_neighbors(softmax_model, "Aladdin", DOT)
movie_neighbors(softmax_model, "Aladdin", COSINE)
movie_embedding_norm([reg_model, softmax_model])
tsne_movie_embeddings(softmax_model) | _____no_output_____ | Apache-2.0 | ml/recommendation-systems/recommendation-systems.ipynb | howl-anderson/eng-edu |
**[Machine Learning Course Home Page](kaggle.com/learn/machine-learning).**--- Selecting Data for ModelingYour dataset had too many variables to wrap your head around, or even to print out nicely. How can you pare down this overwhelming amount of data to something you can understand?We'll start by picking a few varia... | import pandas as pd
melbourne_file_path = '../input/melbourne-housing-snapshot/melb_data.csv'
melbourne_data = pd.read_csv(melbourne_file_path)
melbourne_data.columns
# The Melbourne data has some missing values (some houses for which some variables weren't recorded.)
# We'll learn to handle missing values in a later... | _____no_output_____ | Apache-2.0 | learntools/machine_learning/nbs/tut3.ipynb | rosbo/learntools |
There are many ways to select a subset of your data. The [Pandas Course](https://www.kaggle.com/learn/pandas) covers these in more depth, but we will focus on two approaches for now.1. Dot notation, which we use to select the "prediction target"2. Selecting with a column list, which we use to select the Selecting The ... | y = melbourne_data.Price | _____no_output_____ | Apache-2.0 | learntools/machine_learning/nbs/tut3.ipynb | rosbo/learntools |
Choosing "Features"The columns that are inputted into our model (and later used to make predictions) are called "features." In our case, those would be the columns used to determine the home price. Sometimes, you will use all columns except the target as features. Other times you'll be better off with fewer features. ... | melbourne_features = ['Rooms', 'Bathroom', 'Landsize', 'Lattitude', 'Longtitude'] | _____no_output_____ | Apache-2.0 | learntools/machine_learning/nbs/tut3.ipynb | rosbo/learntools |
By convention, this data is called **X**. | X = melbourne_data[melbourne_features] | _____no_output_____ | Apache-2.0 | learntools/machine_learning/nbs/tut3.ipynb | rosbo/learntools |
Let's quickly review the data we'll be using to predict house prices using the `describe` method and the `head` method, which shows the top few rows. | X.describe()
X.head() | _____no_output_____ | Apache-2.0 | learntools/machine_learning/nbs/tut3.ipynb | rosbo/learntools |
Visually checking your data with these commands is an important part of a data scientist's job. You'll frequently find surprises in the dataset that deserve further inspection. --- Building Your ModelYou will use the **scikit-learn** library to create your models. When coding, this library is written as **sklearn**, ... | from sklearn.tree import DecisionTreeRegressor
# Define model. Specify a number for random_state to ensure same results each run
melbourne_model = DecisionTreeRegressor(random_state=1)
# Fit model
melbourne_model.fit(X, y) | _____no_output_____ | Apache-2.0 | learntools/machine_learning/nbs/tut3.ipynb | rosbo/learntools |
Many machine learning models allow some randomness in model training. Specifying a number for `random_state` ensures you get the same results in each run. This is considered a good practice. You use any number, and model quality won't depend meaningfully on exactly what value you choose.We now have a fitted model that ... | print("Making predictions for the following 5 houses:")
print(X.head())
print("The predictions are")
print(melbourne_model.predict(X.head())) | _____no_output_____ | Apache-2.0 | learntools/machine_learning/nbs/tut3.ipynb | rosbo/learntools |
Assignment:Beat the performance of my Lasso regression by **using different feature engineering steps ONLY!!**.The performance of my current model, as shown in this notebook is:- test rmse: 44798.497576784845- test r2: 0.7079639526659389To beat my model you will need a test r2 bigger than 0.71 and a rmse smaller than ... | from math import sqrt
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# for the model
from sklearn.model_selection import train_test_split
from sklearn.linear_model import Lasso
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.metrics import mean_s... | _____no_output_____ | BSD-3-Clause | 13-Assignement_Gian.ipynb | rahuliitb/udemy-feml-challenge |
Load Datasets | # load dataset
data = pd.read_csv('../houseprice.csv')
# make lists of variable types
categorical_vars = [var for var in data.columns if data[var].dtype == 'O']
year_vars = [var for var in data.columns if 'Yr' in var or 'Year' in var]
discrete_vars = [
var for var in data.columns if data[var].dtype != 'O'
a... | There are 19 continuous variables
There are 13 discrete variables
There are 4 temporal variables
There are 43 categorical variables
| BSD-3-Clause | 13-Assignement_Gian.ipynb | rahuliitb/udemy-feml-challenge |
Separate train and test set | # IMPORTANT: keep the random_state to zero for reproducibility
# Let's separate into train and test set
X_train, X_test, y_train, y_test = train_test_split(data.drop(
['Id', 'SalePrice'], axis=1),
data['SalePrice'],
test_size=0.1,
random_state=0)
# calculate elapsed time
def elapsed_years(df, var):
... | _____no_output_____ | BSD-3-Clause | 13-Assignement_Gian.ipynb | rahuliitb/udemy-feml-challenge |
Feature Engineering Pipeline | ## functions to encode rare categories
def find_non_rare_labels(df, variable, tolerance):
temp = df.groupby([variable])[variable].count()/len(df)
non_rare = [x for x in temp.loc[temp>tolerance].index.values]
return non_rare
def rare_encoding(X_train, X_test, variable, tolerance):
X_train = X... | train mse: 684649908.3271698
train rmse: 26165.815644217357
train r2: 0.8903477989380937
test mse: 1448795526.4934826
test rmse: 38063.04673161993
test r2: 0.7891776453011499
| BSD-3-Clause | 13-Assignement_Gian.ipynb | rahuliitb/udemy-feml-challenge |
We see an improvement on both rmse and r2 score with respect to the baseline as desired :) | # plot predictions vs real value
plt.scatter(y_test,X_test_preds)
plt.xlabel('True Price')
plt.ylabel('Predicted Price')
plt.xlim(0,800000)
plt.ylim(0,800000); | _____no_output_____ | BSD-3-Clause | 13-Assignement_Gian.ipynb | rahuliitb/udemy-feml-challenge |
Combining and merging dataframes Setup | # Connect my Google Drive to Google Colab
from google.colab import drive
drive.mount ('/content/gdrive')
# Change the working directory -Alex's version as he has a shared folder
# %cd /content/gdrive/MyDrive/swd1a-python-2021-10
# Change the working directory - Martin's version
%cd /content/gdrive/MyDrive/Colab Noteboo... | total 394
-rw------- 1 root root 35824 Oct 18 13:50 010_starting_with_python.ipynb
-rw------- 1 root root 96573 Oct 25 14:07 020_starting_with_data.ipynb
-rw------- 1 root root 216480 Oct 25 15:00 030_indexing_and_types.ipynb
-rw------- 1 root root 49257 Nov 1 13:56 040_dataframes.ipynb
drwx------ 2 root root 409... | CC-BY-4.0 | notebooks/040_dataframes.ipynb | ARCTraining/python-2021-04 |
Combining dataframes | # import pandas
import pandas as pd
surveys_df = pd.read_csv("data/surveys.csv", keep_default_na=False, na_values=[""])
surveys_df.head()
species_df = pd.read_csv("data/species.csv", keep_default_na=False, na_values=[""])
species_df.head()
# make some fragments of surveys_df
surveys_sub = surveys_df.head(10)
surve... | _____no_output_____ | CC-BY-4.0 | notebooks/040_dataframes.ipynb | ARCTraining/python-2021-04 |
Joining dataframes together Combining DataFrames using a common field is called “joining”. The columns containing the common values are called “join key(s)”. Joining DataFrames in this way is often useful when one DataFrame is a “lookup table” containing additional data that we want to include in the other.NOTE: This ... | # Lets get some data
# Read in 10 lines of the surveys table
# import pandas first
import pandas as pd
surveys_df = pd.read_csv("data/surveys.csv", keep_default_na=False, na_values=[""])
survey_sub = surveys_df.head(10)
# Grab a small subset of the species data
species_sub = pd.read_csv('data/speciesSubset.csv', k... | _____no_output_____ | CC-BY-4.0 | notebooks/040_dataframes.ipynb | ARCTraining/python-2021-04 |
Inner JoinAn inner join combines two DataFrames based on a join key and returns a new DataFrame that contains only those rows that have matching values in both of the original DataFrames. 
# Take a look at the data
merged_inner.shape
merged_inner | _____no_output_____ | CC-BY-4.0 | notebooks/040_dataframes.ipynb | ARCTraining/python-2021-04 |
Left joinsWhat if we want to add information from species_sub to survey_sub without losing any of the information from survey_sub? In this case, we use a different type of join called a “left outer join”, or a “left join”.Like an inner join, a left join uses join keys to combine two DataFrames. Unlike an inner join, a... | merged_left = pd.merge(left=survey_sub, right=species_sub, how='left', left_on='species_id',
right_on='species_id')
merged_left
# If we wanted to find the rows with missing species data:
merged_left [pd.isnull(merged_left.genus)] | _____no_output_____ | CC-BY-4.0 | notebooks/040_dataframes.ipynb | ARCTraining/python-2021-04 |
The pandas merge function supports two other join types:Right (outer) join: Invoked by passing how='right' as an argument. Similar to a left join, except all rows from the right DataFrame are kept, while rows from the left DataFrame without matching join key(s) values are discarded.Full (outer) join: Invoked by passing... | # Challenge 1: Distributions
# Create a new dataframe
# by joining the contents of the surveys.csv and species.csv tables
merged_left = pd.merge (left = surveys_df, right=species_df, how="left",
on="species_id")
merged_left.shape
# Calculate and plot distribution of:
# 1. taxa per plot (number o... | _____no_output_____ | CC-BY-4.0 | notebooks/040_dataframes.ipynb | ARCTraining/python-2021-04 |
You can calculate a biodiversity index as:the number of species in the plot / the total number of individuals in the plot = Biodiversity index | plot_info = pd.read_csv("data/plots.csv")
plot_info.groupby("plot_type").count()
# Diversity index
merged_site_type = pd.merge(merged_left, plot_info, on='plot_id')
# For each plot, get the number of species for each plot
nspecies_site = merged_site_type.groupby(["plot_id"])["species"].nunique().rename("nspecies")
# Fo... | _____no_output_____ | CC-BY-4.0 | notebooks/040_dataframes.ipynb | ARCTraining/python-2021-04 |
Table of Contents-time-serie-0.1">-> time serieoutlier detection | import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
from statsmodels.graphics import tsaplots
%matplotlib inline
sns.set(rc={"figure.figsize": (15, 6)})
sns.set_palette(sns.color_palette("Set2", 10))
sns.set_style("whitegrid")
CO2_measurement = pd.read_csv('data/CO2_sensor_me... | _____no_output_____ | MIT | Exploration_Py.ipynb | gregunz/TimeSeries2018 |
-> time serie | choosen_location = 'AJGR'
choosen_id = 1122
time_serie_dirty = CO2_measurement.loc[choosen_location].loc[choosen_id] | _____no_output_____ | MIT | Exploration_Py.ipynb | gregunz/TimeSeries2018 |
outlier detection | time_serie = time_serie_dirty.copy()
time_serie[time_serie_dirty['CO2'] > 380] = np.nan
time_serie = time_serie.interpolate().resample('1H').mean()
time_serie_dif = time_serie.pct_change().dropna()
time_serie_dirty.plot()
plt.savefig('plots/raw_data.eps')
time_serie.plot()
plt.savefig('plots/raw_data_no_outliers.eps'... | _____no_output_____ | MIT | Exploration_Py.ipynb | gregunz/TimeSeries2018 |
Homework 7: Kernel K-Means and EMThis homework is due on Thursday April 1,2021 Problem 1: Kernel K-MeansIn this exercise, we will consider how one may go about performing non-linear machine learning by adapting machine learning algorithms that we have discussed in class. We will discuss one particular approach that ... | from matplotlib.patches import Ellipse
from scipy.special import logsumexp
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import math | _____no_output_____ | MIT | ec414_Intro_to_machine_learning/Kernel_K-Means_and_EM_EC414_HW7.ipynb | pequode/class-projects |
**Data creation.** Create 3 2D Gaussian clusters of data, with the following means and covariances:$\boldsymbol{\mu}_1 = [2,2]^T, \boldsymbol{\mu}_2 = [-2,0]^T, \boldsymbol{\mu}_3 = [0,-2]^T$,$\Sigma_1 = [[0.1,0];[0,0.1]]$, $\Sigma_2 = [[0.2,0];[0,0.2]]$, $\Sigma_3 = [[1,0.7];[0.7,1]]$ Create 50 points in each cluster ... | # Part a - data creation. This code is from the previous homework. You do not have to edit it.
num_pts = 50
np.random.seed(10)
Xa = np.random.multivariate_normal([2,2], [[0.1,0],[0,0.1]], num_pts)
Xb = np.random.multivariate_normal([-2,0], [[0.2,0],[0,0.2]], num_pts)
Xc = np.random.multivariate_normal([0,-2], [[1,0.7]... | (150, 2)
| MIT | ec414_Intro_to_machine_learning/Kernel_K-Means_and_EM_EC414_HW7.ipynb | pequode/class-projects |
**Fill in the code to complete the EM algorithm given below.** Remember, the EM algorithm is given by a process similar to k-means/DP-means in nature, since it is iterative. However, the actual calculations done are very different. For a Gaussian mixture model, they are described by:*E-Step (Compute probabilities with ... |
def EStep(data, n_points, k, pi, mu, cov):
## Performs the expectation (E) step ##
## You do not need to edit this function (actually, please do not edit it..)
# The end result is an n_points x k matrix, where each element is the probability that
# the ith point will be in the jth cluster.
exp... | _____no_output_____ | MIT | ec414_Intro_to_machine_learning/Kernel_K-Means_and_EM_EC414_HW7.ipynb | pequode/class-projects |
**Perform EM on the GMM you created.** Put it all together! Run the completed EM function on your dataset. (This part is already done for you, just run it and see the output. The expected results are given to you) |
def MStep(data, n_points, k, expectations):
## Performs the maximization (M) step ##
# We clear the parameters completely, since we recompute them each time
mu = [np.zeros((2,1)) for _ in np.arange(k)] # 3 2x1 np.arrays in a list
cov = [np.zeros((2,2)) for _ in np.arange(k)] # 3 2x2 np.arrays in a... | /usr/local/lib/python3.7/dist-packages/ipykernel_launcher.py:20: DeprecationWarning: np.asscalar(a) is deprecated since NumPy v1.16, use a.item() instead
| MIT | ec414_Intro_to_machine_learning/Kernel_K-Means_and_EM_EC414_HW7.ipynb | pequode/class-projects |
Problem 3: Comparison of K-Means and Gaussian MixtureWe would like you to perform K-Means and GMM for clustering using sklearn. In this Problem, we can visualize the difference of these two algorithm.First, we can general some clustered data as follows. | import matplotlib.pyplot as plt
import seaborn as sns; sns.set()
import numpy as np
from sklearn.datasets.samples_generator import make_blobs
X, y_true = make_blobs(n_samples=400, centers=4,
cluster_std=0.60, random_state=0)
X = X[:, ::-1] # flip axes for better plotting
print(X.shape)
plt.scatte... | /usr/local/lib/python3.7/dist-packages/sklearn/utils/deprecation.py:144: FutureWarning: The sklearn.datasets.samples_generator module is deprecated in version 0.22 and will be removed in version 0.24. The corresponding classes / functions should instead be imported from sklearn.datasets. Anything that cannot be import... | MIT | ec414_Intro_to_machine_learning/Kernel_K-Means_and_EM_EC414_HW7.ipynb | pequode/class-projects |
**a. Perform Kmeans and GMM on data X using build-in sklearn functions.**You can find the documentation for instantiating and fitting `sklearn`'s `Kmeans` [here](https://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html). Set `n_clusters=4` and `random_state=0`. | from sklearn.cluster import KMeans
### ADD CODE HERE:
# Instantiate KMeans instance.
# Fit the Kmeans with the data X.
# Use the Kmeans to predict on the labels of X, here the labels is unordered.
nClust = 4
randSate = 0
kmeans = KMeans(n_clusters=nClust, random_state=randSate).fit(X)
labels = kmeans.labels_
plt.scat... | _____no_output_____ | MIT | ec414_Intro_to_machine_learning/Kernel_K-Means_and_EM_EC414_HW7.ipynb | pequode/class-projects |
You can find the documentation for instantiating and fitting `sklearn`'s `GMM` [here](https://scikit-learn.org/stable/modules/generated/sklearn.mixture.GaussianMixture.html). Set `n_clusters=4` and `random_state=0`. | from sklearn.mixture import GaussianMixture as GMM
### ADD CODE HERE:
# Instantiate GMM instance.
# Fit the GMM with the data X.
# Use the GMM to predict on the labels of X, here the labels is unordered.
gm = GMM(n_components=nClust, random_state=randSate).fit(X)
labels = gm.predict(X)
plt.scatter(X[:, 0], X[:, 1], c=l... | _____no_output_____ | MIT | ec414_Intro_to_machine_learning/Kernel_K-Means_and_EM_EC414_HW7.ipynb | pequode/class-projects |
**b. Perform Kmeans and GMM on data X_stretched using build-in sklearn functions.**First we stretch the data by a random matrix. | rng = np.random.RandomState(13)
X_stretched = np.dot(X, rng.randn(2, 2)) | _____no_output_____ | MIT | ec414_Intro_to_machine_learning/Kernel_K-Means_and_EM_EC414_HW7.ipynb | pequode/class-projects |
Applying `Kmeans` on `X_stretched` and set `n_clusters=4` and `random_state=0`. | from sklearn.cluster import KMeans
### ADD CODE HERE:
# Instantiate KMeans instance.
# Fit the Kmeans with the data X.
# Use the Kmeans to predict on the labels of X, here the labels is unordered.
kmeans = KMeans(n_clusters=nClust, random_state=randSate).fit(X_stretched)
labels = kmeans.labels_
plt.scatter(X_stretched[... | _____no_output_____ | MIT | ec414_Intro_to_machine_learning/Kernel_K-Means_and_EM_EC414_HW7.ipynb | pequode/class-projects |
Applying `GMM` on `X_stretched` and set `n_clusters=4` and `random_state=0`. | from sklearn.mixture import GaussianMixture as GMM
### ADD CODE HERE:
# Instantiate GMM instance.
# Fit the GMM with the data X.
# Use the GMM to predict on the labels of X, here the labels is unordered.
gm = GMM(n_components=nClust, random_state=randSate).fit(X_stretched)
labels = gm.predict(X_stretched)
plt.scatter(X... | _____no_output_____ | MIT | ec414_Intro_to_machine_learning/Kernel_K-Means_and_EM_EC414_HW7.ipynb | pequode/class-projects |
Retirement ModelThis is a retirement model which models salary with both a constant growth rate for cost of living raises as well as regular salary increases for promotions. The model is broken up into the following sections:- [**Setup**](Setup): Runs any imports and other setup- [**Inputs**](Inputs): Defines the inpu... | from dataclasses import dataclass
import pandas as pd
%matplotlib inline | _____no_output_____ | MIT | docsrc/source/_static/Examples/Visualization/Python/Dynamic Salary Retirement Model Visualized.ipynb | whoopnip/fin-model-course |
InputsAll of the inputs for the model are defined here. A class is constructed to manage the data, and an instance of the class containing the default inputs is created. | @dataclass
class ModelInputs:
starting_salary: int = 60000
promos_every_n_years: int = 5
cost_of_living_raise: float = 0.02
promo_raise: float = 0.15
savings_rate: float = 0.25
interest_rate: float = 0.05
desired_cash: int = 1500000
model_data = ModelInputs()
model_data | _____no_output_____ | MIT | docsrc/source/_static/Examples/Visualization/Python/Dynamic Salary Retirement Model Visualized.ipynb | whoopnip/fin-model-course |
SalariesHere the salary for each year is calculated. We assume that the salary grows at a constant rate each year for cost of living raises, and then also every number of years, the salary increases by a further percentage due to a promotion or switching jobs. Based on this assumption, the salary would evolve over tim... | def salary_at_year(data: ModelInputs, year):
"""
Gets the salary at a given year from the start of the model based on cost of living raises and regular promotions.
"""
# Every n years we have a promotion, so dividing the years and taking out the decimals gets the number of promotions
num_promos = in... | _____no_output_____ | MIT | docsrc/source/_static/Examples/Visualization/Python/Dynamic Salary Retirement Model Visualized.ipynb | whoopnip/fin-model-course |
That function will get the salary at a given year, so to get all the salaries we just run it on each year. But we will not know how many years to run as we should run it until the individual is able to retire. So we are just showing the first few salaries for now and will later use this function in the [Wealths](Wealth... | for i in range(6):
year = i + 1
salary = salary_at_year(model_data, year)
print(f'The salary at year {year} is ${salary:,.0f}.') | The salary at year 1 is $61,200.
The salary at year 2 is $62,424.
The salary at year 3 is $63,672.
The salary at year 4 is $64,946.
The salary at year 5 is $76,182.
The salary at year 6 is $77,705.
| MIT | docsrc/source/_static/Examples/Visualization/Python/Dynamic Salary Retirement Model Visualized.ipynb | whoopnip/fin-model-course |
As expected, with the default inputs, the salary is increasing at 2% per year. Then at year 5, there is a promotion so there is a larger increase in salary. WealthsThe wealths portion of the model is concerned with applying the savings rate to the earned salary to calculate the cash saved, accumulating the cash saved ... | def cash_saved_during_year(data: ModelInputs, year):
"""
Calculated the cash saved within a given year, by first calculating the salary at that year then applying the
savings rate.
"""
salary = salary_at_year(data, year)
cash_saved = salary * data.savings_rate
return cash_saved | _____no_output_____ | MIT | docsrc/source/_static/Examples/Visualization/Python/Dynamic Salary Retirement Model Visualized.ipynb | whoopnip/fin-model-course |
To get the wealth at each year, it is just applying the investment return to last year's wealth, then adding this year's cash saved:$$w_t = w_{t-1} (1 + r_i) + c_t$$Where:- $w_t$: Wealth at year $t$- $r_i$: Investment rate | def wealth_at_year(data: ModelInputs, year, prior_wealth):
"""
Calculate the accumulated wealth for a given year, based on previous wealth, the investment rate,
and cash saved during the year.
"""
cash_saved = cash_saved_during_year(data, year)
wealth = prior_wealth * (1 + data.interest_rate) + ... | _____no_output_____ | MIT | docsrc/source/_static/Examples/Visualization/Python/Dynamic Salary Retirement Model Visualized.ipynb | whoopnip/fin-model-course |
Again, just like in the [Salaries](Salaries) section, we can now get the output for each year, but we don't know ultimately how many years we will have to run it. That will be determined in the [Retirement](Retirement) section. So for now, just show the first few years of wealth accumulation: | prior_wealth = 0 # starting with no cash saved
for i in range(6):
year = i + 1
wealth = wealth_at_year(model_data, year, prior_wealth)
print(f'The wealth at year {year} is ${wealth:,.0f}.')
# Set next year's prior wealth to this year's wealth
prior_wealth = wealth | The wealth at year 1 is $15,300.
The wealth at year 2 is $31,671.
The wealth at year 3 is $49,173.
The wealth at year 4 is $67,868.
The wealth at year 5 is $90,307.
The wealth at year 6 is $114,248.
| MIT | docsrc/source/_static/Examples/Visualization/Python/Dynamic Salary Retirement Model Visualized.ipynb | whoopnip/fin-model-course |
With default inputs, the wealth is going up by approximately 25% of the salary each year, plus a bit more for investment. Then in year 6 we see a substantially larger increase because the salary is substantially larger due to the promotion. So everything is looking correct. RetirementThis section of the model puts eve... | def years_to_retirement(data: ModelInputs):
# starting with no cash saved
prior_wealth = 0
wealth = 0
year = 0 # will become 1 on first loop
print('Wealths over time:') # \n makes a blank line in the output.
while wealth < data.desired_cash:
year = year + 1
weal... | _____no_output_____ | MIT | docsrc/source/_static/Examples/Visualization/Python/Dynamic Salary Retirement Model Visualized.ipynb | whoopnip/fin-model-course |
With the default inputs: | years = years_to_retirement(model_data) | Wealths over time:
The wealth at year 1 is $15,300.
The wealth at year 2 is $31,671.
The wealth at year 3 is $49,173.
The wealth at year 4 is $67,868.
The wealth at year 5 is $90,307.
The wealth at year 6 is $114,248.
The wealth at year 7 is $139,775.
The wealth at year 8 is $166,975.
The wealth at year 9 is $195,939.
... | MIT | docsrc/source/_static/Examples/Visualization/Python/Dynamic Salary Retirement Model Visualized.ipynb | whoopnip/fin-model-course |
Results Summary Put Results in a TableNow I will visualize the salaries and wealths over time. First create a function which runs the model to put these results in a DataFrame. | def get_salaries_wealths_df(data):
"""
Runs the retirement model, collecting salary and wealth information year by year and storing
into a DataFrame for further analysis.
"""
# starting with no cash saved
prior_wealth = 0
wealth = 0
year = 0 # will become 1 on first loop
... | _____no_output_____ | MIT | docsrc/source/_static/Examples/Visualization/Python/Dynamic Salary Retirement Model Visualized.ipynb | whoopnip/fin-model-course |
Also set up a function which formats the `DataFrame` for display. | def styled_salaries_wealths(df):
return df.style.format({
'Salary': '${:,.2f}',
'Wealth': '${:,.2f}'
}) | _____no_output_____ | MIT | docsrc/source/_static/Examples/Visualization/Python/Dynamic Salary Retirement Model Visualized.ipynb | whoopnip/fin-model-course |
Now call the function to save the results into the `DataFrame`. | df = get_salaries_wealths_df(model_data)
styled_salaries_wealths(df) | _____no_output_____ | MIT | docsrc/source/_static/Examples/Visualization/Python/Dynamic Salary Retirement Model Visualized.ipynb | whoopnip/fin-model-course |
Plot ResultsNow I will visualize the salaries and wealths over time. Salaries over Time | df.plot.line(x='Year', y='Salary') | _____no_output_____ | MIT | docsrc/source/_static/Examples/Visualization/Python/Dynamic Salary Retirement Model Visualized.ipynb | whoopnip/fin-model-course |
Wealths over Time | df.plot.line(x='Year', y='Wealth') | _____no_output_____ | MIT | docsrc/source/_static/Examples/Visualization/Python/Dynamic Salary Retirement Model Visualized.ipynb | whoopnip/fin-model-course |
Loading the dataset | italy_dataset = pd.read_csv("../datasets/it - feb 2021.csv")
# italy_dataset.head() | _____no_output_____ | Apache-2.0 | notebooks/trade_demo/smpc/bug_reproducing/Data Owner - Italy.ipynb | Noob-can-Compile/PySyft |
Logging into the domain | it = sy.login(email="info@openmined.org", password="changethis", port=8082) | Connecting to http://localhost:8082... done! Logging into italy... done!
| Apache-2.0 | notebooks/trade_demo/smpc/bug_reproducing/Data Owner - Italy.ipynb | Noob-can-Compile/PySyft |
Upload the dataset to Domain node | # Selecting a subset of the dataset
italy_dataset = italy_dataset[:40000]
# We will upload only the first 40k rows and three columns
# All these three columns are of `int` type
sampled_italy_dataset = italy_dataset[["Trade Flow Code", "Partner Code", "Trade Value (US$)"]].values
# Convert the dataset to numpy array
sa... | _____no_output_____ | Apache-2.0 | notebooks/trade_demo/smpc/bug_reproducing/Data Owner - Italy.ipynb | Noob-can-Compile/PySyft |
Create a Data Scientist User | it.users.create(
**{
"name": "Sheldon Cooper",
"email": "sheldon@caltech.edu",
"password": "bazinga",
"budget":10
}
) | _____no_output_____ | Apache-2.0 | notebooks/trade_demo/smpc/bug_reproducing/Data Owner - Italy.ipynb | Noob-can-Compile/PySyft |
Accept/Deny Requests to the Domain | # it_domain_node.requests
# it_domain_node.requests[-1].accept()
# it_domain_node.store.pandas[it_domain_node.store.pandas["object_type"] == "<class 'syft.core.tensor.smpc.share_tensor.ShareTensor'>"] | _____no_output_____ | Apache-2.0 | notebooks/trade_demo/smpc/bug_reproducing/Data Owner - Italy.ipynb | Noob-can-Compile/PySyft |
Copyright 2018 The TF-Agents Authors. | #@title Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under... | _____no_output_____ | Apache-2.0 | docs/tutorials/1_dqn_tutorial.ipynb | FlorisHoogenboom/agents |
Train a Deep Q Network with TF-Agents View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook Introduction This example shows how to train a [DQN (Deep Q Networks)](https://storage.googleapis.com/deepmind-media/dqn/DQNNaturePaper.pdf) age... | !sudo apt-get install -y xvfb ffmpeg
!pip install 'gym==0.10.11'
!pip install 'imageio==2.4.0'
!pip install PILLOW
!pip install 'pyglet==1.3.2'
!pip install pyvirtualdisplay
!pip install tf-agents
from __future__ import absolute_import, division, print_function
import base64
import imageio
import IPython
import matplo... | _____no_output_____ | Apache-2.0 | docs/tutorials/1_dqn_tutorial.ipynb | FlorisHoogenboom/agents |
Hyperparameters | num_iterations = 20000 # @param {type:"integer"}
initial_collect_steps = 100 # @param {type:"integer"}
collect_steps_per_iteration = 1 # @param {type:"integer"}
replay_buffer_max_length = 100000 # @param {type:"integer"}
batch_size = 64 # @param {type:"integer"}
learning_rate = 1e-3 # @param {type:"number"}
log... | _____no_output_____ | Apache-2.0 | docs/tutorials/1_dqn_tutorial.ipynb | FlorisHoogenboom/agents |
EnvironmentIn Reinforcement Learning (RL), an environment represents the task or problem to be solved. Standard environments can be created in TF-Agents using `tf_agents.environments` suites. TF-Agents has suites for loading environments from sources such as the OpenAI Gym, Atari, and DM Control.Load the CartPole envi... | env_name = 'CartPole-v0'
env = suite_gym.load(env_name) | _____no_output_____ | Apache-2.0 | docs/tutorials/1_dqn_tutorial.ipynb | FlorisHoogenboom/agents |
You can render this environment to see how it looks. A free-swinging pole is attached to a cart. The goal is to move the cart right or left in order to keep the pole pointing up. | #@test {"skip": true}
env.reset()
PIL.Image.fromarray(env.render()) | _____no_output_____ | Apache-2.0 | docs/tutorials/1_dqn_tutorial.ipynb | FlorisHoogenboom/agents |
The `environment.step` method takes an `action` in the environment and returns a `TimeStep` tuple containing the next observation of the environment and the reward for the action.The `time_step_spec()` method returns the specification for the `TimeStep` tuple. Its `observation` attribute shows the shape of observations... | print('Observation Spec:')
print(env.time_step_spec().observation)
print('Reward Spec:')
print(env.time_step_spec().reward) | _____no_output_____ | Apache-2.0 | docs/tutorials/1_dqn_tutorial.ipynb | FlorisHoogenboom/agents |
The `action_spec()` method returns the shape, data types, and allowed values of valid actions. | print('Action Spec:')
print(env.action_spec()) | _____no_output_____ | Apache-2.0 | docs/tutorials/1_dqn_tutorial.ipynb | FlorisHoogenboom/agents |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.