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
To perform Binary classification on Tabular data, SageMaker contains following algorithms:- XGBoost Algorithm- Linear Learner Algorithm, - K-Nearest Neighbors (k-NN) Algorithm, Create model 1: XGBoost model in SageMaker Use the XGBoost built-in algorithm to build an XGBoost training container as shown in the followin...
container <- sagemaker$image_uris$retrieve(framework='xgboost', region= session$boto_region_name, version='latest') cat('XGBoost Container Image URL: ', container) s3_output <- paste0('s3://', bucket, '/output_xgboost') estimator1 <- sagemaker$estimator$Estimator(image_uri = container, ...
_____no_output_____
Apache-2.0
r_examples/r_sagemaker_binary_classification_algorithms/R_binary_classification_algorithms_comparison.ipynb
vllyakho/amazon-sagemaker-examples
How would an untuned model perform compared to a tuned model? Is it worth the effort? Before going deeper into XGBoost model tuning, let’s highlight the reasons why you have to tune your model. The main reason to perform hyper-parameter tuning is to increase predictability of our models by choosing our hyperparameters ...
# check to make sure which are required and which are optional estimator1$set_hyperparameters(eval_metric='auc', objective='binary:logistic', num_round = 6L ) # Set Hyperparameter Ranges, check to make sure which are integer and ...
_____no_output_____
Apache-2.0
r_examples/r_sagemaker_binary_classification_algorithms/R_binary_classification_algorithms_comparison.ipynb
vllyakho/amazon-sagemaker-examples
The evaluation metric that we will use for our binary classification purpose is validation:auc, but you could use any other metric that is right for your problem. You do have to be careful to change your objective_type to point to the right direction of Maximize or Minimize according to the objective metric you have ch...
# Create a hyperparamter tuner objective_metric_name = 'validation:auc' tuner1 <- sagemaker$tuner$HyperparameterTuner(estimator1, objective_metric_name, hyperparameter_ranges, objective...
_____no_output_____
Apache-2.0
r_examples/r_sagemaker_binary_classification_algorithms/R_binary_classification_algorithms_comparison.ipynb
vllyakho/amazon-sagemaker-examples
The output of the tuning job can be checked in SageMaker if needed. Calculate AUC for the test data on model 1 SageMaker will automatically recognize the training job with the best evaluation metric and load the hyperparameters associated with that training job when we deploy the model. One of the benefits of SageMake...
model_endpoint1 <- tuner1$deploy(initial_instance_count = 1L, instance_type = 'ml.t2.medium')
_____no_output_____
Apache-2.0
r_examples/r_sagemaker_binary_classification_algorithms/R_binary_classification_algorithms_comparison.ipynb
vllyakho/amazon-sagemaker-examples
The serializer tells SageMaker what format the model expects data to be input in.
model_endpoint1$serializer <- sagemaker$serializers$CSVSerializer(content_type='text/csv')
_____no_output_____
Apache-2.0
r_examples/r_sagemaker_binary_classification_algorithms/R_binary_classification_algorithms_comparison.ipynb
vllyakho/amazon-sagemaker-examples
We input the `iris_test` dataset without the labels into the model using the `predict` function and check its AUC value.
# Prepare the test sample for input into the model test_sample <- as.matrix(iris_test[-1]) dimnames(test_sample)[[2]] <- NULL # Predict using the deployed model predictions_ep <- model_endpoint1$predict(test_sample) predictions_ep <- stringr::str_split(predictions_ep, pattern = ',', simplify = TRUE) predictions_ep <- ...
_____no_output_____
Apache-2.0
r_examples/r_sagemaker_binary_classification_algorithms/R_binary_classification_algorithms_comparison.ipynb
vllyakho/amazon-sagemaker-examples
Create model 2: Linear Learner in SageMaker Linear models are supervised learning algorithms used for solving either classification or regression problems. For input, you give the model labeled examples (x, y). x is a high-dimensional vector and y is a numeric label. For binary classification problems, the label must ...
container <- sagemaker$image_uris$retrieve(framework='linear-learner', region= session$boto_region_name, version='latest') cat('Linear Learner Container Image URL: ', container) s3_output <- paste0('s3://', bucket, '/output_glm') estimator2 <- sagemaker$estimator$Estimator(image_uri = container, ...
_____no_output_____
Apache-2.0
r_examples/r_sagemaker_binary_classification_algorithms/R_binary_classification_algorithms_comparison.ipynb
vllyakho/amazon-sagemaker-examples
For the text/csv input type, the first column is assumed to be the label, which is the target variable for prediction. predictor_type is the only hyperparameter that is required to be pre-defined for tuning. The rest are optional. Normalization, or feature scaling, is an important preprocessing step for certain loss fu...
estimator2$set_hyperparameters(predictor_type="binary_classifier", normalize_data = TRUE)
_____no_output_____
Apache-2.0
r_examples/r_sagemaker_binary_classification_algorithms/R_binary_classification_algorithms_comparison.ipynb
vllyakho/amazon-sagemaker-examples
The tunable hyperparameters for linear learner are:- wd- l1- learning_rate- mini_batch_size- use_bias- positive_example_weight_multBe careful to check which parameters are integers and which parameters are continuous because that is one of the common sources of errors. Also be careful to give a proper range for hyperpa...
# Set Hyperparameter Ranges hyperparameter_ranges = list('wd' = sagemaker$parameter$ContinuousParameter(0.00001,1), 'l1' = sagemaker$parameter$ContinuousParameter(0.00001,1), 'learning_rate' = sagemaker$parameter$ContinuousParameter(0.00001,1), ...
_____no_output_____
Apache-2.0
r_examples/r_sagemaker_binary_classification_algorithms/R_binary_classification_algorithms_comparison.ipynb
vllyakho/amazon-sagemaker-examples
The evaluation metric we will be using in our case to compare the models will be the objective loss and is based on the validation dataset.
# Create a hyperparamter tuner objective_metric_name = 'validation:objective_loss' tuner2 <- sagemaker$tuner$HyperparameterTuner(estimator2, objective_metric_name, hyperparameter_ranges, ...
_____no_output_____
Apache-2.0
r_examples/r_sagemaker_binary_classification_algorithms/R_binary_classification_algorithms_comparison.ipynb
vllyakho/amazon-sagemaker-examples
Calculate AUC for the test data on model 2
# Deploy the model into an instance of your choosing. model_endpoint2 <- tuner2$deploy(initial_instance_count = 1L, instance_type = 'ml.t2.medium')
_____no_output_____
Apache-2.0
r_examples/r_sagemaker_binary_classification_algorithms/R_binary_classification_algorithms_comparison.ipynb
vllyakho/amazon-sagemaker-examples
For inference, the linear learner algorithm supports the application/json, application/x-recordio-protobuf, and text/csv formats. For more information, https://docs.aws.amazon.com/sagemaker/latest/dg/LL-in-formats.html
# Specify what data formats you want the input and output of your model to look like. model_endpoint2$serializer <- sagemaker$serializers$CSVSerializer(content_type='text/csv') model_endpoint2$deserializer <- sagemaker$deserializers$JSONDeserializer()
_____no_output_____
Apache-2.0
r_examples/r_sagemaker_binary_classification_algorithms/R_binary_classification_algorithms_comparison.ipynb
vllyakho/amazon-sagemaker-examples
In Linear Learner the output inference files are in JSON or RecordIO formats. https://docs.aws.amazon.com/sagemaker/latest/dg/LL-in-formats.html When you make predictions on new data, the contents of the response data depends on the type of model you choose within Linear Learner. For regression (predictor_type='regres...
# Prepare the test data for input into the model test_sample <- as.matrix(iris_test[-1]) dimnames(test_sample)[[2]] <- NULL # Predict using the test data on the deployed model predictions_ep <- model_endpoint2$predict(test_sample) # Add the predictions to the test dataset. df <- data.frame(matrix(unlist(predictions_e...
_____no_output_____
Apache-2.0
r_examples/r_sagemaker_binary_classification_algorithms/R_binary_classification_algorithms_comparison.ipynb
vllyakho/amazon-sagemaker-examples
Create model 3: KNN in SageMaker Amazon SageMaker k-nearest neighbors (k-NN) algorithm is an index-based algorithm. It uses a non-parametric method for classification or regression. For classification problems, the algorithm queries the k points that are closest to the sample point and returns the most frequently used...
container <- sagemaker$image_uris$retrieve(framework='knn', region= session$boto_region_name, version='latest') cat('KNN Container Image URL: ', container) s3_output <- paste0('s3://', bucket, '/output_knn') estimator3 <- sagemaker$estimator$Estimator(image_uri = container, ro...
_____no_output_____
Apache-2.0
r_examples/r_sagemaker_binary_classification_algorithms/R_binary_classification_algorithms_comparison.ipynb
vllyakho/amazon-sagemaker-examples
Hyperparameter `dimension_reduction_target` should not be set when `dimension_reduction_type` is set to its default value, which is `None`. If 'dimension_reduction_target' is set to a certain number without setting `dimension_reduction_type`, then SageMaker will ask us to remove 'dimension_reduction_target' from the sp...
estimator3$set_hyperparameters( feature_dim = 4L, sample_size = 10L, predictor_type = "classifier" )
_____no_output_____
Apache-2.0
r_examples/r_sagemaker_binary_classification_algorithms/R_binary_classification_algorithms_comparison.ipynb
vllyakho/amazon-sagemaker-examples
Amazon SageMaker k-nearest neighbor model can be tuned with the following hyperparameters:- k - sample_size
# Set Hyperparameter Ranges hyperparameter_ranges = list('k' = sagemaker$parameter$IntegerParameter(1L,10L) ) # Create a hyperparamter tuner objective_metric_name = 'test:accuracy' tuner3 <- sagemaker$tuner$HyperparameterTuner(estimator3, objectiv...
_____no_output_____
Apache-2.0
r_examples/r_sagemaker_binary_classification_algorithms/R_binary_classification_algorithms_comparison.ipynb
vllyakho/amazon-sagemaker-examples
Calculate AUC for the test data on model 3
# Deploy the model into an instance of your choosing. model_endpoint3 <- tuner3$deploy(initial_instance_count = 1L, instance_type = 'ml.t2.medium')
_____no_output_____
Apache-2.0
r_examples/r_sagemaker_binary_classification_algorithms/R_binary_classification_algorithms_comparison.ipynb
vllyakho/amazon-sagemaker-examples
For inference, the linear learner algorithm supports the application/json, application/x-recordio-protobuf, and text/csv formats. For more information, https://docs.aws.amazon.com/sagemaker/latest/dg/LL-in-formats.html
# Specify what data formats you want the input and output of your model to look like. model_endpoint3$serializer <- sagemaker$serializers$CSVSerializer(content_type='text/csv') model_endpoint3$deserializer <- sagemaker$deserializers$JSONDeserializer()
_____no_output_____
Apache-2.0
r_examples/r_sagemaker_binary_classification_algorithms/R_binary_classification_algorithms_comparison.ipynb
vllyakho/amazon-sagemaker-examples
In KNN, the input formats for inference are:- CSV- JSON- JSONLINES- RECORDIOThe output formats for inference are:- JSON- JSONLINES- Verbose JSON- Verbose RecordIO-ProtoBufNotice that there is no CSV output format for inference. See https://docs.aws.amazon.com/sagemaker/latest/dg/kNN-inference-formats.html for more det...
# Prepare the test data for input into the model test_sample <- as.matrix(iris_test[-1]) dimnames(test_sample)[[2]] <- NULL # Predict using the test data on the deployed model predictions_ep <- model_endpoint3$predict(test_sample)
_____no_output_____
Apache-2.0
r_examples/r_sagemaker_binary_classification_algorithms/R_binary_classification_algorithms_comparison.ipynb
vllyakho/amazon-sagemaker-examples
We see that the output is of a deserialized JSON format.
predictions_ep typeof(predictions_ep) # Add the predictions to the test dataset. df = data.frame(predicted_flower = unlist(predictions_ep$predictions)) iris_predictions_ep2 <- dplyr::bind_cols(predicted_flower = df$predicted_flower, iris_test) iris_predictions_ep2 # Get the AUC auc(roc(iris_pred...
_____no_output_____
Apache-2.0
r_examples/r_sagemaker_binary_classification_algorithms/R_binary_classification_algorithms_comparison.ipynb
vllyakho/amazon-sagemaker-examples
Compare the AUC of 3 models for the test data - AUC of Sagemaker XGBoost = 1 - AUC of Sagemaker Linear Learner = 0.83- AUC of Sagemaker KNN = 1 Based on the AUC metric (the higher the better), both XGBoost and KNN perform equally well and are better than the Linear Learner. We can also explore the 3 models with other ...
model_endpoint1$delete_model() model_endpoint2$delete_model() model_endpoint3$delete_model() session$delete_endpoint(model_endpoint1$endpoint) session$delete_endpoint(model_endpoint2$endpoint) session$delete_endpoint(model_endpoint3$endpoint)
_____no_output_____
Apache-2.0
r_examples/r_sagemaker_binary_classification_algorithms/R_binary_classification_algorithms_comparison.ipynb
vllyakho/amazon-sagemaker-examples
"""SPEECh: Scalable Probabilistic Estimates of EV ChargingCode first published in October 2021.Developed by Siobhan Powell (siobhan.powell@stanford.edu).""" This code produces the data set of driver group profiles that has been posted Siobhan Powell, October 2021
from speech import DataSetConfigurations from speech import SPEECh from speech import SPEEChGeneralConfiguration from speech import Plotting from speech import LoadProfile import os os.chdir('..') import pandas as pd import matplotlib.pyplot as plt import numpy as np total_evs = 10000 weekday_option = 'weekday' # dat...
_____no_output_____
BSD-2-Clause
ProcessingForPaper/7_produce_dataset.ipynb
SiobhanPowell/speech
Testing:
plt.plot(results[5]) test = pd.read_csv('Output_Data/group3_weekday.csv') test2 = pd.read_csv('Output_Data/group3_weekend.csv') plt.plot(test.sum(axis=1), label='weekday') plt.plot(test2.sum(axis=1), label='weekend') plt.legend() plt.show() test = pd.read_csv('Output_Data/group4_weekday.csv') test2 = pd.read_csv('Outpu...
_____no_output_____
BSD-2-Clause
ProcessingForPaper/7_produce_dataset.ipynb
SiobhanPowell/speech
This Notebook - Goals - FOR EDINA**What?:**- Standard classification method example/tutorial**Who?:**- Researchers in ML- Students in computer science- Teachers in ML/STEM**Why?:**- Demonstrate capability/simplicity of core scipy stack. - Demonstrate common ML concept known to learners and used by researchers.**Noteab...
import numpy as np import sklearn.datasets as ds import sklearn.model_selection as ms from sklearn import decomposition from sklearn import neighbors from sklearn import metrics import matplotlib.pyplot as plt %matplotlib inline
_____no_output_____
BSD-3-Clause
GeneralExemplars/MLExemplars/Classification_k_NN_Notebook.ipynb
gaybro8777/Exemplars2020
Data - Handwritten DigitsIn terms of data, [scikit-learn](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html) has a loading function for some data regarding hand written digits.
# get the digits data from scikit into the notebook digits = ds.load_digits()
_____no_output_____
BSD-3-Clause
GeneralExemplars/MLExemplars/Classification_k_NN_Notebook.ipynb
gaybro8777/Exemplars2020
The cell above loads the data as a [bunch object](https://scikit-learn.org/stable/modules/generated/sklearn.datasets.load_digits.html), meaning that the data (in this case images of handwritten digits) and the target (the number that is written) can be split by accessing the attributes of the bunch object:
# store data and targets seperately X = digits.data y = digits.target print("The data is of the shape", X.shape) print("The target data is of the shape", y.shape)
_____no_output_____
BSD-3-Clause
GeneralExemplars/MLExemplars/Classification_k_NN_Notebook.ipynb
gaybro8777/Exemplars2020
The individual samples in the X array each represent an image. In this representation, 64 numbers are used to represent a greyscale value on an 8\*8 square. The images can be examined by using pyplot's [matshow](https://matplotlib.org/3.3.0/api/_as_gen/matplotlib.pyplot.matshow.html) function.The next cell displays the...
# create figure to display the 17th sample fig = plt.matshow(digits.images[17], cmap=plt.cm.gray) fig.axes.get_xaxis().set_visible(False) fig.axes.get_yaxis().set_visible(False)
_____no_output_____
BSD-3-Clause
GeneralExemplars/MLExemplars/Classification_k_NN_Notebook.ipynb
gaybro8777/Exemplars2020
Suppose instead of viewing the 17th sample, we want to see the average of samples corresponding to a certain value.This can be done as follows (using 0 as an example):- All samples where the target value is 0 are located- The mean of these samples is taken- The resulting 64 long array is reshaped to be 8\*8 (for displa...
# take samples with target=0 izeros = np.where(y == 0) # take average across samples, reshape to visualise zeros = np.mean(X[izeros], axis=0).reshape(8,8) # display fig = plt.matshow(zeros, cmap=plt.cm.gray) fig.axes.get_xaxis().set_visible(False) fig.axes.get_yaxis().set_visible(False)
_____no_output_____
BSD-3-Clause
GeneralExemplars/MLExemplars/Classification_k_NN_Notebook.ipynb
gaybro8777/Exemplars2020
Fit and test the model Split the data Now that you have an understanding of the data, the model can be fitted.Fitting the model involves setting some of the data aside for testing, and allowing the model to "see" the target values corresponding to the training samples.Once the model has been fitted to the training dat...
# split data to train and test sets X_train, X_test, y_train, y_test = \ ms.train_test_split(X, y, test_size=0.25, shuffle=True, random_state=22)
_____no_output_____
BSD-3-Clause
GeneralExemplars/MLExemplars/Classification_k_NN_Notebook.ipynb
gaybro8777/Exemplars2020
The data can be examined - here you can see that 1347 samples have been put into the training set, and 450 have been set aside for testing.
# print shape of data print("training samples:", X_train.shape) print("testing samples :", X_test.shape) print("training targets:", y_train.shape) print("testing targets :", y_test.shape)
_____no_output_____
BSD-3-Clause
GeneralExemplars/MLExemplars/Classification_k_NN_Notebook.ipynb
gaybro8777/Exemplars2020
Using PCA to visualise dataBefore diving into classifying, it is useful to visualise the data.Since each sample has 64 dimensions, some dimensionality reduction is needed in order to visualise the samples as points on a 2D map.One of the easiest ways of visualising high dimensional data is by principal component analy...
# create PCA model with 2 components pca = decomposition.PCA(n_components=2)
_____no_output_____
BSD-3-Clause
GeneralExemplars/MLExemplars/Classification_k_NN_Notebook.ipynb
gaybro8777/Exemplars2020
The next step is to perform the PCA on the samples, and store the results.
# transform training data to 2 principal components X_pca = pca.fit_transform(X_train) # transform test data to 2 principal components T_pca = pca.transform(X_test) # check shape of result print(X_pca.shape) print(T_pca.shape)
_____no_output_____
BSD-3-Clause
GeneralExemplars/MLExemplars/Classification_k_NN_Notebook.ipynb
gaybro8777/Exemplars2020
As you can see from the above cell, the X_pca and T_pca data is now represented by only 2 elements per sample. The number of samples has remained the same.Now that there is a 2D representation of the data, it can be plotted on a regular scatter graph. Since the labels corresponding to each point are stored in the y_tra...
# choose the colours for each digit cmap_digits = plt.cm.tab10 # plot training data with labels plt.figure(figsize = (9,6)) plt.scatter(X_pca[:,0], X_pca[:,1], s=7, c=y_train, cmap=cmap_digits, alpha=0.7) plt.title("Training data coloured by target value") plt.colorbar();
_____no_output_____
BSD-3-Clause
GeneralExemplars/MLExemplars/Classification_k_NN_Notebook.ipynb
gaybro8777/Exemplars2020
Create and fit the modelThe scikit-learn library allows fitting of a k-NN model just as with PCA above.First, create the classifier:
# create model knn = neighbors.KNeighborsClassifier()
_____no_output_____
BSD-3-Clause
GeneralExemplars/MLExemplars/Classification_k_NN_Notebook.ipynb
gaybro8777/Exemplars2020
The next step fits the k-NN model using the training data.
# fit model to training data knn.fit(X_train,y_train);
_____no_output_____
BSD-3-Clause
GeneralExemplars/MLExemplars/Classification_k_NN_Notebook.ipynb
gaybro8777/Exemplars2020
Test modelNow use the data that was set aside earlier - this stage involves getting the model to "guess" the samples (this time without seeing their target values).Once the model has predicted the sample's class, a score can be calculated by checking how many samples the model guessed correctly.
# predict test data preds = knn.predict(X_test) # test model on test data score = round(knn.score(X_test,y_test)*100, 2) print("Score on test data: " + str(score) + "%")
_____no_output_____
BSD-3-Clause
GeneralExemplars/MLExemplars/Classification_k_NN_Notebook.ipynb
gaybro8777/Exemplars2020
98.44% is a really high score, one that would not likely be seen on real life applications of the method.It can often be useful to visualise the results of your example. Below are plots showing:- The labels that the model predicted for the test data- The actual labels for the test data- The data points that were incorr...
# plot 3 axes fig, axes = plt.subplots(2,2,figsize=(12,12)) # top left axis for predictions axes[0,0].scatter(T_pca[:,0], T_pca[:,1], s=5, c=preds, cmap=cmap_digits) axes[0,0].set_title("Predicted labels") # top right axis for actual targets axes[0,1].scatter(T_pca[:,0], T_pca[:,1], s=5, ...
_____no_output_____
BSD-3-Clause
GeneralExemplars/MLExemplars/Classification_k_NN_Notebook.ipynb
gaybro8777/Exemplars2020
So which samples did the model get wrong?There were 7 samples that were misclassified. These can be displayed alongside their actual and predicted labels using the cell below:
# find the misclassified samples misclass = np.where(preds!=y_test)[0] # display misclassified samples r, c = 1, len(misclass) fig, axes = plt.subplots(r,c,figsize=(10,5)) for i in range(c): ax = axes[i] ax.matshow(X_test[misclass[i]].reshape(8,8),cmap=plt.cm.gray) ax.set_axis_off() act = y_test[miscl...
_____no_output_____
BSD-3-Clause
GeneralExemplars/MLExemplars/Classification_k_NN_Notebook.ipynb
gaybro8777/Exemplars2020
Additionally, a confusion matrix can be used to identify which samples are misclassified by the model. This can help you identify if their are samples that are commonly misidentified - for example you may identify that 8's are often mistook for 1's.
# confusion matrix conf = metrics.confusion_matrix(y_test,preds) # figure f, ax = plt.subplots(figsize=(9,5)) im = ax.imshow(conf, cmap=plt.cm.RdBu) # set labels as ticks on axes ax.set_xticks(np.arange(10)) ax.set_yticks(np.arange(10)) ax.set_xticklabels(list(range(0,10))) ax.set_yticklabels(list(range(0,10))) ax.se...
_____no_output_____
BSD-3-Clause
GeneralExemplars/MLExemplars/Classification_k_NN_Notebook.ipynb
gaybro8777/Exemplars2020
Dependencies
!nvidia-smi !jupyter notebook list %env CUDA_VISIBLE_DEVICES=3 %matplotlib inline %load_ext autoreload %autoreload 2 import time from pathlib import Path import numpy as np import matplotlib.pyplot as plt import torch import torch.nn as nn import torch.optim as optim import torchvision import torchvision.transforms a...
_____no_output_____
MIT
extract_training_images.ipynb
adriancampos/road-extraction
DatasetDownload the DeepGlobe dataset from https://competitions.codalab.org/competitions/18467. Place it in datasets/deepglobe/dataset/train,test,validDownload the Massachusetts Road Dataset from https://www.cs.toronto.edu/~vmnih/data/. Combine the training, validation, and test sets, process with `crop_dataset.ipynb`...
run = "expM.3.drop2.1" DEEPGLOBE_PATH = Path('datasets/', 'deepglobe/dataset') MAROADS_PATH = Path('datasets/', 'maroads/dataset') RESULTS_PATH = Path('.results/') WEIGHTS_PATH = Path('.weights/') RUNS_PATH = Path('.runs/') RESULTS_PATH.mkdir(exist_ok=True) WEIGHTS_PATH.mkdir(exist_ok=True) RUNS_PATH.mkdir(exist_ok=...
Train: 4909 Val: 1243 Test: 2226 <torch.utils.data.dataloader._SingleProcessDataLoaderIter object at 0x7f387e5c3dd0> Inputs: torch.Size([1, 3, 1024, 1024]) Targets: torch.Size([1, 1024, 1024]) Procssing image 0 Procssing image 10 Procssing image 20 Procssing image 30 Procssing image 40 Procssing image 50 Procssing im...
MIT
extract_training_images.ipynb
adriancampos/road-extraction
Fun with PythonA very minimal example for the Pythia Foundations collection. A Python program can be a single line:
print('Hello interweb')
Hello interweb
Apache-2.0
jb_demo/foundations/Hello.ipynb
halehawk/sphinx-pythia-theme
Inference and ValidationNow that you have a trained network, you can use it for making predictions. This is typically called **inference**, a term borrowed from statistics. However, neural networks have a tendency to perform *too well* on the training data and aren't able to generalize to data that hasn't been seen be...
import torch from torchvision import datasets, transforms # Define a transform to normalize the data transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))]) # Download and load the training data trainset = datasets.FashionMNIST('~/.pytorch/F_MNIST_d...
_____no_output_____
MIT
intro-to-pytorch/Part 5 - Inference and Validation (Exercises).ipynb
rodolfoams/deep-learning-v2-pytorch
Here I'll create a model like normal, using the same one from my solution for part 4.
from torch import nn, optim import torch.nn.functional as F class Classifier(nn.Module): def __init__(self): super().__init__() self.fc1 = nn.Linear(784, 256) self.fc2 = nn.Linear(256, 128) self.fc3 = nn.Linear(128, 64) self.fc4 = nn.Linear(64, 10) def forward(s...
_____no_output_____
MIT
intro-to-pytorch/Part 5 - Inference and Validation (Exercises).ipynb
rodolfoams/deep-learning-v2-pytorch
The goal of validation is to measure the model's performance on data that isn't part of the training set. Performance here is up to the developer to define though. Typically this is just accuracy, the percentage of classes the network predicted correctly. Other options are [precision and recall](https://en.wikipedia.or...
model = Classifier() images, labels = next(iter(testloader)) # Get the class probabilities ps = torch.exp(model(images)) # Make sure the shape is appropriate, we should get 10 class probabilities for 64 examples print(ps.shape)
torch.Size([64, 10])
MIT
intro-to-pytorch/Part 5 - Inference and Validation (Exercises).ipynb
rodolfoams/deep-learning-v2-pytorch
With the probabilities, we can get the most likely class using the `ps.topk` method. This returns the $k$ highest values. Since we just want the most likely class, we can use `ps.topk(1)`. This returns a tuple of the top-$k$ values and the top-$k$ indices. If the highest value is the fifth element, we'll get back 4 as ...
top_p, top_class = ps.topk(1, dim=1) # Look at the most likely classes for the first 10 examples print(top_class[:10,:])
tensor([[4], [4], [4], [4], [4], [4], [4], [4], [4], [4]])
MIT
intro-to-pytorch/Part 5 - Inference and Validation (Exercises).ipynb
rodolfoams/deep-learning-v2-pytorch
Now we can check if the predicted classes match the labels. This is simple to do by equating `top_class` and `labels`, but we have to be careful of the shapes. Here `top_class` is a 2D tensor with shape `(64, 1)` while `labels` is 1D with shape `(64)`. To get the equality to work out the way we want, `top_class` and `l...
equals = top_class == labels.view(*top_class.shape)
_____no_output_____
MIT
intro-to-pytorch/Part 5 - Inference and Validation (Exercises).ipynb
rodolfoams/deep-learning-v2-pytorch
Now we need to calculate the percentage of correct predictions. `equals` has binary values, either 0 or 1. This means that if we just sum up all the values and divide by the number of values, we get the percentage of correct predictions. This is the same operation as taking the mean, so we can get the accuracy with a c...
accuracy = torch.mean(equals.type(torch.FloatTensor)) print(f'Accuracy: {accuracy.item()*100}%')
Accuracy: 9.375%
MIT
intro-to-pytorch/Part 5 - Inference and Validation (Exercises).ipynb
rodolfoams/deep-learning-v2-pytorch
The network is untrained so it's making random guesses and we should see an accuracy around 10%. Now let's train our network and include our validation pass so we can measure how well the network is performing on the test set. Since we're not updating our parameters in the validation pass, we can speed up our code by t...
model = Classifier() criterion = nn.NLLLoss() optimizer = optim.Adam(model.parameters(), lr=0.003) epochs = 30 steps = 0 train_losses, test_losses = [], [] for e in range(epochs): running_loss = 0 for images, labels in trainloader: optimizer.zero_grad() log_ps = model(images)...
_____no_output_____
MIT
intro-to-pytorch/Part 5 - Inference and Validation (Exercises).ipynb
rodolfoams/deep-learning-v2-pytorch
OverfittingIf we look at the training and validation losses as we train the network, we can see a phenomenon known as overfitting.The network learns the training set better and better, resulting in lower training losses. However, it starts having problems generalizing to data outside the training set leading to the va...
## TODO: Define your model with dropout added class MyClassifier(nn.Module): def __init__(self): super().__init__() self.fc1 = nn.Linear(784, 256) self.fc2 = nn.Linear(256, 128) self.fc3 = nn.Linear(128, 64) self.fc4 = nn.Linear(64, 10) self.dropout = nn.Dropout(p=0.2...
Accuracy: 75.0% Accuracy: 90.625% Accuracy: 75.0% Accuracy: 78.125% Accuracy: 85.9375% Accuracy: 81.25% Accuracy: 73.4375% Accuracy: 75.0% Accuracy: 79.6875% Accuracy: 87.5% Accuracy: 82.8125% Accuracy: 79.6875% Accuracy: 90.625% Accuracy: 79.6875% Accuracy: 81.25% Accuracy: 75.0% Accuracy: 84.375% Accuracy: 81.25% Acc...
MIT
intro-to-pytorch/Part 5 - Inference and Validation (Exercises).ipynb
rodolfoams/deep-learning-v2-pytorch
InferenceNow that the model is trained, we can use it for inference. We've done this before, but now we need to remember to set the model in inference mode with `model.eval()`. You'll also want to turn off autograd with the `torch.no_grad()` context.
# Import helper module (should be in the repo) import helper # Test out your network! model.eval() dataiter = iter(testloader) images, labels = dataiter.next() img = images[0] # Convert 2D image to 1D vector img = img.view(1, 784) # Calculate the class probabilities (softmax) for img with torch.no_grad(): outpu...
_____no_output_____
MIT
intro-to-pytorch/Part 5 - Inference and Validation (Exercises).ipynb
rodolfoams/deep-learning-v2-pytorch
SoundPlayer Usage InstructionsThe `SoundPlayer` class plays sounds contained within the Sounds directory in the project. Sounds can be played simmply by initializing the class and calling the available methods.The sounds that are available to play are located in the folder `Sounds/`. Files of type .mp3 and .wav are ...
from SoundPlayer import SoundPlayer player = SoundPlayer() player.list_sounds()
_____no_output_____
MIT
salemPi/SoundPlayerDocs.ipynb
kburgon/salem-candy-dispenser
Playing a SoundA sound can be played by calling the method `SoundPlayer.play(sound)`, where sound is the string name of the sound that will be played.
sound = player.list_sounds()[0] player.play(sound)
playing name wlaugh.mp3
MIT
salemPi/SoundPlayerDocs.ipynb
kburgon/salem-candy-dispenser
Rotating Through SoundsWhen the method `SoundPlayer.play_rotated_sound()` is called, a different sound within the Sounds folder will be played each time.
for i in range(len(player.list_sounds())): player.play_rotated_sound()
playing name wlaugh.mp3 playing name hag_idle.mp3 playing name ghosts03.mp3
MIT
salemPi/SoundPlayerDocs.ipynb
kburgon/salem-candy-dispenser
Scale-Out Data Preparation Once we are done with preparing and featurizing the data locally, we can run the same steps on the full dataset in scale-out mode. The new york taxi cab data is about 300GB in total, which is perfect for scale-out. Let's start by downloading the package we saved earlier to disk. Feel free to...
from tempfile import mkdtemp from os import path from urllib.request import urlretrieve dflow_root = mkdtemp() dflow_path = path.join(dflow_root, "new_york_taxi.dprep") print("Downloading Dataflow to: {}".format(dflow_path)) urlretrieve("https://dprepdata.blob.core.windows.net/demo/new_york_taxi_v2.dprep", dflow_path)
_____no_output_____
MIT
case-studies/new-york-taxi/new-york-taxi_scale-out.ipynb
Bhaskers-Blu-Org2/AMLDataPrepDocs
Let's load the package we just downloaded.
import azureml.dataprep as dprep df = dprep.Dataflow.open(dflow_path)
_____no_output_____
MIT
case-studies/new-york-taxi/new-york-taxi_scale-out.ipynb
Bhaskers-Blu-Org2/AMLDataPrepDocs
Let's replace the datasources with the full dataset.
from uuid import uuid4 other_step = df._get_steps()[7].arguments['dataflows'][0]['anonymousSteps'][0] other_step['id'] = str(uuid4()) other_step['arguments']['path']['target'] = 1 other_step['arguments']['path']['resourceDetails'][0]['path'] = 'https://wranglewestus.blob.core.windows.net/nyctaxi/yellow_tripdata*' gree...
_____no_output_____
MIT
case-studies/new-york-taxi/new-york-taxi_scale-out.ipynb
Bhaskers-Blu-Org2/AMLDataPrepDocs
Once we have replaced the datasource, we can now run the same steps on the full dataset. We will print the first 5 rows of the spark DataFrame. Since we are running on the full dataset, this might take a little while depending on your spark cluster's size.
spark_df = df.to_spark_dataframe() spark_df.head(5)
_____no_output_____
MIT
case-studies/new-york-taxi/new-york-taxi_scale-out.ipynb
Bhaskers-Blu-Org2/AMLDataPrepDocs
Regular ExpressionsRegular expressions are text-matching patterns described with a formal syntax. You'll often hear regular expressions referred to as 'regex' or 'regexp' in conversation. Regular expressions can include a variety of rules, from finding repetition, to text-matching, and much more. As you advance in Pyt...
import re # List of patterns to search for patterns = ['term1', 'term2'] # Text to parse text = 'This is a string with term1, but it does not have the other term.' for pattern in patterns: print('Searching for "%s" in:\n "%s"\n' %(pattern,text)) #Check for match if re.search(pattern,text): p...
Searching for "term1" in: "This is a string with term1, but it does not have the other term." Match was found. Searching for "term2" in: "This is a string with term1, but it does not have the other term." No Match was found.
MIT
13-Advanced Python Modules/05-Regular Expressions - re.ipynb
Pankaj-Ra/Complete-Python3-Bootcamp-master
Now we've seen that re.search() will take the pattern, scan the text, and then return a **Match** object. If no pattern is found, **None** is returned. To give a clearer picture of this match object, check out the cell below:
# List of patterns to search for pattern = 'term1' # Text to parse text = 'This is a string with term1, but it does not have the other term.' match = re.search(pattern,text) type(match)
_____no_output_____
MIT
13-Advanced Python Modules/05-Regular Expressions - re.ipynb
Pankaj-Ra/Complete-Python3-Bootcamp-master
This **Match** object returned by the search() method is more than just a Boolean or None, it contains information about the match, including the original input string, the regular expression that was used, and the location of the match. Let's see the methods we can use on the match object:
# Show start of match match.start() # Show end match.end()
_____no_output_____
MIT
13-Advanced Python Modules/05-Regular Expressions - re.ipynb
Pankaj-Ra/Complete-Python3-Bootcamp-master
Split with regular expressionsLet's see how we can split with the re syntax. This should look similar to how you used the split() method with strings.
# Term to split on split_term = '@' phrase = 'What is the domain name of someone with the email: hello@gmail.com' # Split the phrase re.split(split_term,phrase)
_____no_output_____
MIT
13-Advanced Python Modules/05-Regular Expressions - re.ipynb
Pankaj-Ra/Complete-Python3-Bootcamp-master
Note how re.split() returns a list with the term to split on removed and the terms in the list are a split up version of the string. Create a couple of more examples for yourself to make sure you understand! Finding all instances of a patternYou can use re.findall() to find all the instances of a pattern in a string. F...
# Returns a list of all matches re.findall('match','test phrase match is in middle')
_____no_output_____
MIT
13-Advanced Python Modules/05-Regular Expressions - re.ipynb
Pankaj-Ra/Complete-Python3-Bootcamp-master
re Pattern SyntaxThis will be the bulk of this lecture on using re with Python. Regular expressions support a huge variety of patterns beyond just simply finding where a single string occurred. We can use *metacharacters* along with re to find specific types of patterns. Since we will be testing multiple re syntax for...
def multi_re_find(patterns,phrase): ''' Takes in a list of regex patterns Prints a list of all matches ''' for pattern in patterns: print('Searching the phrase using the re check: %r' %(pattern)) print(re.findall(pattern,phrase)) print('\n')
_____no_output_____
MIT
13-Advanced Python Modules/05-Regular Expressions - re.ipynb
Pankaj-Ra/Complete-Python3-Bootcamp-master
Repetition SyntaxThere are five ways to express repetition in a pattern: 1. A pattern followed by the meta-character * is repeated zero or more times. 2. Replace the * with + and the pattern must appear at least once. 3. Using ? means the pattern appears zero or one time. 4. For a specific number of occurre...
test_phrase = 'sdsd..sssddd...sdddsddd...dsds...dsssss...sdddd' test_patterns = [ 'sd*', # s followed by zero or more d's 'sd+', # s followed by one or more d's 'sd?', # s followed by zero or one d's 'sd{3}', # s followed by three d's ...
Searching the phrase using the re check: 'sd*' ['sd', 'sd', 's', 's', 'sddd', 'sddd', 'sddd', 'sd', 's', 's', 's', 's', 's', 's', 'sdddd'] Searching the phrase using the re check: 'sd+' ['sd', 'sd', 'sddd', 'sddd', 'sddd', 'sd', 'sdddd'] Searching the phrase using the re check: 'sd?' ['sd', 'sd', 's', 's', 'sd', 's...
MIT
13-Advanced Python Modules/05-Regular Expressions - re.ipynb
Pankaj-Ra/Complete-Python3-Bootcamp-master
Character SetsCharacter sets are used when you wish to match any one of a group of characters at a point in the input. Brackets are used to construct character set inputs. For example: the input [ab] searches for occurrences of either **a** or **b**.Let's see some examples:
test_phrase = 'sdsd..sssddd...sdddsddd...dsds...dsssss...sdddd' test_patterns = ['[sd]', # either s or d 's[sd]+'] # s followed by one or more s or d multi_re_find(test_patterns,test_phrase)
Searching the phrase using the re check: '[sd]' ['s', 'd', 's', 'd', 's', 's', 's', 'd', 'd', 'd', 's', 'd', 'd', 'd', 's', 'd', 'd', 'd', 'd', 's', 'd', 's', 'd', 's', 's', 's', 's', 's', 's', 'd', 'd', 'd', 'd'] Searching the phrase using the re check: 's[sd]+' ['sdsd', 'sssddd', 'sdddsddd', 'sds', 'sssss', 'sdddd'...
MIT
13-Advanced Python Modules/05-Regular Expressions - re.ipynb
Pankaj-Ra/Complete-Python3-Bootcamp-master
It makes sense that the first input [sd] returns every instance of s or d. Also, the second input s[sd]+ returns any full strings that begin with an s and continue with s or d characters until another character is reached. ExclusionWe can use ^ to exclude terms by incorporating it into the bracket syntax notation. For...
test_phrase = 'This is a string! But it has punctuation. How can we remove it?'
_____no_output_____
MIT
13-Advanced Python Modules/05-Regular Expressions - re.ipynb
Pankaj-Ra/Complete-Python3-Bootcamp-master
Use [^!.? ] to check for matches that are not a !,.,?, or space. Add a + to check that the match appears at least once. This basically translates into finding the words.
re.findall('[^!.? ]+',test_phrase)
_____no_output_____
MIT
13-Advanced Python Modules/05-Regular Expressions - re.ipynb
Pankaj-Ra/Complete-Python3-Bootcamp-master
Character RangesAs character sets grow larger, typing every character that should (or should not) match could become very tedious. A more compact format using character ranges lets you define a character set to include all of the contiguous characters between a start and stop point. The format used is [start-end].Comm...
test_phrase = 'This is an example sentence. Lets see if we can find some letters.' test_patterns=['[a-z]+', # sequences of lower case letters '[A-Z]+', # sequences of upper case letters '[a-zA-Z]+', # sequences of lower or upper case letters '[A-Z][a-z]+'] # on...
Searching the phrase using the re check: '[a-z]+' ['his', 'is', 'an', 'example', 'sentence', 'ets', 'see', 'if', 'we', 'can', 'find', 'some', 'letters'] Searching the phrase using the re check: '[A-Z]+' ['T', 'L'] Searching the phrase using the re check: '[a-zA-Z]+' ['This', 'is', 'an', 'example', 'sentence', 'Lets...
MIT
13-Advanced Python Modules/05-Regular Expressions - re.ipynb
Pankaj-Ra/Complete-Python3-Bootcamp-master
Escape CodesYou can use special escape codes to find specific types of patterns in your data, such as digits, non-digits, whitespace, and more. For example:CodeMeaning\da digit\Da non-digit\swhitespace (tab, space, newline, etc.)\Snon-whitespace\walphanumeric\Wnon-alphanumericEscapes are indicated by prefixing the cha...
test_phrase = 'This is a string with some numbers 1233 and a symbol #hashtag' test_patterns=[ r'\d+', # sequence of digits r'\D+', # sequence of non-digits r'\s+', # sequence of whitespace r'\S+', # sequence of non-whitespace r'\w+', # alphanumeric charac...
Searching the phrase using the re check: '\\d+' ['1233'] Searching the phrase using the re check: '\\D+' ['This is a string with some numbers ', ' and a symbol #hashtag'] Searching the phrase using the re check: '\\s+' [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '] Searching the phrase using the re check...
MIT
13-Advanced Python Modules/05-Regular Expressions - re.ipynb
Pankaj-Ra/Complete-Python3-Bootcamp-master
Minimum Absolute Difference in an Array![image](https://user-images.githubusercontent.com/50367487/83008403-0e8a6480-a050-11ea-8973-4b41088e6e7e.png)
#!/bin/python3 import math import os import random import re import sys # Complete the minimumAbsoluteDifference function below. def minimumAbsoluteDifference(arr): arr.sort(reverse=True) Min = arr[0] - arr[1] for i in range(1, n - 1): Min = min(Min, arr[i] - arr[i + 1]) return Min if __name_...
_____no_output_____
MIT
Interview Preparation Kit/6. Greedy Algorithms/Minimum Absolute Difference in an Array.ipynb
Nam-SH/HackerRank
Feature selection using SelectFromModel and LassoCVUse SelectFromModel meta-transformer along with Lasso to select the bestcouple of features from the Boston dataset.
# Author: Manoj Kumar <mks542@nyu.edu> # License: BSD 3 clause print(__doc__) import matplotlib.pyplot as plt import numpy as np from sklearn.datasets import load_boston from sklearn.feature_selection import SelectFromModel from sklearn.linear_model import LassoCV import pandas as pd # Load the boston dataset. # bo...
Automatically created module for IPython interactive environment
CC-BY-3.0
Assignments/hw3/Failed_to_perform_with_dataset/HW3_feature_selection_from_Boston/plot_select_from_model_boston.ipynb
Leon23N/Leon23N.github.io
Lambda School Data Science*Unit 4, Sprint 3, Module 2*--- Convolutional Neural Networks (Prepare)> Convolutional networks are simply neural networks that use convolution in place of general matrix multiplication in at least one of their layers. *Goodfellow, et al.* Learning Objectives- Part 1: Describe convolution an...
from IPython.display import YouTubeVideo YouTubeVideo('MPU2HistivI', width=600, height=400)
_____no_output_____
MIT
module2-convolutional-neural-networks/LS_DS_432_Convolutional_Neural_Networks_Lecture.ipynb
SamH3pn3r/DS-Unit-4-Sprint-3-Deep-Learning
Convolution & Pooling (Learn) OverviewLike neural networks themselves, CNNs are inspired by biology - specifically, the receptive fields of the visual cortex.Put roughly, in a real brain the neurons in the visual cortex *specialize* to be receptive to certain regions, shapes, colors, orientations, and other common vi...
from IPython.display import YouTubeVideo YouTubeVideo('IOHayh06LJ4', width=600, height=400)
_____no_output_____
MIT
module2-convolutional-neural-networks/LS_DS_432_Convolutional_Neural_Networks_Lecture.ipynb
SamH3pn3r/DS-Unit-4-Sprint-3-Deep-Learning
Follow AlongLet's try to do some convolutions in `Keras`. Convolution - an exampleConsider blurring an image - assume the image is represented as a matrix of numbers, where each number corresponds to the color value of a pixel.
import imageio import matplotlib.pyplot as plt from skimage import color, io from skimage.exposure import rescale_intensity austen = io.imread('https://dl.airtable.com/S1InFmIhQBypHBL0BICi_austen.jpg') austen_grayscale = rescale_intensity(color.rgb2gray(austen)) austen_grayscale plt.imshow(austen_grayscale, cmap="gray...
_____no_output_____
MIT
module2-convolutional-neural-networks/LS_DS_432_Convolutional_Neural_Networks_Lecture.ipynb
SamH3pn3r/DS-Unit-4-Sprint-3-Deep-Learning
ChallengeYou will be expected to be able to describe convolution. CNNs for Classification (Learn) Overview Typical CNN Architecture![A Typical CNN](https://upload.wikimedia.org/wikipedia/commons/thumb/6/63/Typical_cnn.png/800px-Typical_cnn.png)The first stage of a CNN is, unsurprisingly, a convolution - specifical...
from tensorflow.keras import datasets from tensorflow.keras.models import Sequential, Model # <- May Use from tensorflow.keras.layers import Dense, Conv2D, MaxPooling2D, Flatten import matplotlib.pyplot as plt (train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data() # Normalize pixel val...
- 25s - loss: 0.9412 - acc: 0.7020
MIT
module2-convolutional-neural-networks/LS_DS_432_Convolutional_Neural_Networks_Lecture.ipynb
SamH3pn3r/DS-Unit-4-Sprint-3-Deep-Learning
ChallengeYou will apply CNNs to a classification task in the module project. CNNs for Object Detection (Learn) Overview Transfer Learning - TensorFlow Hub"A library for reusable machine learning modules"This lets you quickly take advantage of a model that was trained with thousands of GPU hours. It also enables tra...
import numpy as np from tensorflow.keras.applications.resnet50 import ResNet50 from tensorflow.keras.preprocessing import image from tensorflow.keras.applications.resnet50 import preprocess_input, decode_predictions def process_img_path(img_path): return image.load_img(img_path, target_size=(224, 224)) def img_con...
[('n07753592', 'banana', 0.06643853), ('n03532672', 'hook', 0.06110267), ('n03498962', 'hatchet', 0.05880436)]
MIT
module2-convolutional-neural-networks/LS_DS_432_Convolutional_Neural_Networks_Lecture.ipynb
SamH3pn3r/DS-Unit-4-Sprint-3-Deep-Learning
Trump Charges
# https://www.metaculus.com/questions/6222/criminal-charges-against-trump/ trump_charges = compare_metaculus_vs_polymarket('https://polymarket.com/market/donald-trump-federally-charged-by-february-20th', 6222, actual=0) trum...
_____no_output_____
MIT
Metaculus vs. Polymarket.ipynb
rethinkpriorities/compare_forecast_markets
GOP Win
# https://www.metaculus.com/questions/5734/gop-to-hold-senate-on-feb-1st-2021/ gop_senate = compare_metaculus_vs_polymarket('https://polymarket.com/market/which-party-will-control-the-senate', 5734, actual=0) gop_senate['data'] go...
_____no_output_____
MIT
Metaculus vs. Polymarket.ipynb
rethinkpriorities/compare_forecast_markets
Trump Pardon
# https://www.metaculus.com/questions/5685/will-donald-trump-attempt-to-pardon-himself/ trump_pardon = compare_metaculus_vs_polymarket('https://polymarket.com/market/will-trump-pardon-himself-in-his-first-term', 5685, actual=0...
_____no_output_____
MIT
Metaculus vs. Polymarket.ipynb
rethinkpriorities/compare_forecast_markets
538 - Economist
# https://www.metaculus.com/questions/5503/comparing-538-and-economist-forecasts-in-2020/ economist_538 = compare_metaculus_vs_polymarket('https://polymarket.com/market/will-538-outperform-the-economist-in-forecasting-the-2020-presidential-election', 5503, ...
_____no_output_____
MIT
Metaculus vs. Polymarket.ipynb
rethinkpriorities/compare_forecast_markets
Biden in-person inauguration
## https://www.metaculus.com/questions/6293/biden-in-person-inauguration/ biden_in_person = compare_metaculus_vs_polymarket('https://polymarket.com/market/will-joe-biden-be-officially-inaugurated-as-president-in-person-outside-the-us-capitol-on-january-20th-2021', 6293,...
_____no_output_____
MIT
Metaculus vs. Polymarket.ipynb
rethinkpriorities/compare_forecast_markets
Trump at Biden's Inauguration
## https://www.metaculus.com/questions/5825/trump-at-bidens-inauguration/ trump_attend = compare_metaculus_vs_polymarket('https://polymarket.com/market/will-donald-trump-attend-joe-biden-s-inauguration-ceremony-in-person', 5825, ...
_____no_output_____
MIT
Metaculus vs. Polymarket.ipynb
rethinkpriorities/compare_forecast_markets
Electoral Challenge
## https://www.metaculus.com/questions/5844/electoral-college-results-challenged/ challenge = compare_metaculus_vs_polymarket('https://polymarket.com/market/will-any-electoral-certificates-be-formally-challenged-in-congress', 5844, ...
_____no_output_____
MIT
Metaculus vs. Polymarket.ipynb
rethinkpriorities/compare_forecast_markets
Trump Convict
## https://www.metaculus.com/questions/6303/trump-convicted-by-senate/ trump_convict = compare_metaculus_vs_polymarket('https://polymarket.com/market/will-the-senate-convict-donald-trump-on-impeachment-before-june-1-2021', 6303, ...
_____no_output_____
MIT
Metaculus vs. Polymarket.ipynb
rethinkpriorities/compare_forecast_markets
Tokyo Olympics
# https://polymarket.com/market/will-the-tokyo-summer-olympics-be-cancelled-or-postponed # https://www.metaculus.com/questions/5555/rescheduled-2020-olympics/
_____no_output_____
MIT
Metaculus vs. Polymarket.ipynb
rethinkpriorities/compare_forecast_markets
Brier
(challenge['brier'] + trump_attend['brier'] + biden_in_person['brier'] + economist_538['brier'] + trump_pardon['brier'] + gop_senate['brier'] + trump_charges['brier'] + trump_convict['brier']) / 8 (challenge['winnings'] + trump_attend['winnings'] + biden_in_person['winnings'] + economist_538['winnings'] + trump_pardon[...
_____no_output_____
MIT
Metaculus vs. Polymarket.ipynb
rethinkpriorities/compare_forecast_markets
Training a ConvNet PyTorchIn this notebook, you'll learn how to use the powerful PyTorch framework to specify a conv net architecture and train it on the CIFAR-10 dataset.
import torch import torch.nn as nn import torch.optim as optim from torch.autograd import Variable from torch.utils.data import DataLoader from torch.utils.data import sampler import torchvision.datasets as dset import torchvision.transforms as T import numpy as np import matplotlib.pyplot as plt import timeit from ...
_____no_output_____
MIT
assignment2/PyTorch.ipynb
aoboturov/cs237n-17
What's this PyTorch business?You've written a lot of code in this assignment to provide a whole host of neural network functionality. Dropout, Batch Norm, and 2D convolutions are some of the workhorses of deep learning in computer vision. You've also worked hard to make your code efficient and vectorized.For the last ...
class ChunkSampler(sampler.Sampler): """Samples elements sequentially from some offset. Arguments: num_samples: # of desired datapoints start: offset where we should start selecting from """ def __init__(self, num_samples, start = 0): self.num_samples = num_samples self....
Files already downloaded and verified Files already downloaded and verified Files already downloaded and verified
MIT
assignment2/PyTorch.ipynb
aoboturov/cs237n-17
For now, we're going to use a CPU-friendly datatype. Later, we'll switch to a datatype that will move all our computations to the GPU and measure the speedup.
# Constant to control how frequently we print train loss print_every = 100 # This is a little utility that we'll use to reset the model # if we want to re-initialize all our parameters def reset(m): if hasattr(m, 'reset_parameters'): m.reset_parameters()
_____no_output_____
MIT
assignment2/PyTorch.ipynb
aoboturov/cs237n-17
Example Model Some assorted tidbitsLet's start by looking at a simple model. First, note that PyTorch operates on Tensors, which are n-dimensional arrays functionally analogous to numpy's ndarrays, with the additional feature that they can be used for computations on GPUs.We'll provide you with a Flatten function, whi...
class Flatten(nn.Module): def forward(self, x): N, C, H, W = x.size() # read in N, C, H, W return x.view(N, -1) # "flatten" the C * H * W values into a single vector per image def out_dim(sz, filter_size, padding, stride): """ Computes the size of dimension after convolution. Input: ...
_____no_output_____
MIT
assignment2/PyTorch.ipynb
aoboturov/cs237n-17
The example model itselfThe first step to training your own model is defining its architecture.Here's an example of a convolutional neural network defined in PyTorch -- try to understand what each line is doing, remembering that each layer is composed upon the previous layer. We haven't trained anything yet - that'll ...
# Here's where we define the architecture of the model... simple_model = nn.Sequential( nn.Conv2d(3, 32, kernel_size=7, stride=2), nn.ReLU(inplace=True), Flatten(), # see above for explanation nn.Linear(5408, 10), # affine layer ) # the numb...
_____no_output_____
MIT
assignment2/PyTorch.ipynb
aoboturov/cs237n-17
PyTorch supports many other layer types, loss functions, and optimizers - you will experiment with these next. Here's the official API documentation for these (if any of the parameters used above were unclear, this resource will also be helpful). One note: what we call in the class "spatial batch norm" is called "Batch...
n_Conv2d = out_dim(32, 7, 0, 1) n_MaxPool2d = out_dim(n_Conv2d, 2, 0, 2) n_Flatten = 32*n_MaxPool2d**2 fixed_model_base = nn.Sequential( # You fill this in! nn.Conv2d(3, 32, kernel_size=7, stride=1), nn.ReLU(inplace=True), nn.BatchNorm2d(32), nn.MaxPool2d...
_____no_output_____
MIT
assignment2/PyTorch.ipynb
aoboturov/cs237n-17
To make sure you're doing the right thing, use the following tool to check the dimensionality of your output (it should be 64 x 10, since our batches have size 64 and the output of the final affine layer should be 10, corresponding to our 10 classes):
## Now we're going to feed a random batch into the model you defined and make sure the output is the right size x = torch.randn(64, 3, 32, 32).type(dtype) x_var = Variable(x.type(dtype)) # Construct a PyTorch Variable out of your input data ans = fixed_model(x_var) # Feed it through the model! # Check to make ...
_____no_output_____
MIT
assignment2/PyTorch.ipynb
aoboturov/cs237n-17
GPU!Now, we're going to switch the dtype of the model and our data to the GPU-friendly tensors, and see what happens... everything is the same, except we are casting our model and input tensors as this new dtype instead of the old one.If this returns false, or otherwise fails in a not-graceful way (i.e., with some err...
import copy fixed_model_gpu = copy.deepcopy(fixed_model_base).type(dtype) x_gpu = torch.randn(64, 3, 32, 32).type(dtype) x_var_gpu = Variable(x.type(dtype)) # Construct a PyTorch Variable out of your input data ans = fixed_model_gpu(x_var_gpu) # Feed it through the model! # Check to make sure what comes out ...
_____no_output_____
MIT
assignment2/PyTorch.ipynb
aoboturov/cs237n-17
Run the following cell to evaluate the performance of the forward pass running on the CPU:
%%timeit ans = fixed_model(x_var)
1000 loops, best of 3: 445 µs per loop
MIT
assignment2/PyTorch.ipynb
aoboturov/cs237n-17
... and now the GPU:
%%timeit # torch.cuda.synchronize() # Make sure there are no pending GPU computations ans = fixed_model_gpu(x_var_gpu) # Feed it through the model! # torch.cuda.synchronize() # Make sure there are no pending GPU computations
1000 loops, best of 3: 448 µs per loop
MIT
assignment2/PyTorch.ipynb
aoboturov/cs237n-17
You should observe that even a simple forward pass like this is significantly faster on the GPU. So for the rest of the assignment (and when you go train your models in assignment 3 and your project!), you should use the GPU datatype for your model and your tensors: as a reminder that is *torch.cuda.FloatTensor* (in ou...
loss_fn = nn.CrossEntropyLoss() optimizer = optim.RMSprop(fixed_model_gpu.parameters(), lr=1e-3) # This sets the model in "training" mode. This is relevant for some layers that may have different behavior # in training mode vs testing mode, such as Dropout and BatchNorm. fixed_model_gpu.train() # Load one batch at a...
26%|██▌ | 198/766 [00:01<00:05, 105.99it/s]
MIT
assignment2/PyTorch.ipynb
aoboturov/cs237n-17
Now you've seen how the training process works in PyTorch. To save you writing boilerplate code, we're providing the following helper functions to help you train for multiple epochs and check the accuracy of your model:
def train(model, loss_fn, optimizer, num_epochs = 1, verbose = True): for epoch in range(num_epochs): if verbose: print('Starting epoch %d / %d' % (epoch + 1, num_epochs)) model.train() for t, (x, y) in enumerate(loader_train): x_var = Variable(x.type(dtype)) ...
_____no_output_____
MIT
assignment2/PyTorch.ipynb
aoboturov/cs237n-17
Check the accuracy of the model.Let's see the train and check_accuracy code in action -- feel free to use these methods when evaluating the models you develop below.You should get a training loss of around 1.2-1.4, and a validation accuracy of around 50-60%. As mentioned above, if you re-run the cells, you'll be train...
fixed_model_gpu.apply(reset) train(fixed_model_gpu, loss_fn, optimizer, num_epochs=5) check_accuracy(fixed_model_gpu, loader_val)
Starting epoch 1 / 5 t = 100, loss = 1.3351 t = 200, loss = 1.4855 t = 300, loss = 1.4892 t = 400, loss = 1.2383 t = 500, loss = 1.2223 t = 600, loss = 1.3844 t = 700, loss = 1.1986 Starting epoch 2 / 5 t = 100, loss = 0.9178 t = 200, loss = 0.9722 t = 300, loss = 1.0708 t = 400, loss = 0.8852 t = 500, loss = 0.9199 t ...
MIT
assignment2/PyTorch.ipynb
aoboturov/cs237n-17