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
We can see that this model gets a very high accuracy of 99.9% ! But it still misclassifies about 30 (each) of our valid and fraudulent cases, which results in much lower values for recall and precision.Next, let's delete this endpoint and discuss ways to improve this model. Delete the EndpointI've added a convenience ...
# Deletes a precictor.endpoint def delete_endpoint(predictor): try: boto3.client('sagemaker').delete_endpoint(EndpointName=predictor.endpoint) print('Deleted {}'.format(predictor.endpoint)) except: print('Already deleted: {}'.format(predictor.endpoint)) # delete the p...
_____no_output_____
MIT
notebooks/Payment_Fraud_Detection/Fraud_Detection_Solution.ipynb
LourensWalters/deep-learning-udacity
--- Model ImprovementsThe default LinearLearner got a high accuracy, but still classified fraudulent and valid data points incorrectly. Specifically classifying more than 30 points as false negatives (incorrectly labeled, fraudulent transactions), and a little over 30 points as false positives (incorrectly labeled, val...
# instantiate a LinearLearner # tune the model for a higher recall linear_recall = LinearLearner(role=role, train_instance_count=1, train_instance_type='ml.c4.xlarge', predictor_type='binary_classifier', ...
_____no_output_____
MIT
notebooks/Payment_Fraud_Detection/Fraud_Detection_Solution.ipynb
LourensWalters/deep-learning-udacity
Train the tuned estimatorFit the new, tuned estimator on the formatted training data.
%%time # train the estimator on formatted training data linear_recall.fit(formatted_train_data)
_____no_output_____
MIT
notebooks/Payment_Fraud_Detection/Fraud_Detection_Solution.ipynb
LourensWalters/deep-learning-udacity
Deploy and evaluate the tuned estimatorDeploy the tuned predictor and evaluate it.We hypothesized that a tuned model, optimized for a higher recall, would have fewer false negatives (fraudulent transactions incorrectly labeled as valid); did the number of false negatives get reduced after tuning the model?
%%time # deploy and create a predictor recall_predictor = linear_recall.deploy(initial_instance_count=1, instance_type='ml.t2.medium') print('Metrics for tuned (recall), LinearLearner.\n') # get metrics for tuned predictor metrics = evaluate(recall_predictor, test_features.astype('float32'), ...
_____no_output_____
MIT
notebooks/Payment_Fraud_Detection/Fraud_Detection_Solution.ipynb
LourensWalters/deep-learning-udacity
Delete the endpoint As always, when you're done evaluating a model, you should delete the endpoint. Below, I'm using the `delete_endpoint` helper function I defined earlier.
# delete the predictor endpoint delete_endpoint(recall_predictor)
_____no_output_____
MIT
notebooks/Payment_Fraud_Detection/Fraud_Detection_Solution.ipynb
LourensWalters/deep-learning-udacity
--- Improvement: Managing Class ImbalanceWe have a model that is tuned to get a higher recall, which aims to reduce the number of false negatives. Earlier, we discussed how class imbalance may actually bias our model towards predicting that all transactions are valid, resulting in higher false negatives and true negati...
# instantiate a LinearLearner # include params for tuning for higher recall # *and* account for class imbalance in training data linear_balanced = LinearLearner(role=role, train_instance_count=1, train_instance_type='ml.c4.xlarge', ...
_____no_output_____
MIT
notebooks/Payment_Fraud_Detection/Fraud_Detection_Solution.ipynb
LourensWalters/deep-learning-udacity
EXERCISE: Train the balanced estimatorFit the new, balanced estimator on the formatted training data.
%%time # train the estimator on formatted training data linear_balanced.fit(formatted_train_data)
_____no_output_____
MIT
notebooks/Payment_Fraud_Detection/Fraud_Detection_Solution.ipynb
LourensWalters/deep-learning-udacity
EXERCISE: Deploy and evaluate the balanced estimatorDeploy the balanced predictor and evaluate it. Do the results match with your expectations?
%%time # deploy and create a predictor balanced_predictor = linear_balanced.deploy(initial_instance_count=1, instance_type='ml.t2.medium') print('Metrics for balanced, LinearLearner.\n') # get metrics for balanced predictor metrics = evaluate(balanced_predictor, test_features.astype('float32'), ...
_____no_output_____
MIT
notebooks/Payment_Fraud_Detection/Fraud_Detection_Solution.ipynb
LourensWalters/deep-learning-udacity
Delete the endpoint When you're done evaluating a model, you should delete the endpoint.
# delete the predictor endpoint delete_endpoint(balanced_predictor)
_____no_output_____
MIT
notebooks/Payment_Fraud_Detection/Fraud_Detection_Solution.ipynb
LourensWalters/deep-learning-udacity
A note on metric variability: The above model is tuned for the best possible precision with recall fixed at about 90%. The recall is fixed at 90% during training, but may vary when we apply our trained model to a test set of data. --- Model DesignNow that you've seen how to tune and balance a LinearLearner. Create, tra...
%%time # instantiate and train a LinearLearner # include params for tuning for higher precision # *and* account for class imbalance in training data linear_precision = LinearLearner(role=role, train_instance_count=1, train_instance_type='ml.c4.xlarge', ...
_____no_output_____
MIT
notebooks/Payment_Fraud_Detection/Fraud_Detection_Solution.ipynb
LourensWalters/deep-learning-udacity
This model trains for a fixed precision of 90%, and, under that constraint, tries to get as high a recall as possible.
%%time # deploy and evaluate a predictor precision_predictor = linear_precision.deploy(initial_instance_count=1, instance_type='ml.t2.medium') print('Metrics for tuned (precision), LinearLearner.\n') # get metrics for balanced predictor metrics = evaluate(precision_predictor, test_features.astype(...
_____no_output_____
MIT
notebooks/Payment_Fraud_Detection/Fraud_Detection_Solution.ipynb
LourensWalters/deep-learning-udacity
(Source: http://www.scipy-lectures.org/packages/scikit-learn/index.htmlsupervised-learning-classification-of-handwritten-digits)
%matplotlib notebook from sklearn.datasets import load_digits digits = load_digits()
_____no_output_____
MIT
sklearn/3. Supervised Learning, Digit Classification.ipynb
ltetrel/introML
Look at the data
from matplotlib import pyplot as plt fig = plt.figure(figsize=(6, 6)) # figure size in inches fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05) for i in range(64): ax = fig.add_subplot(8, 8, i + 1, xticks=[], yticks=[]) ax.imshow(digits.images[i], cmap=plt.cm.binary, interpolatio...
_____no_output_____
MIT
sklearn/3. Supervised Learning, Digit Classification.ipynb
ltetrel/introML
Let's look at the first 2 dimensions
plt.figure() from sklearn.decomposition import PCA pca = PCA(n_components=2) proj = pca.fit_transform(digits.data) plt.scatter(proj[:, 0], proj[:, 1], c=digits.target, cmap="Paired") plt.colorbar() plt.show()
_____no_output_____
MIT
sklearn/3. Supervised Learning, Digit Classification.ipynb
ltetrel/introML
Let's try Naive Bayes Classification...> Abstractly, naive Bayes is a conditional probability model: given a problem instance to be classified, represented by a vector $ \mathbf {x} =(x_{1},\dots ,x_{n}) $ representing some $n$ features (independent variables), it assigns to this instance probabilities, $ p(C_{k}\mid ...
from sklearn.naive_bayes import GaussianNB from sklearn.model_selection import train_test_split # split the data into training and validation sets X_train, X_test, y_train, y_test = train_test_split(digits.data, digits.target) # train the model clf = GaussianNB() clf.fit(X_train, y_train) # use the model to predict ...
[[41 1 0 0 0 0 0 0 0 0] [ 0 37 0 0 0 0 0 0 3 0] [ 0 7 19 0 0 0 0 0 15 0] [ 0 1 0 39 0 0 0 1 11 0] [ 0 3 0 0 35 0 0 8 1 0] [ 0 2 0 1 0 40 0 0 0 0] [ 0 2 0 0 1 0 47 0 0 0] [ 0 0 0 0 2 0 0 43 0 0] [ 0 7 0 1 0 0 0 0 27 0] [ 0 5 0 1 1 0 0 ...
MIT
sklearn/3. Supervised Learning, Digit Classification.ipynb
ltetrel/introML
Model Selection and ValidationModel selection and validation are fundamental steps in statistical learning applications. In particular, we wish to select the model that performs optimally, both with respect to the training data and to external data. A model's performance on external data is known as its generalization...
%matplotlib inline import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns sns.set_context('notebook') import warnings warnings.simplefilter("ignore") salmon = pd.read_table("../data/salmon.dat", sep=r'\s+', index_col=0) salmon.plot(x='spawners', y='recruits', kind='scatter')
_____no_output_____
MIT
notebooks/Day3_2-Model-selection-and-validation.ipynb
vcalderon2009/cqs_machine_learning
On the one extreme, a linear relationship is underfit; on the other, we see that including a very large number of polynomial terms is clearly overfitting the data.
fig, axes = plt.subplots(1, 2, figsize=(14,6)) xvals = np.arange(salmon.spawners.min(), salmon.spawners.max()) fit1 = np.polyfit(salmon.spawners, salmon.recruits, 1) p1 = np.poly1d(fit1) axes[0].plot(xvals, p1(xvals)) axes[0].scatter(x=salmon.spawners, y=salmon.recruits) fit15 = np.polyfit(salmon.spawners, salmon.re...
_____no_output_____
MIT
notebooks/Day3_2-Model-selection-and-validation.ipynb
vcalderon2009/cqs_machine_learning
We can select an appropriate polynomial order for the model using **cross-validation**, in which we hold out a testing subset from our dataset, fit the model to the remaining data, and evaluate its performance on the held-out subset.
from sklearn.model_selection import train_test_split xtrain, xtest, ytrain, ytest = train_test_split(salmon.spawners, salmon.recruits, test_size=0.3, random_state=42)
_____no_output_____
MIT
notebooks/Day3_2-Model-selection-and-validation.ipynb
vcalderon2009/cqs_machine_learning
A natural criterion to evaluate model performance is root mean square error.$$L\left(Y, \hat{f}(X) \right) = \sqrt{\frac{1}{N}(Y - \hat{f}(X))^2}$$
from sklearn.metrics import mean_squared_error def rmse(x, y, coefs): yfit = np.polyval(coefs, x) return mean_squared_error(y, yfit) ** .5
_____no_output_____
MIT
notebooks/Day3_2-Model-selection-and-validation.ipynb
vcalderon2009/cqs_machine_learning
We can now evaluate the model at varying polynomial degrees, and compare their fit.
degrees = np.arange(11) train_err = np.zeros(len(degrees)) validation_err = np.zeros(len(degrees)) for i, d in enumerate(degrees): p = np.polyfit(xtrain, ytrain, d) train_err[i] = rmse(xtrain, ytrain, p) validation_err[i] = rmse(xtest, ytest, p) fig, ax = plt.subplots() ax.plot(degrees, validation_err, ...
_____no_output_____
MIT
notebooks/Day3_2-Model-selection-and-validation.ipynb
vcalderon2009/cqs_machine_learning
In the cross-validation above, notice that the error is high for both very low and very high polynomial values, while training error declines monotonically with degree. The cross-validation error (sometimes referred to as test error or generalization error) is composed of two components: **bias** and **variance**. When...
def aic(rss, n, k): return n * np.log(float(rss) / n) + 2 * k
_____no_output_____
MIT
notebooks/Day3_2-Model-selection-and-validation.ipynb
vcalderon2009/cqs_machine_learning
We can use AIC to select the appropriate polynomial degree.
aic_values = np.zeros(len(degrees)) params = np.zeros((len(degrees), len(degrees))) for i, d in enumerate(degrees): p, residuals, rank, singular_values, rcond = np.polyfit( salmon.spawners, salmon.recruits, d, full=True) aic_values[i] = aic((residuals).sum(), len(salmon.spawners...
_____no_output_____
MIT
notebooks/Day3_2-Model-selection-and-validation.ipynb
vcalderon2009/cqs_machine_learning
For ease of interpretation, AIC values can be transformed into model weights via:$$p_i = \frac{\exp^{-\frac{1}{2} AIC_i}}{\sum_j \exp^{-\frac{1}{2} AIC_j} }$$
aic_trans = np.exp(-0.5 * aic_values) aic_probs = aic_trans / aic_trans.sum() aic_probs.round(2)
_____no_output_____
MIT
notebooks/Day3_2-Model-selection-and-validation.ipynb
vcalderon2009/cqs_machine_learning
Metrics for ClassificationFor classifiers such as decision trees and random forests, we may judge our model performance a little differently than the above.First, let's describe four concepts to help evaluate a classifier.A **true positive** (TP) occurs when we correctly predict the positive class.A **true negative** ...
from sklearn.datasets import make_classification from sklearn.metrics import confusion_matrix from sklearn.linear_model import LogisticRegression X, y = make_classification( n_samples=1000, n_features=50, n_informative=25, n_redundant=0, random_state=123 ) X_train = X[:750] y_train = y[:750] X...
_____no_output_____
MIT
notebooks/Day3_2-Model-selection-and-validation.ipynb
vcalderon2009/cqs_machine_learning
K-fold Cross-validationAs introduced above, cross-validation is probably the most widely used method for estimating generalization error. In particularly data rich environments, we may split our sample into a training set, a testing set, and a validation set that is completely set aside until we have performed model s...
from sklearn.model_selection import cross_val_score, KFold nfolds = 3 kf = KFold(n_splits=nfolds, shuffle=True) fig, axes = plt.subplots(1, nfolds, figsize=(14,4)) for i, fold in enumerate(kf.split(salmon.values)): training, validation = fold y, x = salmon.values[training].T axes[i].plot(x, y, 'ro', labe...
_____no_output_____
MIT
notebooks/Day3_2-Model-selection-and-validation.ipynb
vcalderon2009/cqs_machine_learning
If the model shows high **bias**, the following actions might help:- **Add more features**. In our example of predicting home prices, it may be helpful to make use of information such as the neighborhood the house is in, the year the house was built, the size of the lot, etc. Adding these features to the training an...
from sklearn.ensemble import BaggingRegressor from sklearn.preprocessing import PolynomialFeatures from sklearn.linear_model import LinearRegression X,y = salmon.values.T br = BaggingRegressor(LinearRegression(), oob_score=True, random_state=20090425) X2 = PolynomialFeatures(degree=2).fit_transform(X[:, None]) br.fit(...
_____no_output_____
MIT
notebooks/Day3_2-Model-selection-and-validation.ipynb
vcalderon2009/cqs_machine_learning
In order to evaluate a particular model, the samples that were not selected for a particular resampled dataset (the **out-of-bag** sample) can be used to estimate the generalization error.
br.oob_score_
_____no_output_____
MIT
notebooks/Day3_2-Model-selection-and-validation.ipynb
vcalderon2009/cqs_machine_learning
Scikit-learn includes a convenient facility called a **pipeline**, which can be used to chain two or more estimators into a single function. We will hear more about using pipelines later. Here, we will use it to join the bagging regressor, polynomial feature selection, and linear regression into a single function.
from sklearn.pipeline import make_pipeline def polynomial_bagging_regression(degree, **kwargs): return make_pipeline(PolynomialFeatures(degree=degree), BaggingRegressor(LinearRegression(), **kwargs)) scores = [] for d in degrees: print('fitting', d) pbr = polynomial_bagging_r...
_____no_output_____
MIT
notebooks/Day3_2-Model-selection-and-validation.ipynb
vcalderon2009/cqs_machine_learning
RegularizationThe `scikit-learn` package includes a built-in dataset of diabetes progression, taken from [Efron *et al.* (2003)](http://arxiv.org/pdf/math/0406456.pdf), which includes a set of 10 normalized predictors.
from sklearn import datasets # Predictors: "age" "sex" "bmi" "map" "tc" "ldl" "hdl" "tch" "ltg" "glu" diabetes = datasets.load_diabetes()
_____no_output_____
MIT
notebooks/Day3_2-Model-selection-and-validation.ipynb
vcalderon2009/cqs_machine_learning
Let's examine how a linear regression model performs across a range of sample sizes.
diabetes['data'].shape from sklearn import model_selection def plot_learning_curve(estimator, label=None): scores = list() train_sizes = np.linspace(10, 200, 10).astype(np.int) for train_size in train_sizes: test_error = model_selection.cross_val_score(estimator, diabetes['data'], diabetes['target'...
_____no_output_____
MIT
notebooks/Day3_2-Model-selection-and-validation.ipynb
vcalderon2009/cqs_machine_learning
Notice the linear regression is not defined for scenarios where the number of features/parameters exceeds the number of observations. It performs poorly as long as the number of sample is not several times the number of features. One approach for dealing with overfitting is to **regularize** the regession model.The **r...
from sklearn import preprocessing from sklearn.linear_model import Ridge k = diabetes['data'].shape[1] alphas = np.linspace(0, 4) params = np.zeros((len(alphas), k)) for i,a in enumerate(alphas): X = preprocessing.scale(diabetes['data']) y = diabetes['target'] fit = Ridge(alpha=a, normalize=True).fit...
_____no_output_____
MIT
notebooks/Day3_2-Model-selection-and-validation.ipynb
vcalderon2009/cqs_machine_learning
Notice that at very small sample sizes, the ridge estimator outperforms the unregularized model.The regularization of the ridge is a **shrinkage**: the coefficients learned are shrunk towards zero.The amount of regularization is set via the `alpha` parameter of the ridge, which is tunable. The `RidgeCV` method in `scik...
for a in [0.001, 0.01, 0.1, 1, 10]: plot_learning_curve(Ridge(a), a)
_____no_output_____
MIT
notebooks/Day3_2-Model-selection-and-validation.ipynb
vcalderon2009/cqs_machine_learning
scikit-learn's `RidgeCV` class automatically tunes the L2 penalty using Generalized Cross-Validation.
from sklearn.linear_model import RidgeCV plot_learning_curve(LinearRegression()) plot_learning_curve(Ridge()) plot_learning_curve(RidgeCV())
_____no_output_____
MIT
notebooks/Day3_2-Model-selection-and-validation.ipynb
vcalderon2009/cqs_machine_learning
In contrast to the Ridge estimator, **the Lasso estimator** is useful to impose sparsity on the coefficients. In other words, it is to be prefered if we believe that many of the features are not relevant.$$\hat{\beta}^{lasso} = \text{argmin}_{\beta}\left\{\frac{1}{2}\sum_{i=1}^N (y_i - \beta_0 - \sum_{j=1}^k x_{ij} \be...
from sklearn.linear_model import Lasso k = diabetes['data'].shape[1] alphas = np.linspace(0.1, 3) params = np.zeros((len(alphas), k)) for i,a in enumerate(alphas): X = preprocessing.scale(diabetes['data']) y = diabetes['target'] fit = Lasso(alpha=a, normalize=True).fit(X, y) params[i] = fit.coef_ ...
_____no_output_____
MIT
notebooks/Day3_2-Model-selection-and-validation.ipynb
vcalderon2009/cqs_machine_learning
In this example, the ridge estimator performs better than the lasso, but when there are fewer observations, the lasso matches its performance. Otherwise, the variance-reducing effect of the lasso regularization is unhelpful relative to the increase in bias.With the lasso too, me must tune the regularization parameter f...
from sklearn.linear_model import LassoCV plot_learning_curve(RidgeCV()) plot_learning_curve(LassoCV(n_alphas=10, max_iter=5000))
_____no_output_____
MIT
notebooks/Day3_2-Model-selection-and-validation.ipynb
vcalderon2009/cqs_machine_learning
Can't decide? **ElasticNet** is a compromise between lasso and ridge regression.$$\hat{\beta}^{elastic} = \text{argmin}_{\beta}\left\{\frac{1}{2}\sum_{i=1}^N (y_i - \beta_0 - \sum_{j=1}^k x_{ij} \beta_j)^2 + (1 - \alpha) \sum_{j=1}^k \beta^2_j + \alpha \sum_{j=1}^k |\beta_j| \right\}$$where $\alpha = \lambda_1/(\lambda...
from sklearn.linear_model import ElasticNetCV plot_learning_curve(RidgeCV()) plot_learning_curve(ElasticNetCV(l1_ratio=.7, n_alphas=10))
_____no_output_____
MIT
notebooks/Day3_2-Model-selection-and-validation.ipynb
vcalderon2009/cqs_machine_learning
Using Cross-validation for Parameter Tuning
lasso = Lasso() alphas = np.logspace(-4, -1, 20) scores = np.empty(len(alphas)) scores_std = np.empty(len(alphas)) for i,alpha in enumerate(alphas): lasso.alpha = alpha s = model_selection.cross_val_score(lasso, diabetes.data, diabetes.target, n_jobs=-1) scores[i] = s.mean() scores_std[i] = s.std() pl...
_____no_output_____
MIT
notebooks/Day3_2-Model-selection-and-validation.ipynb
vcalderon2009/cqs_machine_learning
Model Checking using Learning CurvesA useful way of checking model performance (in terms of bias and/or variance) is to plot learning curves, which illustrates the learning process as your model is exposed to more data. When the dataset is small, it is easier for a model of a particular complexity to be made to fit th...
from sklearn.model_selection import learning_curve train_sizes, train_scores, test_scores = learning_curve(lasso, diabetes.data, diabetes.target, train_sizes=[50, 70, 90, 110, 130], cv=5) train_scores_mean = np.mean(tra...
_____no_output_____
MIT
notebooks/Day3_2-Model-selection-and-validation.ipynb
vcalderon2009/cqs_machine_learning
For models with high bias, training and cross-validation scores will tend to converge at a low value (high error), indicating that adding more data will not improve performance. For models with high variance, there may be a gap between the training and cross-validation scores, suggesting that model performance could be...
X,y = salmon.values.T X2 = PolynomialFeatures(degree=2).fit_transform(X[:, None]) train_sizes, train_scores, test_scores = learning_curve(LinearRegression(), X2, y, train_sizes=[10, 15, 20, 30], cv=5) train_scores_mean = np.mean(train_scores, axis=1) train_scores_std = np.s...
_____no_output_____
MIT
notebooks/Day3_2-Model-selection-and-validation.ipynb
vcalderon2009/cqs_machine_learning
Exercise: Very low birthweight infantsCompare logistic regression models (using the `linear_model.LogisticRegression` interface) with varying degrees of regularization for the VLBW infant database. Use a relevant metric such as the Brier's score as a metric.$$B = \frac{1}{n} \sum_{i=1}^n (\hat{p}_i - y_i)^2$$
vlbw = pd.read_csv("../data/vlbw.csv", index_col=0) vlbw = vlbw.replace( { 'inout': { 'born at Duke': 0, 'transported': 1 }, 'delivery': { 'abdominal':0, 'vaginal':1 }, 'ivh': { 'absent': 0, 'present': 1, ...
_____no_output_____
MIT
notebooks/Day3_2-Model-selection-and-validation.ipynb
vcalderon2009/cqs_machine_learning
SalishSeaCast Domain + Ariane CS plotbased on Ben's code from https://github.com/SalishSeaCast/analysis-ben/blob/master/notebooks/Maps.ipynb
import numpy as np import xarray as xr import matplotlib.pyplot as plt from scipy.io import loadmat from cmocean import cm import warnings from cartopy import crs, feature from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER from salishsea_tools import viz_tools, geo_tools # import LambertConforma...
_____no_output_____
Apache-2.0
Ariane/DomainPlot.ipynb
UBC-MOAD/analysis-becca
PlotsThis notebook defines functions for plotting the river reliability and confidence reliability diagrams. Both types of diagrams can be plotted with one figure per class (class-wise) or one aggregated figure for the classifier.
%load_ext autoreload %autoreload 2 #hide from nbdev.showdoc import * # export from riverreliability import utils, metrics as rmetrics import matplotlib.pyplot as plt import matplotlib.axes from matplotlib import cm import numpy as np from scipy.stats import beta from scipy import interpolate from riverreliability.be...
_____no_output_____
Apache-2.0
notebooks/plots.ipynb
MaximLippeveld/riverreliability
Probabilistic classification: toy example
np.random.seed(42) X, y = sklearn.datasets.make_classification(n_samples=5000, n_features=12, n_informative=3, n_classes=3) X_train, X_test, y_train, y_test = sklearn.model_selection.train_test_split(X, y, test_size=0.2, shuffle=True) logreg = sklearn.svm.SVC(probability=True) logreg.fit(X_train, y_train) y_probs = log...
Accuracy: 0.808 Balanced accuracy: 0.8084048918146675
Apache-2.0
notebooks/plots.ipynb
MaximLippeveld/riverreliability
Ridge reliability diagram
# exporti def river_diagram(distributions:np.array, confidence_levels:np.array, ax:matplotlib.axes.Axes, ci:list): ci = sorted(ci)[::-1] _decorate_ax(ax) ax.set_ylim(0, 1) intervals = np.empty((len(confidence_levels), len(ci), 2), dtype=float) means = np.empty((len(confidence_levels),), dtype=fl...
_____no_output_____
Apache-2.0
notebooks/plots.ipynb
MaximLippeveld/riverreliability
Provide an error metric to show the plots ordered according decreasing error.
class_wise_river_reliability_diagram(y_probs, y_probs.argmax(axis=1), y_test, bins="equal-count", metric=rmetrics.peace)
_____no_output_____
Apache-2.0
notebooks/plots.ipynb
MaximLippeveld/riverreliability
Confidence reliability diagram
# exporti def bar_diagram(edges:np.array, bin_accuracies:np.array, bin_confidences:np.array, ax:matplotlib.axes.Axes, bin_sem:np.array=None): """Plot a bar plot confidence reliability diagram. Arguments: edges -- Edges of the probability bins bin_accuracies -- Accuracy per bin bin_confidences -- A...
_____no_output_____
Apache-2.0
notebooks/plots.ipynb
MaximLippeveld/riverreliability
Neuromatch Academy: Week 2, Day 1, Tutorial 3: Fitting to data__Content creators:__ Vincent Valton, Konrad Kording__Content reviewers:__ Matt Krause, Jesse Livezey, Karolina Stosio, Saeed Salehi, Michael Waskom --- Tutorial objectives In this notebook, we'll have a look at computing all the necessary steps to perfor...
import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl from scipy.optimize import minimize #@title Figure Settings import ipywidgets as widgets plt.style.use("https://raw.githubusercontent.com/NeuromatchAcademy/course-content/master/nma.mplstyle") %matplotlib inline %config InlineBackend.figure_for...
_____no_output_____
CC-BY-4.0
tutorials/W2D1_BayesianStatistics/student/W2D1_Tutorial3.ipynb
KeerthanaManikandan/NMA-course-content
--- Introduction
#@title Video 1: Intro from IPython.display import YouTubeVideo video = YouTubeVideo(id='YSKDhnbjKmA', width=854, height=480, fs=1) print("Video available at https://youtube.com/watch?v=" + video.id) video
Video available at https://youtube.com/watch?v=YSKDhnbjKmA
CC-BY-4.0
tutorials/W2D1_BayesianStatistics/student/W2D1_Tutorial3.ipynb
KeerthanaManikandan/NMA-course-content
![Generative model](https://github.com/vincentvalton/figures_NMA_W2D1_T3/blob/master/Drawing%20Generative%20Model%20W2T3.png?raw=true)Here is a graphical representation of the generative model: 1. We present a stimulus $x$ to participants. 2. The brain encodes this true stimulus $x$ noisily (this is the brain's repr...
x = np.arange(-10, 10, 0.1) hypothetical_stim = np.linspace(-8, 8, 1000) def compute_likelihood_array(x_points, stim_array, sigma=1.): # initializing likelihood_array likelihood_array = np.zeros((len(stim_array), len(x_points))) # looping over stimulus array for i in range(len(stim_array)): ...
_____no_output_____
CC-BY-4.0
tutorials/W2D1_BayesianStatistics/student/W2D1_Tutorial3.ipynb
KeerthanaManikandan/NMA-course-content
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W2D1_BayesianStatistics/solutions/W2D1_Tutorial3_Solution_9e34b2b1.py)*Example output:* --- Section 2: Causal mixture of Gaussian prior
#@title Video 2: Prior array video = YouTubeVideo(id='F0IYpUicXu4', width=854, height=480, fs=1) print("Video available at https://youtube.com/watch?v=" + video.id) video
Video available at https://youtube.com/watch?v=F0IYpUicXu4
CC-BY-4.0
tutorials/W2D1_BayesianStatistics/student/W2D1_Tutorial3.ipynb
KeerthanaManikandan/NMA-course-content
As in Tutorial 2, we want to create a prior that will describe the participants' prior knowledge that sounds come 75% of the time from a common position around the puppet, and 25% of the time from another independent position. We will embody this information into a prior using a mixture of Gaussians. For visualization ...
x = np.arange(-10, 10, 0.1) def calculate_prior_array(x_points, stim_array, p_indep, prior_mean_common=.0, prior_sigma_common=.5, prior_mean_indep=.0, prior_sigma_indep=10): """ 'common' stands for common 'indep' stands for independent """ ...
_____no_output_____
CC-BY-4.0
tutorials/W2D1_BayesianStatistics/student/W2D1_Tutorial3.ipynb
KeerthanaManikandan/NMA-course-content
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W2D1_BayesianStatistics/solutions/W2D1_Tutorial3_Solution_89e387f7.py)*Example output:* --- Section 3: Bayes rule and Posterior array
#@title Video 3: Posterior array video = YouTubeVideo(id='HpOzXZUKFJc', width=854, height=480, fs=1) print("Video available at https://youtube.com/watch?v=" + video.id) video
Video available at https://youtube.com/watch?v=HpOzXZUKFJc
CC-BY-4.0
tutorials/W2D1_BayesianStatistics/student/W2D1_Tutorial3.ipynb
KeerthanaManikandan/NMA-course-content
We now want to calcualte the posterior using *Bayes Rule*. Since we have already created a likelihood and a prior for each hypothetical stimulus x, all we need to do is to multiply them row-wise. That is, each row of the posterior array will be the posterior resulting from the multiplication of the prior and likelihood...
def calculate_posterior_array(prior_array, likelihood_array): ############################################################################ ## Insert your code here to: ## - calculate the 'posterior_array' from the given ## 'prior_array', 'likelihood_array' ## - normalize ## rem...
_____no_output_____
CC-BY-4.0
tutorials/W2D1_BayesianStatistics/student/W2D1_Tutorial3.ipynb
KeerthanaManikandan/NMA-course-content
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W2D1_BayesianStatistics/solutions/W2D1_Tutorial3_Solution_9cdc9264.py)*Example output:* --- Section 4: Estimating the position $\hat x$
#@title Video 4: Binary decision matrix video = YouTubeVideo(id='gy3GmlssHgQ', width=854, height=480, fs=1) print("Video available at https://youtube.com/watch?v=" + video.id) video
Video available at https://youtube.com/watch?v=gy3GmlssHgQ
CC-BY-4.0
tutorials/W2D1_BayesianStatistics/student/W2D1_Tutorial3.ipynb
KeerthanaManikandan/NMA-course-content
Now that we have a posterior distribution that represents the brain's estimated stimulus position: $p(x|\tilde x)$, we want to make an estimate (response) of the sound location $\hat x$ using the posterior distribution. The participant's noisy estimate of the stimulus position $\hat x$ is the participant's percept. Thi...
def calculate_binary_decision_array(x_points, posterior_array): binary_decision_array = np.zeros_like(posterior_array) for i in range(len(posterior_array)): ######################################################################## ## Insert your code here to: ## - For each hypothe...
_____no_output_____
CC-BY-4.0
tutorials/W2D1_BayesianStatistics/student/W2D1_Tutorial3.ipynb
KeerthanaManikandan/NMA-course-content
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W2D1_BayesianStatistics/solutions/W2D1_Tutorial3_Solution_d0399098.py)*Example output:* --- Section 5: Probabilities of encoded stimuli
#@title Video 5: Input array video = YouTubeVideo(id='C1d1n_Si83o', width=854, height=480, fs=1) print("Video available at https://youtube.com/watch?v=" + video.id) video
Video available at https://youtube.com/watch?v=C1d1n_Si83o
CC-BY-4.0
tutorials/W2D1_BayesianStatistics/student/W2D1_Tutorial3.ipynb
KeerthanaManikandan/NMA-course-content
Because the brain does not have access to the true presented stimulus, we had to compute the binary decision array for hypothetical stimulus values of $x$. We will then use that information when presented with a real stimulus $x$. First however, we need to create the input from the true presented stimulus. That is, we ...
def generate_input_array(x_points, stim_array, posterior_array, mean=-2.5, sigma=1.): input_array = np.zeros_like(posterior_array) ######################################################################## ## Insert your code here to: ## - Generate a gaussian centered on th...
_____no_output_____
CC-BY-4.0
tutorials/W2D1_BayesianStatistics/student/W2D1_Tutorial3.ipynb
KeerthanaManikandan/NMA-course-content
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W2D1_BayesianStatistics/solutions/W2D1_Tutorial3_Solution_41daa20a.py)*Example output:* --- Section 6: Normalization and expected estimate distribution
#@title Video 6: Marginalization video = YouTubeVideo(id='5alwtNS4CGw', width=854, height=480, fs=1) print("Video available at https://youtube.com/watch?v=" + video.id) video
Video available at https://youtube.com/watch?v=5alwtNS4CGw
CC-BY-4.0
tutorials/W2D1_BayesianStatistics/student/W2D1_Tutorial3.ipynb
KeerthanaManikandan/NMA-course-content
Now that we have a true stimulus $x$ and a way to link it to hypothetical stimulus locations, we will be able to estimate what is the brain's representation of the true stimulus $x$ by integrating over all the possible hypothetical stimulus locations that the brain could have been expecting. This is because the brain d...
def my_marginalization(input_array, binary_decision_array): ############################################################################ ## Insert your code here to: ## - Compute 'marginalization_array' by multiplying pointwise the Binary ## decision array over hypothetical stimuli and the Input ar...
_____no_output_____
CC-BY-4.0
tutorials/W2D1_BayesianStatistics/student/W2D1_Tutorial3.ipynb
KeerthanaManikandan/NMA-course-content
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W2D1_BayesianStatistics/solutions/W2D1_Tutorial3_Solution_910a90df.py)*Example output:* --- Generate some dataNow that we've seen how to calculate the posterior and marginalize to get $p(\hat{x} \mid x)$, we will generate ...
#@title #@markdown #### Run the 'generate_data' function (this cell) def generate_data(x_stim, p_independent): """ DO NOT EDIT THIS FUNCTION !!! Returns generated data using the mixture of Gaussian prior with mixture parameter `p_independent` Args : x_stim (numpy array of floats) - x values at which s...
_____no_output_____
CC-BY-4.0
tutorials/W2D1_BayesianStatistics/student/W2D1_Tutorial3.ipynb
KeerthanaManikandan/NMA-course-content
---Section 7: Model fitting
#@title Video 7: Log likelihood video = YouTubeVideo(id='jbYauFpyZhs', width=854, height=480, fs=1) print("Video available at https://youtube.com/watch?v=" + video.id) video
Video available at https://youtube.com/watch?v=jbYauFpyZhs
CC-BY-4.0
tutorials/W2D1_BayesianStatistics/student/W2D1_Tutorial3.ipynb
KeerthanaManikandan/NMA-course-content
Now that we have generated some data, we will attempt to recover the parameter $p_{independent}$ that was used to generate it.We have provided you with an incomplete function called `my_Bayes_model_mse()` that needs to be completed to perform the same computations you have performed in the previous exercises but over a...
def my_Bayes_model_mse(params): """ Function fits the Bayesian model from Tutorial 4 Args : params (list of positive floats): parameters used by the model (params[0] = posterior scaling) Returns : (scalar) negative log-likelihood :sum of log probabiliti...
_____no_output_____
CC-BY-4.0
tutorials/W2D1_BayesianStatistics/student/W2D1_Tutorial3.ipynb
KeerthanaManikandan/NMA-course-content
[*Click for solution*](https://github.com/NeuromatchAcademy/course-content/tree/master//tutorials/W2D1_BayesianStatistics/solutions/W2D1_Tutorial3_Solution_4dc32c4b.py)*Example output:* Section 8: Summary
#@title Video 8: Outro video = YouTubeVideo(id='F5JfqJonz20', width=854, height=480, fs=1) print("Video available at https://youtube.com/watch?v=" + video.id) video
Video available at https://youtube.com/watch?v=F5JfqJonz20
CC-BY-4.0
tutorials/W2D1_BayesianStatistics/student/W2D1_Tutorial3.ipynb
KeerthanaManikandan/NMA-course-content
Note* Instructions have been included for each segment. You do not have to follow them exactly, but they are included to help you think through the steps.
# Dependencies and Setup import pandas as pd # File to Load (Remember to Change These) school_data_to_load = "../Resources/JamesWilliams_schools_complete.csv" student_data_to_load = "../Resources/JamesWilliams_students_complete.csv" # Read School and Student Data File and store into Pandas DataFrames school_data = pd...
_____no_output_____
ADSL
PyCitySchools/JamesWilliams_PyCitySchools.ipynb
jtwilliams17/pandas-challenge
District Summary* Calculate the total number of schools* Calculate the total number of students* Calculate the total budget* Calculate the average math score * Calculate the average reading score* Calculate the percentage of students with a passing math score (70 or greater)* Calculate the percentage of students with ...
# count number of schools and students using nunique function total_number_schools = school_data_complete["school_name"].nunique() total_number_students = school_data_complete["student_name"].count() # extract and sum all budgets for each high school unique_budgets = school_data_complete["budget"].unique() total_budge...
<ipython-input-3-a007a1ef4fd9>:22: UserWarning: Boolean Series key will be reindexed to match DataFrame index. both_above_70 = math_above_70[(school_data_complete["reading_score"] >= 70)]
ADSL
PyCitySchools/JamesWilliams_PyCitySchools.ipynb
jtwilliams17/pandas-challenge
School Summary * Create an overview table that summarizes key metrics about each school, including: * School Name * School Type * Total Students * Total School Budget * Per Student Budget * Average Math Score * Average Reading Score * % Passing Math * % Passing Reading * % Overall Passing (The percentage of ...
# Collect school names and group by each school high_school_names = school_data_complete["school_name"].unique high_school_group = school_data_complete.groupby(["school_name"]) # calculations for the grouped schools school_type = high_school_group["type"].unique() total_students_per_school = high_school_group["student_...
_____no_output_____
ADSL
PyCitySchools/JamesWilliams_PyCitySchools.ipynb
jtwilliams17/pandas-challenge
Top Performing Schools (By % Overall Passing) * Sort and display the top five performing schools by % overall passing.
# sort values base on % overall pass descending overall_pass_summary_desc = per_school_summary.sort_values("% Overall Passing", ascending=False) # display the top five schools top5_overall_pass_summary = overall_pass_summary_desc.head() top5_overall_pass_summary
_____no_output_____
ADSL
PyCitySchools/JamesWilliams_PyCitySchools.ipynb
jtwilliams17/pandas-challenge
Bottom Performing Schools (By % Overall Passing) * Sort and display the five worst-performing schools by % overall passing.
# sort values base on % overall pass ascending overall_pass_summary_asc = per_school_summary.sort_values("% Overall Passing") # display the bottom five schools bottom5_overall_pass_summary = overall_pass_summary_asc.head() bottom5_overall_pass_summary
_____no_output_____
ADSL
PyCitySchools/JamesWilliams_PyCitySchools.ipynb
jtwilliams17/pandas-challenge
Math Scores by Grade * Create a table that lists the average Reading Score for students of each grade level (9th, 10th, 11th, 12th) at each school. * Create a pandas series for each grade. Hint: use a conditional statement. * Group each series by school * Combine the series into a dataframe * Optional: give ...
# create series' for each grade ninth_school_data = school_data_complete[(school_data_complete["grade"] == "9th")] tenth_school_data = school_data_complete[(school_data_complete["grade"] == "10th")] eleventh_school_data = school_data_complete[(school_data_complete["grade"] == "11th")] twelfth_school_data = school_data_...
_____no_output_____
ADSL
PyCitySchools/JamesWilliams_PyCitySchools.ipynb
jtwilliams17/pandas-challenge
Reading Score by Grade * Perform the same operations as above for reading scores
# average reading score for each grade ninth_avg_reading = ninth_school_data_per_school["reading_score"].mean() tenth_avg_reading = tenth_school_data_per_school["reading_score"].mean() eleventh_avg_reading = eleventh_school_data_per_school["reading_score"].mean() twelfth_avg_reading = twelfth_school_data_per_school["re...
_____no_output_____
ADSL
PyCitySchools/JamesWilliams_PyCitySchools.ipynb
jtwilliams17/pandas-challenge
Scores by School Spending * Create a table that breaks down school performances based on average Spending Ranges (Per Student). Use 4 reasonable bins to group school spending. Include in the table each of the following: * Average Math Score * Average Reading Score * % Passing Math * % Passing Reading * Overall Pa...
# create bins bins = [0,584,629,644,675] # create names for the bins group_names = ["<$584","$585-629","$630-644","$645-675"] # convert data type back to float from $ (found on stack overflow) per_school_summary["Per Student Budget"] = per_school_summary["Per Student Budget"]\ .replace('[\$,]', '', regex=True).as...
_____no_output_____
ADSL
PyCitySchools/JamesWilliams_PyCitySchools.ipynb
jtwilliams17/pandas-challenge
Scores by School Size * Perform the same operations as above, based on school size.
# create bins bins = [0,1000,2000,5000] # create names for the bins group_names = ["Small (<1000)","Medium (1000-2000)","Large (2000-5000)"] # slice and put into bins, then place as series into data frame per_school_summary["School Size"] = pd.cut(per_school_summary["Total Students"], ...
_____no_output_____
ADSL
PyCitySchools/JamesWilliams_PyCitySchools.ipynb
jtwilliams17/pandas-challenge
Scores by School Type * Perform the same operations as above, based on school type
# group summary table by the spending ranges per_school_type_group = per_school_summary.groupby("School Type") # calculations after groups created per_school_type_group[["Average Math Score", "Average Reading Score", "% Passing Math", "% Passing Reading" , "% Overall Passing"]].mean()
_____no_output_____
ADSL
PyCitySchools/JamesWilliams_PyCitySchools.ipynb
jtwilliams17/pandas-challenge
from sklearn.feature_extraction.text import CountVectorizer import nltk import numpy as np import pandas as pd import re nltk.download('stopwords') corpus = ['The sky is blue and beautiful.', 'Love this blue and beautiful sky!', 'The quick brown fox jumps over the lazy dog.', "A king's br...
_____no_output_____
MIT
feature_engg_text.ipynb
bipinKrishnan/fastai_course
Vectorizing text
cv = CountVectorizer(min_df=0., max_df=1.) cv_matrix = cv.fit_transform(norm_corp).toarray() cv_matrix vocab = cv.get_feature_names() vocab pd.DataFrame(cv_matrix, columns=vocab) cv.transform(['sky is good and beautiful beautiful today']).toarray()
_____no_output_____
MIT
feature_engg_text.ipynb
bipinKrishnan/fastai_course
ngram_range --> if set to (1, 2) --> creates uni-gram and bi-gram --> if set to (2, 2) --> creates only bi-gram --> if set to (1, 3) --> creates only uni-gram, bi-gram and tri-gram
cv = CountVectorizer(ngram_range=(2, 2)) cv_matrix = cv.fit_transform(norm_corp).toarray() pd.DataFrame(cv_matrix, columns=cv.get_feature_names()) cv1 = CountVectorizer(ngram_range=(1, 3)) cv1_matrix = cv1.fit_transform(norm_corp).toarray() pd.DataFrame(cv1_matrix, columns=cv1.get_feature_names())
_____no_output_____
MIT
feature_engg_text.ipynb
bipinKrishnan/fastai_course
Tfidf(Term frequency and Inverse document frequency)
from sklearn.feature_extraction.text import TfidfVectorizer
_____no_output_____
MIT
feature_engg_text.ipynb
bipinKrishnan/fastai_course
Creates vector based on the frequency and inverse document frequency value of ech words and displays the words based on the value or threshold frequency passed to the min_df and max_df value
tfidf = TfidfVectorizer() tf_matrix = tfidf.fit_transform(norm_corp).toarray() tf_matrix pd.DataFrame(tf_matrix, columns=tfidf.get_feature_names()) len(tfidf.get_feature_names()), len(cv.get_feature_names())
_____no_output_____
MIT
feature_engg_text.ipynb
bipinKrishnan/fastai_course
Ensemble the model
r2_score_list = [] prediction_list = [] for i in range(1): estimator.fit(x_train_scaled, y_train, batch_size=32, epochs=50, verbose=2, callbacks=callbacks, validation_split=0.1, shuffle=False) y_pred_train = estimator.predict(x_train_scaled) prediction = estimator.predic...
_____no_output_____
MIT
Kaggle/Mercedes-Benz Greener Manufacturing/feed_neural_network.ipynb
datitran/Krimskrams
- Número de grupo:- Nombre de los integrantes del grupo: Práctica 3 : representación de conocimiento Parte 1: consultas SPARQL sobre Wikidata. EjemploRecuperar todas las instancias directas de la clase [Cabra (Q2934)](https://www.wikidata.org/wiki/Q2934) que aparecen en la base de conocimiento. En esta práctica vamo...
#Esta celda es de tipo Raw NBConvert y así jupyter notebook no la interpreta al ejecutarla. #Hay que copiar y pegar la consulta en el punto de acceso SPARQL en https://query.wikidata.org/ SELECT ?item ?itemLabel WHERE { ?item wdt:P31 wd:Q2934. # instancias directas de la clase Cabra (goat (Q2934)) instance of (P3...
_____no_output_____
MIT
Practica3/Practica 3. Sistemas Inteligentes .ipynb
gonzalofdv/SI20-21
itemitemLabelhttp://www.wikidata.org/entity/Q151345Billygoat Henneshttp://www.wikidata.org/entity/Q3569037William Windsorhttp://www.wikidata.org/entity/Q23003932His Whiskershttp://www.wikidata.org/entity/Q24287064Taffyhttp://www.wikidata.org/entity/Q41239734Lance Corporal Shenkin IIIhttp://www.wikidata.org/entity/Q4124...
#%pip install qwikidata from qwikidata.sparql import return_sparql_query_results sparql_query = """ SELECT ?item ?itemLabel WHERE { ?item wdt:P31 wd:Q2934. SERVICE wikibase:label { bd:serviceParam wikibase:language "en". } } """ res = return_sparql_query_results(sparql_query) res # También hay alguna función de ...
_____no_output_____
MIT
Practica3/Practica 3. Sistemas Inteligentes .ipynb
gonzalofdv/SI20-21
Interfaz Linked dataPodemos recuperar la información de distintas entidades y propiedades de Wikidata y acceder a ellas mediante objetos de Python. En este ejemplo vamos a trabajar con el item [Douglas Adams (Q42)](https://www.wikidata.org/wiki/Q42).
from qwikidata.entity import WikidataItem, WikidataProperty, WikidataLexeme from qwikidata.linked_data_interface import get_entity_dict_from_api # obtener un objeto con la información del escritor douglas Adams Q_DOUGLAS_ADAMS = 'Q42' q42_dict = get_entity_dict_from_api(Q_DOUGLAS_ADAMS) q42 = WikidataItem(q42_dict) q...
_____no_output_____
MIT
Practica3/Practica 3. Sistemas Inteligentes .ipynb
gonzalofdv/SI20-21
TV Script GenerationIn this project, you'll generate your own [Simpsons](https://en.wikipedia.org/wiki/The_Simpsons) TV scripts using RNNs. You'll be using part of the [Simpsons dataset](https://www.kaggle.com/wcukierski/the-simpsons-by-the-data) of scripts from 27 seasons. The Neural Network you'll build will gener...
""" DON'T MODIFY ANYTHING IN THIS CELL """ import helper data_dir = './data/simpsons/moes_tavern_lines.txt' text = helper.load_data(data_dir) # Ignore notice, since we don't use it for analysing the data text = text[81:]
_____no_output_____
MIT
tv-script-generation/dlnd_tv_script_generation.ipynb
dxl0632/deeplearning_nd_udacity
Explore the DataPlay around with `view_sentence_range` to view different parts of the data.
view_sentence_range = (0, 10) """ DON'T MODIFY ANYTHING IN THIS CELL """ import numpy as np print('Dataset Stats') print('Roughly the number of unique words: {}'.format(len({word: None for word in text.split()}))) scenes = text.split('\n\n') print('Number of scenes: {}'.format(len(scenes))) sentence_count_scene = [sc...
Dataset Stats Roughly the number of unique words: 11492 Number of scenes: 262 Average number of sentences in each scene: 15.248091603053435 Number of lines: 4257 Average number of words in each line: 11.50434578341555 The sentences 0 to 10: Moe_Szyslak: (INTO PHONE) Moe's Tavern. Where the elite meet to drink. Bart_Si...
MIT
tv-script-generation/dlnd_tv_script_generation.ipynb
dxl0632/deeplearning_nd_udacity
Implement Preprocessing FunctionsThe first thing to do to any dataset is preprocessing. Implement the following preprocessing functions below:- Lookup Table- Tokenize Punctuation Lookup TableTo create a word embedding, you first need to transform the words to ids. In this function, create two dictionaries:- Dictiona...
import numpy as np import problem_unittests as tests from collections import Counter def create_lookup_tables(text): """ Create lookup tables for vocabulary :param text: The text of tv scripts split into words :return: A tuple of dicts (vocab_to_int, int_to_vocab) """ # TODO: Implement Function...
Tests Passed
MIT
tv-script-generation/dlnd_tv_script_generation.ipynb
dxl0632/deeplearning_nd_udacity
Tokenize PunctuationWe'll be splitting the script into a word array using spaces as delimiters. However, punctuations like periods and exclamation marks make it hard for the neural network to distinguish between the word "bye" and "bye!".Implement the function `token_lookup` to return a dict that will be used to toke...
def token_lookup(): """ Generate a dict to turn punctuation into a token. :return: Tokenize dictionary where the key is the punctuation and the value is the token """ # TODO: Implement Function rs = {".": "||period||", ",": "||comma||", '"': "||quotation||", ";": "|...
Tests Passed
MIT
tv-script-generation/dlnd_tv_script_generation.ipynb
dxl0632/deeplearning_nd_udacity
Preprocess all the data and save itRunning the code cell below will preprocess all the data and save it to file.
""" DON'T MODIFY ANYTHING IN THIS CELL """ # Preprocess Training, Validation, and Testing Data helper.preprocess_and_save_data(data_dir, token_lookup, create_lookup_tables)
_____no_output_____
MIT
tv-script-generation/dlnd_tv_script_generation.ipynb
dxl0632/deeplearning_nd_udacity
Check PointThis is your first checkpoint. If you ever decide to come back to this notebook or have to restart the notebook, you can start from here. The preprocessed data has been saved to disk.
""" DON'T MODIFY ANYTHING IN THIS CELL """ import helper import numpy as np import problem_unittests as tests int_text, vocab_to_int, int_to_vocab, token_dict = helper.load_preprocess()
_____no_output_____
MIT
tv-script-generation/dlnd_tv_script_generation.ipynb
dxl0632/deeplearning_nd_udacity
Build the Neural NetworkYou'll build the components necessary to build a RNN by implementing the following functions below:- get_inputs- get_init_cell- get_embed- build_rnn- build_nn- get_batches Check the Version of TensorFlow and Access to GPU
""" DON'T MODIFY ANYTHING IN THIS CELL """ from distutils.version import LooseVersion import warnings import tensorflow as tf # Check TensorFlow Version assert LooseVersion(tf.__version__) >= LooseVersion('1.0'), 'Please use TensorFlow version 1.0 or newer' print('TensorFlow Version: {}'.format(tf.__version__)) # Che...
TensorFlow Version: 1.1.0 Default GPU Device: /gpu:0
MIT
tv-script-generation/dlnd_tv_script_generation.ipynb
dxl0632/deeplearning_nd_udacity
InputImplement the `get_inputs()` function to create TF Placeholders for the Neural Network. It should create the following placeholders:- Input text placeholder named "input" using the [TF Placeholder](https://www.tensorflow.org/api_docs/python/tf/placeholder) `name` parameter.- Targets placeholder- Learning Rate pl...
def get_inputs(): """ Create TF Placeholders for input, targets, and learning rate. :return: Tuple (input, targets, learning rate) """ # TODO: Implement Function inputs = tf.placeholder(tf.int32, [None, None], name='input') targets = tf.placeholder(tf.int32, [None, None], name='targets') ...
Tests Passed
MIT
tv-script-generation/dlnd_tv_script_generation.ipynb
dxl0632/deeplearning_nd_udacity
Build RNN Cell and InitializeStack one or more [`BasicLSTMCells`](https://www.tensorflow.org/api_docs/python/tf/contrib/rnn/BasicLSTMCell) in a [`MultiRNNCell`](https://www.tensorflow.org/api_docs/python/tf/contrib/rnn/MultiRNNCell).- The Rnn size should be set using `rnn_size`- Initalize Cell State using the MultiRNN...
def lstm_cell(lstm_size, keep_prob): cell = tf.contrib.rnn.BasicLSTMCell(lstm_size, reuse=tf.get_variable_scope().reuse) return tf.contrib.rnn.DropoutWrapper(cell, output_keep_prob=keep_prob) def get_init_cell(batch_size, rnn_size, num_layers=3, keep_prob=0.5): """ Create an RNN Cell and initialize it....
Tests Passed
MIT
tv-script-generation/dlnd_tv_script_generation.ipynb
dxl0632/deeplearning_nd_udacity
Word EmbeddingApply embedding to `input_data` using TensorFlow. Return the embedded sequence.
def get_embed(input_data, vocab_size, embed_dim): """ Create embedding for <input_data>. :param input_data: TF placeholder for text input. :param vocab_size: Number of words in vocabulary. :param embed_dim: Number of embedding dimensions :return: Embedded input. """ # TODO: Implement Fun...
Tests Passed
MIT
tv-script-generation/dlnd_tv_script_generation.ipynb
dxl0632/deeplearning_nd_udacity
Build RNNYou created a RNN Cell in the `get_init_cell()` function. Time to use the cell to create a RNN.- Build the RNN using the [`tf.nn.dynamic_rnn()`](https://www.tensorflow.org/api_docs/python/tf/nn/dynamic_rnn) - Apply the name "final_state" to the final state using [`tf.identity()`](https://www.tensorflow.org/a...
def build_rnn(cell, inputs): """ Create a RNN using a RNN Cell :param cell: RNN Cell :param inputs: Input text data :return: Tuple (Outputs, Final State) """ # TODO: Implement Function outputs, state = tf.nn.dynamic_rnn(cell, inputs, dtype=tf.float32) state = tf.identity(state, name=...
Tests Passed
MIT
tv-script-generation/dlnd_tv_script_generation.ipynb
dxl0632/deeplearning_nd_udacity
Build the Neural NetworkApply the functions you implemented above to:- Apply embedding to `input_data` using your `get_embed(input_data, vocab_size, embed_dim)` function.- Build RNN using `cell` and your `build_rnn(cell, inputs)` function.- Apply a fully connected layer with a linear activation and `vocab_size` as the...
def build_nn(cell, rnn_size, input_data, vocab_size, embed_dim): """ Build part of the neural network :param cell: RNN cell :param rnn_size: Size of rnns :param input_data: Input data :param vocab_size: Vocabulary size :param embed_dim: Number of embedding dimensions :return: Tuple (Logi...
Tests Passed
MIT
tv-script-generation/dlnd_tv_script_generation.ipynb
dxl0632/deeplearning_nd_udacity
BatchesImplement `get_batches` to create batches of input and targets using `int_text`. The batches should be a Numpy array with the shape `(number of batches, 2, batch size, sequence length)`. Each batch contains two elements:- The first element is a single batch of **input** with the shape `[batch size, sequence le...
def get_batches(int_text, batch_size, seq_length): """ Return batches of input and target :param int_text: Text with the words replaced by their ids :param batch_size: The size of batch :param seq_length: The length of sequence :return: Batches as a Numpy array """ # TODO: Implement Func...
Tests Passed
MIT
tv-script-generation/dlnd_tv_script_generation.ipynb
dxl0632/deeplearning_nd_udacity
Neural Network Training HyperparametersTune the following parameters:- Set `num_epochs` to the number of epochs.- Set `batch_size` to the batch size.- Set `rnn_size` to the size of the RNNs.- Set `embed_dim` to the size of the embedding.- Set `seq_length` to the length of sequence.- Set `learning_rate` to the learning...
# Number of Epochs # Enough epochs to get near a minimum in the training loss, # no real upper limit on this. Just need to make sure the # training loss is low and not improving much with more training. num_epochs = 200 # Batch Size # Batch size is large enough to train efficiently, but small # enough to fit the da...
_____no_output_____
MIT
tv-script-generation/dlnd_tv_script_generation.ipynb
dxl0632/deeplearning_nd_udacity
Build the GraphBuild the graph using the neural network you implemented.
""" DON'T MODIFY ANYTHING IN THIS CELL """ from tensorflow.contrib import seq2seq train_graph = tf.Graph() with train_graph.as_default(): vocab_size = len(int_to_vocab) input_text, targets, lr = get_inputs() input_data_shape = tf.shape(input_text) cell, initial_state = get_init_cell(input_data_shape[0]...
_____no_output_____
MIT
tv-script-generation/dlnd_tv_script_generation.ipynb
dxl0632/deeplearning_nd_udacity
TrainTrain the neural network on the preprocessed data. If you have a hard time getting a good loss, check the [forms](https://discussions.udacity.com/) to see if anyone is having the same problem.
""" DON'T MODIFY ANYTHING IN THIS CELL """ batches = get_batches(int_text, batch_size, seq_length) with tf.Session(graph=train_graph) as sess: sess.run(tf.global_variables_initializer()) for epoch_i in range(num_epochs): state = sess.run(initial_state, {input_text: batches[0][0]}) for batch_i...
Epoch 0 Batch 0/16 train_loss = 8.832 Epoch 0 Batch 10/16 train_loss = 6.254 Epoch 1 Batch 4/16 train_loss = 5.598 Epoch 1 Batch 14/16 train_loss = 5.381 Epoch 2 Batch 8/16 train_loss = 5.181 Epoch 3 Batch 2/16 train_loss = 5.019 Epoch 3 Batch 12/16 train_loss = 4.798 Epoch...
MIT
tv-script-generation/dlnd_tv_script_generation.ipynb
dxl0632/deeplearning_nd_udacity
Save ParametersSave `seq_length` and `save_dir` for generating a new TV script.
""" DON'T MODIFY ANYTHING IN THIS CELL """ # Save parameters for checkpoint helper.save_params((seq_length, save_dir))
_____no_output_____
MIT
tv-script-generation/dlnd_tv_script_generation.ipynb
dxl0632/deeplearning_nd_udacity
Checkpoint
""" DON'T MODIFY ANYTHING IN THIS CELL """ import tensorflow as tf import numpy as np import helper import problem_unittests as tests _, vocab_to_int, int_to_vocab, token_dict = helper.load_preprocess() seq_length, load_dir = helper.load_params()
_____no_output_____
MIT
tv-script-generation/dlnd_tv_script_generation.ipynb
dxl0632/deeplearning_nd_udacity