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
Evaluation functions
def dcg(top_k_matrix): """Compute discounted cumulative gain (DCG) for each row (user) in matrix. This measures how good the k recommendations for each user are, with decreasing weight placed on items farther down the list. DCG needs to be normalized before comparing between users (see normalized discou...
_____no_output_____
Apache-2.0
_notebooks/2021-07-02-movielens-eda-modeling.ipynb
recohut/notebook
Choose the best user-based model*Let's use cross-validation to examine MAE and NDCG@3 on out-of-sample data and choose the "best" user-based model*
lists_dict = { 'i_fold': np.arange(n_splits), 'k': [1, 2, 5, 10, 20, 50, 100], } k_recs = 3 baseline_algo = DampedUserMovieBaselineModel(damping_factor=10) user_results_df = prep_results_df(lists_dict) cols = ['test_err', 'ndcg_mean', 'ndcg_std', 'dt'] for c in cols: user_results_df[c] = np.nan for i_fold, ...
_____no_output_____
Apache-2.0
_notebooks/2021-07-02-movielens-eda-modeling.ipynb
recohut/notebook
NDCG@3 peaks at $k=50$, and MAE is pretty similar between $k=20$ to $100$, so $k=50$ is the winner.
baseline_algo = DampedUserMovieBaselineModel(damping_factor=10) best_user_model = KNNRecommender(mode='user', k=50, baseline_algo=baseline_algo)
_____no_output_____
Apache-2.0
_notebooks/2021-07-02-movielens-eda-modeling.ipynb
recohut/notebook
Choose the best item-based model*Let's use cross-validation to examine MAE and NDCG@3 on out-of-sample data and choose the "best" item-based model.*
lists_dict = { 'i_fold': np.arange(n_splits), 'k': [1, 2, 5, 10, 20, 50, 100], } k_recs = 3 baseline_algo = DampedUserMovieBaselineModel(damping_factor=10) item_results_df = prep_results_df(lists_dict) cols = ['test_err', 'ndcg_mean', 'ndcg_std', 'dt'] for c in cols: item_results_df[c] = np.nan for i_fold, ...
_____no_output_____
Apache-2.0
_notebooks/2021-07-02-movielens-eda-modeling.ipynb
recohut/notebook
Here, $k=10$ and $k=20$ have similar MAE and NDCG@3, we'll favor higher $k$ in nearest neigbor methods because higher $k$ is less prone to overfitting. $k=20$ is the winner of the item-based models.
baseline_algo = DampedUserMovieBaselineModel(damping_factor=10) best_item_model = KNNRecommender(mode='item', k=20, baseline_algo=baseline_algo)
_____no_output_____
Apache-2.0
_notebooks/2021-07-02-movielens-eda-modeling.ipynb
recohut/notebook
Choose the best ALS modelLet's use cross-validation to examine MAE and NDCG@3 on out-of-sample data and choose the "best" ALS model.
max_epochs = 15 lists_dict = { 'i_fold': np.arange(n_splits), 'i_epoch': np.arange(max_epochs), 'k': [5, 10, 50], } k_recs = 3 baseline_algo = DampedUserMovieBaselineModel(damping_factor=10) als_epoch_results_df = prep_results_df(lists_dict) cols = ['test_err', 'ndcg_mean', 'ndcg_std', 'dt'] for c in cols: ...
_____no_output_____
Apache-2.0
_notebooks/2021-07-02-movielens-eda-modeling.ipynb
recohut/notebook
Here, it looks like MAE is pretty flat with respect to the learning rate $\lambda$, but NDCG@3 shows some interesting variations. The highest NDCG@3 comes from $\lambda=0.1$ and $k>=50$. With matrix factorization methods like ALS, we want to favor lower $k$ for better generalizability, so $\lambda=0.1$ and $k=50$ is th...
baseline_algo = DampedUserMovieBaselineModel(damping_factor=10) best_als_model = ALSRecommender(k=50, lmbda=0.1, max_epochs=30, baseline_algo=baseline_algo)
_____no_output_____
Apache-2.0
_notebooks/2021-07-02-movielens-eda-modeling.ipynb
recohut/notebook
Choose the best SGD model*Let's use cross-validation to examine MAE and NDCG@3 on out-of-sample data and choose the "best" SGD model.*
max_epochs = 15 lists_dict = { 'i_fold': np.arange(n_splits), 'i_epoch': np.arange(max_epochs), 'k': [5, 10, 50], } k_recs = 3 baseline_algo = DampedUserMovieBaselineModel(damping_factor=10) sgd_epoch_results_df = prep_results_df(lists_dict) cols = ['test_err', 'ndcg_mean', 'ndcg_std', 'dt'] for c in cols: ...
_____no_output_____
Apache-2.0
_notebooks/2021-07-02-movielens-eda-modeling.ipynb
recohut/notebook
Compare the top methods of each category
final_models = [best_user_model, best_item_model, best_als_model, best_sgd_model] final_model_names = ['user', 'item', 'als', 'sgd'] final_results = pd.DataFrame(columns=['model', 'i_fold', 'test_err', 'ndcg_mean', 'ndcg_std', 'dt']) for model, name in zip(final_models, final_model_names): for i_fold, (train_inds, ...
_____no_output_____
Apache-2.0
_notebooks/2021-07-02-movielens-eda-modeling.ipynb
recohut/notebook
Fetching posters
n_splits = 3 skf = StratifiedKFold(n_splits=n_splits, random_state=0) splits = [ (train_inds, test_inds) for train_inds, test_inds in skf.split(ratings_df, ratings_df['user_id']) ] baseline_algo = DampedUserMovieBaselineModel(damping_factor=10) reg = 0.0 models_dict = { 'user': KNNRecommender(mode='user', k...
_____no_output_____
Apache-2.0
_notebooks/2021-07-02-movielens-eda-modeling.ipynb
recohut/notebook
Movies this user likes
user = 10 train_inds, test_inds = splits[0] train_df, test_df = ratings_df.iloc[train_inds], ratings_df.iloc[test_inds] favorite_movies = ( train_df[train_df['user_id']==user] .sort_values('rating', ascending=False) .iloc[:5, 1] .values ) display_posters(favorite_movies, base_url, links_df, api_key)
_____no_output_____
Apache-2.0
_notebooks/2021-07-02-movielens-eda-modeling.ipynb
recohut/notebook
Recommended movies
model = models_dict['als'] movies, preds = recommend(model, train_df, user, pretrained=True, k=5) display_posters(movies, base_url, links_df, api_key)
_____no_output_____
Apache-2.0
_notebooks/2021-07-02-movielens-eda-modeling.ipynb
recohut/notebook
Non-Negative Matrix Factorization (NMF, scikit-learn package)Find two non-negative matrices (W, H) whose product approximates the non-negative matrix R.NOTE: since the values of matrix R MUST be all positive, we CAN'T do mean-centering normalization here (although this would improve the accuracy).
from sklearn.decomposition import NMF nmf_model = NMF(n_components=20) # starts with 20 latents factors # Matrix factorization # V ~ W.H (Find two non-negative matrices (W, H) whose product approximates the non- negative matrix X. ) nmf_model.fit(rating_matrix) # R can be array-...
Item features - M: (1682, 20) User features - Theta: (943, 20) R ~ M * Theta.T: [[4.5 2.06 1.41 ... 0. 0.02 0.03] [2.34 0.03 0.17 ... 0.02 0. 0. ] [0.19 0.02 0.1 ... 0.01 0. 0. ] ... [1.98 0.05 0.3 ... 0. 0. 0. ] [1.39 0.1 0.03 ... 0.01 0.01 0. ] [1.6 2.24 1.38 ... 0. 0.03 0.02]] (943, 1682)...
Apache-2.0
_notebooks/2021-07-02-movielens-eda-modeling.ipynb
recohut/notebook
Estimating the error (RMSE) before tuning the hyperparameters
from sklearn.metrics import mean_squared_error def get_rmse(pred, actual): pred = pred[actual.nonzero()].flatten() # Ignore nonzero terms actual = actual[actual.nonzero()].flatten() # Ignore nonzero terms return np.sqrt(mean_squared_error(pred, actual)) get_rmse(R_pred, rating_matrix)
_____no_output_____
Apache-2.0
_notebooks/2021-07-02-movielens-eda-modeling.ipynb
recohut/notebook
When the predictive model is satisfying, save it to a file
import pickle with open('nnmf_sklearn.pickle', 'wb') as f: pickle.dump(nmf_model, f)
_____no_output_____
Apache-2.0
_notebooks/2021-07-02-movielens-eda-modeling.ipynb
recohut/notebook
Item recommendation for an active user (given its rating history)
def make_recommendation_activeuser(R, prediction, user_idx, k=5): ''' user_idx ...... select an active user k ............ number of movies to recommend ''' rated_items_df_user = pd.DataFrame(R).iloc[user_idx, :] # get the list of actual ratings of user_idx (seen movies) user_prediction_df_...
Preferred movies for user # 50 rating prediction title 171 5.0 1.432029 NaN 180 5.0 2.277069 NaN 172 5.0 1.017789 NaN 49 5.0 2.753084 NaN 143 5.0 0.695904 NaN Recommended movies for user # 50 rating prediction title 55 0.0 1.527510 NaN 173 0.0 1...
Apache-2.0
_notebooks/2021-07-02-movielens-eda-modeling.ipynb
recohut/notebook
Item recommendation for a new user (wih rating history)
# creating a new user profile: my_ratings = np.zeros((1682,1), dtype=int) my_ratings[0] = 4 my_ratings[1] = 4 my_ratings[10] = 1 my_ratings[15] = 3 my_ratings[27] = 4 my_ratings[34] = 1 my_ratings[49] = 1 my_ratings[55] = 1 my_ratings[61] = 1 my_ratings[68] = 5 my_ratings[70] = 4 my_ratings[81] = 4 my_ratings[87] = ...
_____no_output_____
Apache-2.0
_notebooks/2021-07-02-movielens-eda-modeling.ipynb
recohut/notebook
Item recommendation for a new user (wihout rating history)
def make_recommendation_newuser(item_sim, item_idx, k=5): ''' item_idx ...... select an item k ............ number of movies to recommend ''' reco_item_df = pd.DataFrame(item_sim).iloc[item_idx, :] reco_item_df = pd.concat([reco_item_df, item_info], axis=1) # merge list with the movie's title reco_ite...
_____no_output_____
Apache-2.0
_notebooks/2021-07-02-movielens-eda-modeling.ipynb
recohut/notebook
Hybrid (using processed dataset)1. Run Content based filtering and determine the movies which we want to recommend to the user.2. Filter and sort the recommendations of CF using SVD predicted ratings. Setup
!git clone https://github.com/vivdalal/movie-recommender-system.git from math import sqrt import pandas as pd import numpy as np import seaborn as sns from matplotlib import pyplot as plt from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import linear_kernel # Reading ratings f...
fatal: destination path 'movie-recommender-system' already exists and is not an empty directory.
Apache-2.0
_notebooks/2021-07-02-movielens-eda-modeling.ipynb
recohut/notebook
Content-based model
tfihmovies_genres = TfidfVectorizer(token_pattern = '[a-zA-Z0-9\-]+') hmovies['genres'] = hmovies['genres'].replace(to_replace="(no genres listed)", value="") tfihmovies_genres_matrix = tfihmovies_genres.fit_transform(hmovies['genres']) cosine_sim_movies = linear_kernel(tfihmovies_genres_matrix, tfihmovies_genres_matri...
_____no_output_____
Apache-2.0
_notebooks/2021-07-02-movielens-eda-modeling.ipynb
recohut/notebook
SVD Collaborative model
# !pip install -q surprise from surprise import Reader, Dataset, SVD from surprise.model_selection import cross_validate reader = Reader() data = Dataset.load_from_df(ratings_df[['user_id', 'item_id', 'rating']], reader) svd = SVD() cross_validate(svd, data, measures=['RMSE', 'MAE'], cv=5, verbose=True) trainset = ...
Evaluating RMSE, MAE of algorithm SVD on 5 split(s). Fold 1 Fold 2 Fold 3 Fold 4 Fold 5 Mean Std RMSE (testset) 0.9328 0.9330 0.9455 0.9341 0.9322 0.9355 0.0050 MAE (testset) 0.7339 0.7376 0.7440 0.7374 0.7330 0.7372 0.0039 Fit time 5.14 5.14 5.24 ...
Apache-2.0
_notebooks/2021-07-02-movielens-eda-modeling.ipynb
recohut/notebook
Hybrid model
def hybrid_content_svd_model(userId): recommended_movies_by_content_model = get_recommendation_content_model(userId) recommended_movies_by_content_model = hmovies[hmovies.apply(lambda movie: movie["title"] in recommended_movies_by_content_model, axis=1)] for key, columns in recommended_movies_by_content_mod...
/usr/local/lib/python3.6/dist-packages/pandas/core/indexing.py:1596: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing...
Apache-2.0
_notebooks/2021-07-02-movielens-eda-modeling.ipynb
recohut/notebook
LightFM - BPR & WARP
# !pip install -q lightfm import numpy as np from lightfm.datasets import fetch_movielens from lightfm import LightFM from lightfm.evaluation import precision_at_k from lightfm.evaluation import auc_score movielens = fetch_movielens() for key, value in movielens.items(): print(key, type(value), value.shape) lfm_...
Precision: train 0.59, test 0.20. AUC: train 0.90, test 0.88.
Apache-2.0
_notebooks/2021-07-02-movielens-eda-modeling.ipynb
recohut/notebook
BPR optimises for ROC. The WARP model, on the other hand, optimises for precision@k---we should expect its performance to be better on precision.
model = LightFM(learning_rate=0.05, loss='warp') model.fit_partial(lfm_train, epochs=10) train_precision = precision_at_k(model, lfm_train, k=10).mean() test_precision = precision_at_k(model, lfm_test, k=10, train_interactions=lfm_train).mean() train_auc = auc_score(model, lfm_train).mean() test_auc = auc_score(model...
Precision: train 0.60, test 0.22. AUC: train 0.94, test 0.93.
Apache-2.0
_notebooks/2021-07-02-movielens-eda-modeling.ipynb
recohut/notebook
Microsoft Library - FastAI-Collab
%cd /content/4CED0278/4CED0278 import os import sys import time import itertools import numpy as np import pandas as pd import torch, fastai from fastai.collab import EmbeddingDotBias, collab_learner, CollabDataBunch, load_learner from reco_utils.dataset.python_splitters import python_stratified_split from reco_utils...
_____no_output_____
Apache-2.0
_notebooks/2021-07-02-movielens-eda-modeling.ipynb
recohut/notebook
Now we will create a `collab_learner` for the data, which by default uses the `EmbeddingDotBias` model. We will be using 40 latent factors. This will create an embedding for the users and the items that will map each of these to 40 floats as can be seen below. Note that the embedding parameters are not predefined, but ...
learn = collab_learner(data, n_factors=N_FACTORS, y_range=[0,5.5], wd=1e-1) learn.model
_____no_output_____
Apache-2.0
_notebooks/2021-07-02-movielens-eda-modeling.ipynb
recohut/notebook
Now train the model for 5 epochs setting the maximal learning rate. The learner will reduce the learning rate with each epoch using cosine annealing
learn.fit_one_cycle(EPOCHS, max_lr=5e-3) # save the learner learn.export('movielens_model.pkl')
_____no_output_____
Apache-2.0
_notebooks/2021-07-02-movielens-eda-modeling.ipynb
recohut/notebook
Evaluation
# load the learner learner = load_learner(path=".", file='movielens_model.pkl') # get all users and items that the model knows total_users, total_items = learner.data.train_ds.x.classes.values() total_items = total_items[1:] total_users = total_users[1:] # get all users from the test set and remove any users that wer...
_____no_output_____
Apache-2.0
_notebooks/2021-07-02-movielens-eda-modeling.ipynb
recohut/notebook
VisualsThis notebook contains visual output functions for Constitutive Models, more specifically for a bounding surface model by Borjas & Amies, 1994. The functions are developed and maintained by Justin Bonus (University of Washington).Use ``%run YOURPATH/'Bounding Surface'/Visuals.ipynb`` at the start of your notebo...
def visBorjas3D(R_B, R_F, Stress0): #======================================================================== # Visualizing the Borjas constitutive model in 3D #======================================================================== #Base code for generic cylinder plotting: #Created on Sun Oct 2 1...
_____no_output_____
MIT
Visuals.ipynb
JustinBonus/Borja-Amies
Branching GP Regression on hematopoietic data--*Alexis Boukouvalas, 2017***Note:** this notebook is automatically generated by [Jupytext](https://jupytext.readthedocs.io/en/latest/index.html), see the README for instructions on working with it.test changeBranching GP regression with Gaussian noise on the hematopoiesis ...
import time import numpy as np import pandas as pd from matplotlib import pyplot as plt import BranchedGP plt.style.use("ggplot") %matplotlib inline
_____no_output_____
Apache-2.0
notebooks/Hematopoiesis.ipynb
ManchesterBioinference/BranchedGP
Read the hematopoiesis data. This has been simplified to a small subset of 23 genes found to be branching.We have also performed Monocle2 (version 2.1) - DDRTree on this data. The results loaded include the Monocle estimated pseudotime, branching assignment (state) and the DDRTree latent dimensions.
Y = pd.read_csv("singlecelldata/hematoData.csv", index_col=[0]) monocle = pd.read_csv("singlecelldata/hematoMonocle.csv", index_col=[0]) Y.head() monocle.head() # Plot Monocle DDRTree space genelist = ["FLT3", "KLF1", "MPO"] f, ax = plt.subplots(1, len(genelist), figsize=(10, 5), sharex=True, sharey=True) for ig, g in ...
_____no_output_____
Apache-2.0
notebooks/Hematopoiesis.ipynb
ManchesterBioinference/BranchedGP
Fit BGP modelNotice the cell assignment uncertainty is higher for cells close to the branching point.
def FitGene(g, ns=20): # for quick results subsample data t = time.time() Bsearch = list(np.linspace(0.05, 0.95, 5)) + [ 1.1 ] # set of candidate branching points GPy = (Y[g].iloc[::ns].values - Y[g].iloc[::ns].values.mean())[ :, None ] # remove mean from gene expression data ...
CTSG BGP inference completed in 64.9 seconds.
Apache-2.0
notebooks/Hematopoiesis.ipynb
ManchesterBioinference/BranchedGP
A Jupyter Notebook exploring the Scipy.Stats module for Python. [scipy.stats offfical](https://docs.scipy.org/doc/scipy/reference/stats.html)The Scipy.Stats module for Python offers a wide array of probability distributions, summary and frequency statistics, correlation functions and statistical tests, masked statisti...
# import modules # numerical operations import numpy as np # general plotting import matplotlib.pyplot as plt # data frames import pandas as pd # statistical operations import scipy.stats as ss # statistical plots import seaborn as sns
_____no_output_____
MIT
scipy-stats.ipynb
killfoley/ML-and-Stats
Example One-Way ANOVA: Golf Ball driving distance dataset***Premium golf ball manufacturers are constantly looking at ways to develop and improve their golf balls for both professional and amateur players. One attribute of a premium golf ball that is extremely important to professional and amateur golfers alike is the...
# read in the dataset df = pd.read_csv('https://raw.githubusercontent.com/killfoley/ML-and-Stats/main/data/golf_ball.csv') df
_____no_output_____
MIT
scipy-stats.ipynb
killfoley/ML-and-Stats
Assumption 1 - The dependent variable should be measured at the interval or ratio level (in this case metres probably actually yards)***
# dependent variable v_dep = df['distance'] v_dep # describe the data v_dep.describe()
_____no_output_____
MIT
scipy-stats.ipynb
killfoley/ML-and-Stats
Assumption 2 - The independent variable should consist of two or more categorical, independent groups.***
# independent variabl v_indep = df['ball'] v_indep
_____no_output_____
MIT
scipy-stats.ipynb
killfoley/ML-and-Stats
Note: There are three independent categories 'current', 'new', and 'prototype' **Assumption 3** - There should be independence of observations, which means that there is no relationship between the observations in each group or between the groups themselves.This cannot really be shown using the data, it is more of an e...
# Boxplot of variables sns.boxplot(x=v_dep, y=v_indep)
_____no_output_____
MIT
scipy-stats.ipynb
killfoley/ML-and-Stats
There appear to be no outliers in this dataset.*** **Assumption 5** - The dependent variable should be approximately normally distributed for each category of the independent variable.Testing for normality is performed using the Shapiro-Wilk test of normality. [Scipy.Stats](https://docs.scipy.org/doc/scipy/reference/ge...
# Get the distance values for the current golf ball using pandas query x_current = df.query('ball=="current"')['distance'] x_current # get the distance values for the new ball x_new = df.query('ball=="new"')['distance'] x_new # get the distance values for the new ball x_proto = df.query('ball=="prototype"')['distance']...
_____no_output_____
MIT
scipy-stats.ipynb
killfoley/ML-and-Stats
All three datasets have a high probability of being normally distributed with p values significantly > 0.05*** **Data Visualisation Plot**A distribution plot from Seaborn is one of the most effective ways to display datasets. Display each of the datasets with the kernel density estimation. This is a nice way of visuali...
# KDEs of the three types of golf ball. sns.displot(x=v_dep, hue=v_indep, kind="kde")
_____no_output_____
MIT
scipy-stats.ipynb
killfoley/ML-and-Stats
The plot above shows each of the variables. Each one is observed to display a decent normal distribution*** **Assumption 6** - there needs to be homogeneity of variances. This can be tested using Levene test in scipy.stats. [Scipy.Stats.Levene](https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.levene.htm...
# test the 3 variables for homegeneity of variance stat, p = ss.levene(x_current, x_new, x_proto) print(f"Levene test values: Stat={stat}, pvalue={p}")
Levene test values: Stat=0.2117145198685934, pvalue=0.8095049922609396
MIT
scipy-stats.ipynb
killfoley/ML-and-Stats
Since the p value is greater than 0.05 it can be accepted that the 3 variables display close enough to equal variance to proceed with the onw-way ANOVA.*** One-Way ANOVASince the data have satisfied the 6 assumptions required to perform a One-Way ANOVA, the test can now be performed on the data.
# One-way ANOVA scipy.stats ss.f_oneway( x_current, x_new, x_proto)
_____no_output_____
MIT
scipy-stats.ipynb
killfoley/ML-and-Stats
Interpretting the resultsTo determine whether any of the differences between the means are statistically significant, a p-value > 0.05 would be required to accept the null hypothesis. In this case the p value of 0.158 means that there is no significant difference in mean distance between each golf ball and the manufac...
print(f"Mean Current: {np.mean(x_current)}, Mean New: {np.mean(x_new)}, Mean Prototype: {np.mean(x_proto)}")
Mean Current: 270.275, Mean New: 267.5, Mean Prototype: 271.4
MIT
scipy-stats.ipynb
killfoley/ML-and-Stats
Demo: `gpflow.training.monitor`In this notebook we'll demo how to use `gpflow.training.monitor` for logging the optimisation of a GPflow model. Creating the GPflow modelWe first generate some random data and create a GPflow model.Under the hood, GPflow gives a unique name to each model which is used to name the Variab...
np.random.seed(0) X = np.random.rand(10000, 1) * 10 Y = np.sin(X) + np.random.randn(*X.shape) Xt = np.random.rand(10000, 1) * 10 Yt = np.sin(Xt) + np.random.randn(*Xt.shape) with gpflow.defer_build(): m = gpflow.models.SVGP(X, Y, gpflow.kernels.RBF(1), gpflow.likelihoods.Gaussian(), Z=np...
_____no_output_____
Apache-2.0
doc/source/notebooks/monitor-tensorboard.ipynb
codelover-without-talent/GPflow
Let's compute log likelihood before the optimisation
print('LML before the optimisation: %f' % m.compute_log_likelihood())
LML before the optimisation: -1271605.621944
Apache-2.0
doc/source/notebooks/monitor-tensorboard.ipynb
codelover-without-talent/GPflow
We will be using a TensorFlow optimiser. All TensorFlow optimisers have a support for `global_step` variable. Its purpose is to track how many optimisation steps have occurred. It is useful to keep this in a TensorFlow variable as this allows it to be restored together with all the parameters of the model.The code belo...
session = m.enquire_session() global_step = mon.create_global_step(session)
_____no_output_____
Apache-2.0
doc/source/notebooks/monitor-tensorboard.ipynb
codelover-without-talent/GPflow
Construct the monitorNext we need to construct the monitor. `gpflow.training.monitor` provides classes that are building blocks for the monitor. Essengially, a monitor is a function that is provided as a callback to an optimiser. It consists of a number of tasks that may be executed at each step, subject to their runn...
print_task = mon.PrintTimingsTask().with_name('print')\ .with_condition(mon.PeriodicIterationCondition(10))\ .with_exit_condition(True) sleep_task = mon.SleepTask(0.01).with_name('sleep').with_name('sleep') saver_task = mon.CheckpointTask('./monitor-saves').with_name('saver')\ .with_condition(mon.Periodic...
_____no_output_____
Apache-2.0
doc/source/notebooks/monitor-tensorboard.ipynb
codelover-without-talent/GPflow
As the above code shows, each task can be assigned a name and running conditions. The name will be shown in the task timing summary.There are two different types of running conditions: `with_condition` controls execution of the task at each iteration in the optimisation loop. `with_exit_condition` is a simple boolean f...
class CustomTensorBoardTask(mon.BaseTensorBoardTask): def __init__(self, file_writer, model, Xt, Yt): super().__init__(file_writer, model) self.Xt = Xt self.Yt = Yt self._full_test_err = tf.placeholder(gpflow.settings.tf_float, shape=()) self._full_test_nlpp = tf.placeholder(...
_____no_output_____
Apache-2.0
doc/source/notebooks/monitor-tensorboard.ipynb
codelover-without-talent/GPflow
Now we can put all these tasks into a monitor.
monitor_tasks = [print_task, model_tboard_task, lml_tboard_task, custom_tboard_task, saver_task, sleep_task] monitor = mon.Monitor(monitor_tasks, session, global_step)
_____no_output_____
Apache-2.0
doc/source/notebooks/monitor-tensorboard.ipynb
codelover-without-talent/GPflow
Running the optimisationWe finally get to running the optimisation.We may want to continue a previously run optimisation by resotring the TensorFlow graph from the latest checkpoint. Otherwise skip this step.
if os.path.isdir('./monitor-saves'): mon.restore_session(session, './monitor-saves') optimiser = gpflow.train.AdamOptimizer(0.01) with mon.Monitor(monitor_tasks, session, global_step, print_summary=True) as monitor: optimiser.minimize(m, step_callback=monitor, maxiter=450, global_step=global_step) file_writer...
Iteration 10 total itr.rate 12.98/s recent itr.rate 12.98/s opt.step 10 total opt.rate 14.72/s recent opt.rate 14.72/s Iteration 20 total itr.rate 19.32/s recent itr.rate 37.77/s opt.step 20 total opt.rate 28.96/s recent opt.rate 887.41/s Iteration 30 total itr.rate 24.44/s recent itr.rate 51.97/s opt.step 30 total opt...
Apache-2.0
doc/source/notebooks/monitor-tensorboard.ipynb
codelover-without-talent/GPflow
Now lets compute the log likelihood again. Hopefully we will see an increase in its value
print('LML after the optimisation: %f' % m.compute_log_likelihood())
LML after the optimisation: -68705.124191
Apache-2.0
doc/source/notebooks/monitor-tensorboard.ipynb
codelover-without-talent/GPflow
Dynamical systemsare systems (sets of equations) whose variables evolve in time (the equations contains time derivatives). As a branch of mathematics, its theory is mainly concerned with understanding the behaviour of solutions (trajectories) of the systems. Chaosis also known as the butterfly effect: "a buttefly that...
SIGMA = 10.0 BETA = 8/3 RHO = 28.0
_____no_output_____
MIT
tutorials/T4 - Dynamical systems, chaos, Lorenz.ipynb
brajard/DAPPER
The ODEs can be coded as follows
def dxdt(xyz, t0, sigma, beta, rho): """Compute the time-derivative of the Lorenz-63 system.""" x, y, z = xyz return [ sigma * (y - x), x * (rho - z) - y, x * y - beta * z ]
_____no_output_____
MIT
tutorials/T4 - Dynamical systems, chaos, Lorenz.ipynb
brajard/DAPPER
Numerical integration to compute the trajectories Below is a function to numerically **integrate** the ODEs and **plot** the solutions.<!--This function also takes arguments to control ($\sigma$, $\beta$, $\rho$) and of the numerical integration (`N`, `T`).-->
from scipy.integrate import odeint # integrator output_63 = [None] @interact( sigma=(0.,50), beta=(0.,5), rho=(0.,50), N=(0,50), eps=(0.01,1), T=(0.,30)) def animate_lorenz(sigma=SIGMA, beta=BETA, rho=RHO , N=2, eps=0.01, T=1.0): # Initial conditions: perturbations around some "pr...
Widget Javascript not detected. It may not be installed or enabled properly.
MIT
tutorials/T4 - Dynamical systems, chaos, Lorenz.ipynb
brajard/DAPPER
**Exc 4.2**: * Move `T` (use your arrow keys). What does it control? * Set `T` to something small; move the sliders for `N` and `eps`. What do they control?* Visually investigate the system's (i.e. the trajectories') sensititivy to initial conditions by moving `T`, `N` and `eps`. Very roughtly, estimate its predictabi...
xx = output_63[0][:,:,0] # state component index 0 (must be 0,1,2) plt.hist(xx[:,-1] ,normed=1,label="ensemble dist.",alpha=1.0) # -1: last time plt.hist(xx[-1,:] ,normed=1,label="temporal dist.",alpha=0.5) # -1: last ensemble member #plt.hist(xx.ravel(),normed=1,label="total distribution",alpha=0.5) plt.legend...
_____no_output_____
MIT
tutorials/T4 - Dynamical systems, chaos, Lorenz.ipynb
brajard/DAPPER
--- The "Lorenz-95" modelThe Lorenz-96 systemis a "1D" model, designed to simulate atmospheric convection. Each state variable $\mathbf{x}_i$ can be considered some atmospheric quantity at grid point at a fixed lattitude of the earth. The system is given by the coupled set of ODEs,$$\frac{d \mathbf{x}_i}{dt} = (\math...
show_answer("Hint: Lorenz energy") show_answer("Lorenz energy")
_____no_output_____
MIT
tutorials/T4 - Dynamical systems, chaos, Lorenz.ipynb
brajard/DAPPER
The model is animated below.
# For all i, any n: s(x,n) := x[i+n], circularly. def s(x,n): return np.roll(x,-n) output_95 = [None] def animate_lorenz_95(m=40,Force=8.0,eps=0.01,T=0): # Initial conditions: perturbations x0 = zeros(m) x0[0] = eps def dxdt(x,t): return (s(x,1)-s(x,-2))*s(x,-1) - x + Force t...
Widget Javascript not detected. It may not be installed or enabled properly.
MIT
tutorials/T4 - Dynamical systems, chaos, Lorenz.ipynb
brajard/DAPPER
**Exc 4.12:** Under which settings of the force `F` is the system chaotic? --- Error/perturbation dynamics **Exc 4.14*:** Suppose $x(t)$ and $z(t)$ are "twins": they evolve according to the same law $f$:$$\frac{dx}{dt} = f(x) \\ \frac{dz}{dt} = f(z) \, .$$* a) Define the "error": $\varepsilon(t) = x(t) - z(t)$. Suppos...
show_answer("error evolution")
_____no_output_____
MIT
tutorials/T4 - Dynamical systems, chaos, Lorenz.ipynb
brajard/DAPPER
**Exc 4.16*:** Recall the Lorenz-63 system. What is its doubling time (i.e. estimate how long does it take for two trajectories to grow twice as far apart as they were to start with) ?*Hint: Set `N=50, eps=0.01, T=1,` and compute the spread of the particles now as compared to how they started*
xx = output_63[0][:,-1] # Ensemble of particles at the end of integration ### compute your answer here ### show_answer("doubling time")
_____no_output_____
MIT
tutorials/T4 - Dynamical systems, chaos, Lorenz.ipynb
brajard/DAPPER
IUCN - Extinct species **Tags:** iucn opendata extinctspecies analytics plotly **Author:** [Martin Delasalle](https://github.com/delasalle-sio-martin) Source : https://www.iucnredlist.org/statistics If you want another view of the data : Link : https://ourworldindata.org/extinctions HistoryThe initial aim was to com...
import pandas as pd import plotly.express as px
_____no_output_____
BSD-3-Clause
IUCN/IUCN_Extinct_species.ipynb
krajai/testt
Setup your variables 👉 Download data in [CSV](https://www.iucnredlist.org/statistics) and drop it on your root folder
# Input csv csv_input = "Table 3 Species by kingdom and class - show all.csv"
_____no_output_____
BSD-3-Clause
IUCN/IUCN_Extinct_species.ipynb
krajai/testt
Model Get data from csv
# We load the csv file data = pd.read_csv(csv_input, ',') # We set the column Name as index data.set_index('Name', inplace = True) # Then we select the columns EX, EW and Name, and all the lines we want in the graph table = data.loc[["Total", "GASTROPODA", "BIVALVIA", ...
_____no_output_____
BSD-3-Clause
IUCN/IUCN_Extinct_species.ipynb
krajai/testt
Output Plot graph
# We use plotly to show datas with an horizontal bar chart def create_barchart(table): Graph = table.sort_values('Extincted', ascending=False) fig = px.bar(Graph, x="Extincted", y="CATEGORY", color="CATEGORY", orientation="h") fig.update_la...
_____no_output_____
BSD-3-Clause
IUCN/IUCN_Extinct_species.ipynb
krajai/testt
Can I predict how much people will spend online? Insights from Google Analytics data
import pandas as pd import matplotlib.pyplot as plt import numpy as np import plotly.express as px import matplotlib.pyplot as plt import seaborn as sns df = pd.read_csv('mergedGAdata.csv') print(df.shape)
(3532, 16)
MIT
Jupyter_notebooks_and_data/Final Unit 2 Build Week Model.ipynb
willstauffernorris/boat_data
Wrangling
##Turn Session Duration into numbers not strings print(type(df['Session Duration'][0])) df['Session Duration'] = df['Session Duration'].str.replace(' seconds','') df['Session Duration'] = pd.to_numeric(df['Session Duration']) print(type(df['Session Duration'][0])) #display(df.head(5)) ### Dropping an unneccesary colu...
_____no_output_____
MIT
Jupyter_notebooks_and_data/Final Unit 2 Build Week Model.ipynb
willstauffernorris/boat_data
Exploratory Visualizations
fig = px.bar(df, x='Day_of_year', y='Revenue', #color="Session Duration" ) fig.show() matplotlib_figure = plt.figure() x = df['Day_of_year'] y = df['Revenue'] plt.plot(x, y); from plotly.tools import mpl_to_plotly plotly_figure = mpl_to_plotly(matplotlib_figure) plotly_figure.show() i...
_____no_output_____
MIT
Jupyter_notebooks_and_data/Final Unit 2 Build Week Model.ipynb
willstauffernorris/boat_data
Building a model
## Checking to make sure none of my data types will break the models df.dtypes
_____no_output_____
MIT
Jupyter_notebooks_and_data/Final Unit 2 Build Week Model.ipynb
willstauffernorris/boat_data
Break into Test/Train
from sklearn.model_selection import train_test_split train, test = train_test_split(df, train_size=0.80, test_size=0.20, #stratify=df['Product'], random_state=42) print(train.shape) test.shape # Arrange data into X features matrix and y target vector targe...
_____no_output_____
MIT
Jupyter_notebooks_and_data/Final Unit 2 Build Week Model.ipynb
willstauffernorris/boat_data
Baselines
from sklearn.metrics import mean_absolute_error price = df['Revenue'] best_guess = price.mean() best_guess = [best_guess] * len(price) baseline_mae = mean_absolute_error(price, best_guess) print(f'The Baseline mean absolute error is ${baseline_mae.round(2)}')
The Baseline mean absolute error is $813.25
MIT
Jupyter_notebooks_and_data/Final Unit 2 Build Week Model.ipynb
willstauffernorris/boat_data
A Linear Regression
import category_encoders as ce from sklearn.linear_model import LinearRegression from sklearn.pipeline import make_pipeline from sklearn.preprocessing import StandardScaler lr = make_pipeline( ce.TargetEncoder(), LinearRegression() ) lr.fit(X_train, y_train) print('Linear Regression R^2', lr.score(X_test, y...
_____no_output_____
MIT
Jupyter_notebooks_and_data/Final Unit 2 Build Week Model.ipynb
willstauffernorris/boat_data
XGBoost Model
from sklearn.metrics import r2_score from xgboost import XGBRegressor from sklearn.metrics import mean_absolute_error from sklearn.model_selection import RandomizedSearchCV from scipy.stats import randint pipeline = make_pipeline( ce.OrdinalEncoder(), XGBRegressor(objective='reg:squarederror') ) param_distr...
_____no_output_____
MIT
Jupyter_notebooks_and_data/Final Unit 2 Build Week Model.ipynb
willstauffernorris/boat_data
Permutation Importances
transformers = make_pipeline( ce.OrdinalEncoder(), #SimpleImputer(strategy='median') ) X_train_transformed = transformers.fit_transform(X_train) X_test_transformed = transformers.transform(X_test) model = XGBRegressor(n_estimators=100, random_state=42, n_jobs=-1) model.fit(X_train_transformed, y_train) # Ign...
_____no_output_____
MIT
Jupyter_notebooks_and_data/Final Unit 2 Build Week Model.ipynb
willstauffernorris/boat_data
Partial dependence plot
from pdpbox.pdp import pdp_isolate, pdp_plot feature = 'Page Depth' isolated = pdp_isolate( model=pipeline, dataset=X_test, model_features=X_test.columns, feature=feature) pdp_plot(isolated, feature_name=feature); feature = 'Session Duration' isolated = pdp_isolate( model=pipeline, dataset=X_...
_____no_output_____
MIT
Jupyter_notebooks_and_data/Final Unit 2 Build Week Model.ipynb
willstauffernorris/boat_data
Rebuilding the model with only a few features This is so I can deploy a much simpler model with fewer sliders on Heroku
# Arrange data into X features matrix and y target vector target = 'Revenue' model_deploy = ['Day_of_year', 'Page Depth', 'Session Duration'] X_train = train[model_deploy] y_train = train[target] X_test = test[model_deploy] y_test = test[target] from sklearn.metrics import r2_score from xgboost import XGBRegressor fr...
Fitting 10 folds for each of 10 candidates, totalling 100 fits
MIT
Jupyter_notebooks_and_data/Final Unit 2 Build Week Model.ipynb
willstauffernorris/boat_data
Exporting a .joblib file for my Heroku model
from joblib import dump dump(pipeline, 'pipeline.joblib', compress=True) import joblib import sklearn import category_encoders as ce import xgboost print(f'joblib=={joblib.__version__}') print(f'scikit-learn=={sklearn.__version__}') print(f'category_encoders=={ce.__version__}') print(f'xgboost=={xgboost.__version__}')
joblib==0.14.1 scikit-learn==0.22.1 category_encoders==2.1.0 xgboost==0.90
MIT
Jupyter_notebooks_and_data/Final Unit 2 Build Week Model.ipynb
willstauffernorris/boat_data
Imports and simple case example in pyspark
import pyspark from pyspark import SparkContext from pyspark.sql.types import * from pyspark import sql ## simple example - imports flat file from pyspark import SparkContext logFile = "/home/ebrunk/Dropbox/SBRG/CHO/ribo_prof/Database/command" # Should be some file on your system sc = SparkContext("local", "Simple A...
_____no_output_____
MIT
pyspark_parquet_to_csv.ipynb
ebrunk/iPy_notebooks
gets uniprot to pdb mapping df & human genome mapping
!pwd !wget -r http://dataframes.rcsb.org/parquet/uniprotpdb/20160517/ !mv dataframes.rcsb.org/* 20160517/. !mv 20160517/parquet/uniprotpdb/20160517/* 20160517/. !rm -rf 20160517/ !ls 20160517/ !wget -r --no-parent http://dataframes.rcsb.org/parquet/humangenome/20160517/hg38/chr11/ !ls dataframes.rcsb.org/parquet/humang...
_common_metadata index.html index.html?C=D;O=A index.html?C=D;O=D index.html?C=M;O=A index.html?C=M;O=D index.html?C=N;O=A index.html?C=N;O=D index.html?C=S;O=A index.html?C=S;O=D _metadata part-r-00000-3b4d8124-bea8-4b62-844c-cb51354aae17.snappy.parquet part-r-00001-3b4d8124-bea8-4b62-844c-cb51354aae17.sna...
MIT
pyspark_parquet_to_csv.ipynb
ebrunk/iPy_notebooks
Load data into df
sqlContext = pyspark.SQLContext(sc) uniprotPDB = sqlContext.load("/home/ebrunk/Dropbox/SBRG/RECON3D/fatcat/domain_clustering/uniprotpdb/20160517/part-r-00000-04f7101a-c0a5-4d6d-b703-3b1ace2b2f76.snappy.parquet") uniprotPDB.registerTempTable("uniprotPDB") uniprotPDB.show(1) chr11 = sqlContext.load("/home/ebrunk/Dropbox/...
+---+--------------+-------+--------+----------+--------+-----+--------------------------+---------+-----------+-----+--------+---------+----------+ |cds|chromosomeName|exonNum|geneName|geneSymbol|inCoding|inUtr|isoformCorrectedUniprotPos|isoformNr|orientation|phase|position|uniProtId|uniProtPos| +---+--------------+--...
MIT
pyspark_parquet_to_csv.ipynb
ebrunk/iPy_notebooks
Perform mapping
chr11.registerTempTable("chr11") sickeCellSNP = sqlContext.sql("select * from chr11 where position = 5227002") sickeCellSNP.show() sickeCellSNP.registerTempTable("snp") # join genomic info with UniProt to PDB mapping map2PDB = sqlContext.sql("select * from snp left join uniprotPDB where snp.uniProtId = uniprotPDB.un...
+---+--------------+-------+--------+----------+--------+-----+--------------------------+---------+-----------+-----+--------+---------+----------+-------+-------+----------+-----+---------+----------+ |cds|chromosomeName|exonNum|geneName|geneSymbol|inCoding|inUtr|isoformCorrectedUniprotPos|isoformNr|orientation|phase...
MIT
pyspark_parquet_to_csv.ipynb
ebrunk/iPy_notebooks
save df to pandas
type(map2PDB) map2PDB_pandas = map2PDB.toPandas() type(map2PDB_pandas) map2PDB_pandas.head()
_____no_output_____
MIT
pyspark_parquet_to_csv.ipynb
ebrunk/iPy_notebooks
IMPORT LIBRARIES
import numpy as np import pandas import pickle from ScoringAndEvaluation import Get_Class_Probabilities, Evaluate_Predictions %matplotlib inline
_____no_output_____
MIT
code/02_modeling/ScoringAndEvaluation.ipynb
Azure/MachineLearningSamples-TDSPUCIAdultIncome
SET FILE LOCATION, LOCATION TO TEST DATA AND MODEL FILE
dirpath = '..\\..\\outputs' # Transformed test data for scoring transformed_test_file = dirpath + "\\test_data_engineered.pkl" inFile = open(transformed_test_file, 'rb') testDataFrame = pickle.load(inFile) inFile.close() ## Model files RandomForest_model_file = dirpath + '\\CVRandomForestModel.pkl' ElasticNet_model_f...
_____no_output_____
MIT
code/02_modeling/ScoringAndEvaluation.ipynb
Azure/MachineLearningSamples-TDSPUCIAdultIncome
PERFORM SCORING AND EVALUATION
# LOAD TEST DATA y_test = testDataFrame["income"].values X_test = testDataFrame.drop("income", axis=1) # RANDOMFOREST MODEL y_pred = Get_Class_Probabilities(transformed_test_file, RandomForest_model_file); RFAuc = Evaluate_Predictions(y_pred, y_test, RandomForestROCplotpath) print ("Random Forest AUC: " + str(round(RF...
Random Forest AUC: 0.917 ElasticNet AUC: 0.897
MIT
code/02_modeling/ScoringAndEvaluation.ipynb
Azure/MachineLearningSamples-TDSPUCIAdultIncome
영화 리뷰 분류: 이진 분류 예제이 노트북은 [케라스 창시자에게 배우는 딥러닝](https://tensorflow.blog/케라스-창시자에게-배우는-딥러닝/) 책의 3장 4절의 코드 예제입니다. 책에는 더 많은 내용과 그림이 있습니다. 이 노트북에는 소스 코드에 관련된 설명만 포함합니다. 이 노트북의 설명은 케라스 버전 2.2.2에 맞추어져 있습니다. 케라스 최신 버전이 릴리스되면 노트북을 다시 테스트하기 때문에 설명과 코드의 결과가 조금 다를 수 있습니다. (현재 내가 사용하는 것은 케라스 버전 2.3.1 이다.)----2종 분류 또는 이진 분류는 아마도 가장 널...
from keras.datasets import imdb (train_data, train_labels), (test_data, test_labels), = imdb.load_data(num_words=10000)
_____no_output_____
MIT
3.4-classifying-movie-reviews.ipynb
alro923/deep-learning-with-python-notebooks
매개변수 `num_words=10000`은 훈련 데이터에서 가장 자주 나타나는 단어 10,000개만 사용하겠다는 의미입니다. 드물게 나타나는 단어는 무시하겠습니다. 이렇게 하면 적절한 크기의 벡터 데이터를 얻을 수 있습니다.변수 `train_data`와 `test_data`는 리뷰의 목록입니다. 각 리뷰는 단어 인덱스의 리스트입니다(단어 시퀀스가 인코딩된 것입니다). `train_labels`와 `test_labels`는 부정을 나타내는 0과 긍정을 나타내는 1의 리스트입니다:imdb 데이터셋은 train set 25000개, text set 25000개의 샘플을 제...
train_data
_____no_output_____
MIT
3.4-classifying-movie-reviews.ipynb
alro923/deep-learning-with-python-notebooks
train_data는 array 안에 list가 여러개 들어있는 형태.array(list0, list1, list2, ... , list24999) 총 25000개 있다
train_labels train_data[0] train_labels[0]
_____no_output_____
MIT
3.4-classifying-movie-reviews.ipynb
alro923/deep-learning-with-python-notebooks
가장 자주 등장하는 단어 10,000개로 제한했기 때문에 단어 인덱스는 10,000을 넘지 않습니다:
max([max(sequence) for sequence in train_data])
_____no_output_____
MIT
3.4-classifying-movie-reviews.ipynb
alro923/deep-learning-with-python-notebooks
재미 삼아 이 리뷰 데이터 하나를 원래 영어 단어로 어떻게 바꾸는지 보겠습니다:
# word_index는 단어와 정수 인덱스를 매핑한 딕셔너리입니다 word_index = imdb.get_word_index() # 정수 인덱스와 단어를 매핑하도록 뒤집습니다 reverse_word_index = dict([(value, key) for (key, value) in word_index.items()]) # 리뷰를 디코딩합니다. # 0, 1, 2는 '패딩', '문서 시작', '사전에 없음'을 위한 인덱스이므로 3을 뺍니다 decoded_review = ' '.join([reverse_word_index.get(i - 3, '?') for i in t...
_____no_output_____
MIT
3.4-classifying-movie-reviews.ipynb
alro923/deep-learning-with-python-notebooks
데이터 준비신경망에 숫자 리스트를 주입할 수는 없습니다. 리스트를 텐서로 바꾸는 두 가지 방법이 있습니다:* 같은 길이가 되도록 리스트에 패딩을 추가하고 `(samples, sequence_length)` 크기의 정수 텐서로 변환합니다. 그다음 이 정수 텐서를 다룰 수 있는 층을 신경망의 첫 번째 층으로 사용합니다(`Embedding` 층을 말하며 나중에 자세히 다루겠습니다).* 리스트를 원-핫 인코딩하여 0과 1의 벡터로 변환합니다. 예를 들면 시퀀스 `[3, 5]`를 인덱스 3과 5의 위치는 1이고 그 외는 모두 0인 10,000차원의 벡터로 각각 변환합니다. ...
import numpy as np def vectorize_sequences(sequences, dimension=10000): # 크기가 (len(sequences), dimension))이고 모든 원소가 0인 행렬을 만듭니다 results = np.zeros((len(sequences), dimension)) for i, sequence in enumerate(sequences): # 리스트 sequences 의 순서 i, 리스트값 sequence를 가져온다. results[i, sequence] = 1. # ...
_____no_output_____
MIT
3.4-classifying-movie-reviews.ipynb
alro923/deep-learning-with-python-notebooks
이제 샘플은 다음과 같이 나타납니다:
x_train[0] x_train[0].shape
_____no_output_____
MIT
3.4-classifying-movie-reviews.ipynb
alro923/deep-learning-with-python-notebooks
레이블은 쉽게 벡터로 바꿀 수 있습니다:
# 레이블을 벡터로 바꿉니다 y_train = np.asarray(train_labels).astype('float32') y_test = np.asarray(test_labels).astype('float32')
_____no_output_____
MIT
3.4-classifying-movie-reviews.ipynb
alro923/deep-learning-with-python-notebooks
이제 신경망에 주입할 데이터가 준비되었습니다. 신경망 모델 만들기입력 데이터가 벡터이고 레이블은 스칼라(1 또는 0)입니다. 아마 앞으로 볼 수 있는 문제 중에서 가장 간단할 것입니다. 이런 문제에 잘 작동하는 네트워크 종류는 `relu` 활성화 함수를 사용한 완전 연결 층(즉, `Dense(16, activation='relu')`)을 그냥 쌓은 것입니다.`Dense` 층에 전달한 매개변수(16)는 은닉 유닛의 개수입니다. 하나의 은닉 유닛은 층이 나타내는 표현 공간에서 하나의 차원이 됩니다. 2장에서 `relu` 활성화 함수를 사용한 `Dense` 층을 다음과 ...
from keras import models from keras import layers model = models.Sequential() model.add(layers.Dense(16, activation='relu', input_shape=(10000,))) model.add(layers.Dense(16, activation='relu')) model.add(layers.Dense(1, activation='sigmoid'))
_____no_output_____
MIT
3.4-classifying-movie-reviews.ipynb
alro923/deep-learning-with-python-notebooks
마지막으로 손실 함수와 옵티마이저를 선택해야 합니다. 이진 분류 문제이고 신경망의 출력이 확률이기 때문에(네트워크의 끝에 시그모이드 활성화 함수를 사용한 하나의 유닛으로 된 층을 놓았습니다), `binary_crossentropy` 손실이 적합합니다. 이 함수가 유일한 선택은 아니고 예를 들어 `mean_squared_error`를 사용할 수도 있습니다. 확률을 출력하는 모델을 사용할 때는 크로스엔트로피가 최선의 선택입니다. 크로스엔트로피는 정보 이론 분야에서 온 개념으로 확률 분포 간의 차이를 측정합니다. 여기에서는 원본 분포와 예측 분포 사이를 측정합니다.다음은 ...
model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy']) # 옵티마이저를 이와 같이 이름으로 사용하면, 해당 옵티마이저의 기본 설정이 사용됩니다.
_____no_output_____
MIT
3.4-classifying-movie-reviews.ipynb
alro923/deep-learning-with-python-notebooks
케라스에 `rmsprop`, `binary_crossentropy`, `accuracy`가 포함되어 있기 때문에 옵티마이저, 손실 함수, 측정 지표를 문자열로 지정하는 것이 가능합니다. 이따금 옵티마이저의 매개변수를 바꾸거나 자신만의 손실 함수, 측정 함수를 전달해야 할 경우가 있습니다. 전자의 경우에는 옵티마이저 파이썬 클래스를 사용해 객체를 직접 만들어 `optimizer` 매개변수에 전달하면 됩니다:
from keras import optimizers model.compile(optimizer=optimizers.RMSprop(lr=0.001), loss='binary_crossentropy', metrics=['accuracy'])
_____no_output_____
MIT
3.4-classifying-movie-reviews.ipynb
alro923/deep-learning-with-python-notebooks
후자의 경우는 `loss`와 `metrics` 매개변수에 함수 객체를 전달하면 됩니다
from keras import losses from keras import metrics model.compile(optimizer=optimizers.RMSprop(lr=0.001), loss=losses.binary_crossentropy, metrics=[metrics.binary_accuracy]) model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy'])
_____no_output_____
MIT
3.4-classifying-movie-reviews.ipynb
alro923/deep-learning-with-python-notebooks
잘 모르겠다 다시 해보자.
# 옵티마이저의 이름을 사용하는 경우 : 기본 설정이 사용된다. model.compile(optimizer='sgd', loss='mean_squared_error', metrics=[metrics.binary_accuracy])
_____no_output_____
MIT
3.4-classifying-movie-reviews.ipynb
alro923/deep-learning-with-python-notebooks
아 여기서 metrics=[metrics.binary_accuracy] 를 안했어서 아래부분에서 acc KeyError 난 거임
# 옵티마이저의 매개변수를 바꾸거나 # 자신만의 손실 함수, 측정함수를 전달하기 위해서 # 객체 (여기서는 sgd)를 직접 만들어서, model.compile()의 매개변수로 전달해서 쓸 수도 있다. sgd = optimizers.SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True) model.compile(optimizer=sgd, loss='mean_squared_error', metrics=['acc'])
_____no_output_____
MIT
3.4-classifying-movie-reviews.ipynb
alro923/deep-learning-with-python-notebooks
여기에서도 accuracy 안넣어서 KeyError 났음
metrics=['acc']로 하면 history에서 key 가 acc, val_acc 로 바뀐다
_____no_output_____
MIT
3.4-classifying-movie-reviews.ipynb
alro923/deep-learning-with-python-notebooks
* loss == 손실함수 : 학습을 통해 직접적으로 줄이고자 하는 값 (loss(손실) = error(에러) = cost(코스트))* metrics == 측정함수 : 학습을 통해 목표를 얼마나 잘(못) 달성했는지를 나타내는 값, metric(척도)* 머신러닝의 최종 목표는 척도로 달성률을 표시하지만,* 직접 척도를 낮추도록 훈련하는 것은 어렵기때문에 손실을 줄이는 방향으로 훈련한다. 훈련 검증훈련하는 동안 처음 본 데이터에 대한 모델의 정확도를 측정하기 위해서는 원본 훈련 데이터에서 10,000의 샘플을 떼어서 검증 세트를 만들어야 합니다:
x_val = x_train[:10000] # 리스트 x_train에서 index 값이 0 이상 10000미만인 값들을 떼어내서 리스트 x_val을 만든다. partial_x_train = x_train[10000:] # 리스트 x_train에서 index 값이 10000 이상인 값들을 떼어내서 리스트 partial_x_train을 만든다. y_val = y_train[:10000] partial_y_train = y_train[10000:]
_____no_output_____
MIT
3.4-classifying-movie-reviews.ipynb
alro923/deep-learning-with-python-notebooks
이제 모델을 512개 샘플씩 미니 배치를 만들어 20번의 에포크 동안 훈련시킵니다(`x_train`과 `y_train` 텐서에 있는 모든 샘플에 대해 20번 반복합니다). 동시에 따로 떼어 놓은 10,000개의 샘플에서 손실과 정확도를 측정할 것입니다. 이렇게 하려면 `validation_data` 매개변수에 검증 데이터를 전달해야 합니다:
history = model.fit(partial_x_train, partial_y_train, epochs=20, batch_size=512, validation_data=(x_val, y_val))
Train on 15000 samples, validate on 10000 samples Epoch 1/20 15000/15000 [==============================] - 2s 130us/step - loss: 0.0327 - acc: 0.9714 - val_loss: 0.0905 - val_acc: 0.8768 Epoch 2/20 15000/15000 [==============================] - 2s 119us/step - loss: 0.0319 - acc: 0.9725 - val_loss: 0.0907 - val_acc: 0...
MIT
3.4-classifying-movie-reviews.ipynb
alro923/deep-learning-with-python-notebooks
CPU를 사용해도 에포크마다 2초가 걸리지 않습니다. 전체 훈련은 20초 이상 걸립니다. 에포크가 끝날 때마다 10,000개의 검증 샘플 데이터에서 손실과 정확도를 계산하기 때문에 약간씩 지연됩니다.`model.fit()` 메서드는 `History` 객체를 반환합니다. 이 객체는 훈련하는 동안 발생한 모든 정보를 담고 있는 딕셔너리인 `history` 속성을 가지고 있습니다. 한 번 확인해 보죠:
history_dict = history.history history_dict.keys()
_____no_output_____
MIT
3.4-classifying-movie-reviews.ipynb
alro923/deep-learning-with-python-notebooks