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 |
|---|---|---|---|---|---|
use SQL to select cars with 8-cylinder engines - directly from database | dbGetQuery(conn = db, "select * from results where cyl=8") | _____no_output_____ | Apache-2.0 | lessons/misc/sql-intro/r-sql.ipynb | UAAppComp/studyGroup |
Feature selection methods  download-unzip data | !wget https://archive.ics.uci.edu/ml/machine-learning-databases/00320/student.zip
!unzip student.zip | _____no_output_____ | MIT | feature_selection/data_mining_hw3.ipynb | cccaaannn/machine_learning_colab |
imports | import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from scipy.stats import stats | _____no_output_____ | MIT | feature_selection/data_mining_hw3.ipynb | cccaaannn/machine_learning_colab |
load data | df = pd.read_csv("student-mat.csv", index_col=0, delimiter = ";") | _____no_output_____ | MIT | feature_selection/data_mining_hw3.ipynb | cccaaannn/machine_learning_colab |
print head | df.head(5) | _____no_output_____ | MIT | feature_selection/data_mining_hw3.ipynb | cccaaannn/machine_learning_colab |
Options | p_value_threshold = 0.05 | _____no_output_____ | MIT | feature_selection/data_mining_hw3.ipynb | cccaaannn/machine_learning_colab |
Pearson | num_cols = df.drop(["G3","G2","G1"], axis=1)._get_numeric_data().columns
pearson_corrs = []
for col in num_cols:
s = stats.pearsonr(df[col], df['G3'])
if(s[1] < p_value_threshold):
pearson_corrs.append((col, s[0], s[1]))
pearson_corrs = sorted(pearson_corrs, reverse=True, key=lambda tup: abs(tup[1]))
... | _____no_output_____ | MIT | feature_selection/data_mining_hw3.ipynb | cccaaannn/machine_learning_colab |
Spearman | num_cols = df.drop(["G3","G2","G1"], axis=1)._get_numeric_data().columns
spearmar_corrs = []
for col in num_cols:
s = stats.spearmanr(df[col], df['G3'])
if(s[1] < p_value_threshold):
spearmar_corrs.append((col, s[0], s[1]))
spearmar_corrs = sorted(spearmar_corrs, reverse=True, key=lambda tup: abs(tup[1... | _____no_output_____ | MIT | feature_selection/data_mining_hw3.ipynb | cccaaannn/machine_learning_colab |
Kendall | num_cols = df.drop(["G3","G2","G1"], axis=1)._get_numeric_data().columns
kendall_corrs = []
for col in num_cols:
s = stats.kendalltau(df[col], df['G3'])
if(s[1] < p_value_threshold):
kendall_corrs.append((col, s[0], s[1]))
kendall_corrs = sorted(kendall_corrs, reverse=True, key=lambda tup: abs(... | _____no_output_____ | MIT | feature_selection/data_mining_hw3.ipynb | cccaaannn/machine_learning_colab |
f-value | cols = df.columns
num_cols = df._get_numeric_data().columns
categorical_cols = list(set(cols) - set(num_cols))
f_value_corrs = []
for categorical_col in categorical_cols:
groups = []
column_categories = df[categorical_col].unique()
for column_category in column_categories:
groups.append(df[df[cate... | _____no_output_____ | MIT | feature_selection/data_mining_hw3.ipynb | cccaaannn/machine_learning_colab |
加载数据集 | def state(message,start = True, time = 0):
if(start):
print(f'Working on {message} ... ')
else :
print(f'Working on {message} took ({round(time , 3)}) Sec \n')
# Import dataset
df_train = pd.read_csv('../input/train_V2.csv')
df_test = pd.read_csv('../input/test_V2.csv')
# Reduce memory use
df_t... | Memory usage of dataframe is 983.90 MB --> 339.28 MB (Decreased by 65.5%)
Memory usage of dataframe is 413.18 MB --> 140.19 MB (Decreased by 66.1%)
| MIT | code/.ipynb_checkpoints/Predict-checkpoint.ipynb | Jexers/PUBG-Finish-Placement-Prediction-Proj |
对数据进行简单清洗 | # 由于百分比是按照本局的最差名次来计算的,而不是小队的数量,并且本局最差名次与小队数量存在冗余,因此删除
# 由于最远击杀距离统计并不准确 rankPoints官方建议谨慎使用,因此删除
df_train = df_train.drop(['longestKill', 'numGroups', 'rankPoints'], axis=1)
df_test = df_test.drop(['longestKill', 'numGroups', 'rankPoints'], axis=1)
# 删除缺失值
df_train[df_train['winPlacePerc'].isnull()]
df_train.drop(274460... | _____no_output_____ | MIT | code/.ipynb_checkpoints/Predict-checkpoint.ipynb | Jexers/PUBG-Finish-Placement-Prediction-Proj |
特征工程 | def feature_engineering(df,is_train=True):
if is_train:
df = df[df['maxPlace'] > 1]
state('totalDistance')
s = timer()
df['totalDistance'] = df['rideDistance'] + df["walkDistance"] + df["swimDistance"]
e = timer()
state('totalDistance', False, e - s)
state('killPlace_ove... | Working on totalDistance ...
Working on totalDistance took (0.019) Sec
Working on killPlace_over_maxPlace ...
Working on killPlace_over_maxPlace took (0.032) Sec
Working on healsandboosts ...
Working on healsandboosts took (0.009) Sec
get group mean feature
get group median feature
get group max feature
get gr... | MIT | code/.ipynb_checkpoints/Predict-checkpoint.ipynb | Jexers/PUBG-Finish-Placement-Prediction-Proj |
建立模型 | # 将数据集划分为训练集和验证集
random_seed=1
x_train, x_val, y_train, y_val = train_test_split(x_train, y_train, test_size = 0.05, random_state=random_seed) | _____no_output_____ | MIT | code/.ipynb_checkpoints/Predict-checkpoint.ipynb | Jexers/PUBG-Finish-Placement-Prediction-Proj |
Random Forest | RF = RandomForestRegressor(n_estimators=10, min_samples_leaf=3, max_features=0.5, n_jobs=-1)
%%time
RF.fit(x_train, y_train)
mae_train_RF = mean_absolute_error(RF.predict(x_train), y_train)
mae_val_RF = mean_absolute_error(RF.predict(x_val), y_val)
print('mae train RF: ', mae_train_RF)
print('mae val RF: ', mae_val_RF) | mae train RF: 0.015503626984996665
mae val RF: 0.032972121527289365
| MIT | code/.ipynb_checkpoints/Predict-checkpoint.ipynb | Jexers/PUBG-Finish-Placement-Prediction-Proj |
LightGBM | def run_lgb(train_X, train_y, val_X, val_y, x_test):
params = {"objective" : "regression",
"metric" : "mae",
'n_estimators':20000,
'early_stopping_rounds':200,
"num_leaves" : 31,
"learning_rate" : 0.05,
"bagging_fraction" : 0.7... | mae train lgb: 0.022016762514129016
mae val lgb: 0.0270388973536143
| MIT | code/.ipynb_checkpoints/Predict-checkpoint.ipynb | Jexers/PUBG-Finish-Placement-Prediction-Proj |
DNN | def run_DNN(x_train, y_train, x_val, y_val, x_test):
NN_model = Sequential()
NN_model.add(Dense(x_train.shape[1], input_dim = x_train.shape[1], activation='relu'))
NN_model.add(Dense(136, activation='relu'))
NN_model.add(Dense(136, activation='relu'))
NN_model.add(Dense(136, activation='relu'))
... | mae train dnn: 0.04090054122667123
mae val dnn: 0.040935060316103625
| MIT | code/.ipynb_checkpoints/Predict-checkpoint.ipynb | Jexers/PUBG-Finish-Placement-Prediction-Proj |
使用训练好的模型进行预测 Random Forest | pred_test_RF = RF.predict(x_test)
df_test['winPlacePerc_RF'] = pred_test_RF
submission = df_test[['Id', 'winPlacePerc_RF']]
submission.to_csv('../output/submission_RF.csv', index=False) | _____no_output_____ | MIT | code/.ipynb_checkpoints/Predict-checkpoint.ipynb | Jexers/PUBG-Finish-Placement-Prediction-Proj |
LightGBM | df_test['winPlacePerc_lgb'] = pred_test_lgb
submission = df_test[['Id', 'winPlacePerc_lgb']]
submission.to_csv('../output/submission_lgb.csv', index=False) | _____no_output_____ | MIT | code/.ipynb_checkpoints/Predict-checkpoint.ipynb | Jexers/PUBG-Finish-Placement-Prediction-Proj |
DNN | df_test['winPlacePerc_DNN'] = pred_test_DNN
submission = df_test[['Id', 'winPlacePerc_DNN']]
submission.to_csv('../output/submission_DNN.csv', index=False) | _____no_output_____ | MIT | code/.ipynb_checkpoints/Predict-checkpoint.ipynb | Jexers/PUBG-Finish-Placement-Prediction-Proj |
根据验证集上的MAE值为模型划分权重进行集成(RF + DNN + LightGBM) | weight_DNN = (1 - mae_val_DNN) / (3 - mae_val_DNN - mae_val_RF - mae_val_lgb)
weight_RF = (1 - mae_val_RF) / (3 - mae_val_DNN - mae_val_RF - mae_val_lgb)
weight_lgb = (1 - mae_val_lgb) / (3 - mae_val_DNN - mae_val_RF - mae_val_lgb)
df_test['winPlacePerc'] = df_test.apply(lambda x: x['winPlacePerc_RF'] * weight_RF + x[... | _____no_output_____ | MIT | code/.ipynb_checkpoints/Predict-checkpoint.ipynb | Jexers/PUBG-Finish-Placement-Prediction-Proj |
Class DiagramsThis is a simple viewer for class diagrams. Customized towards the book. **Prerequisites*** _Refer to earlier chapters as notebooks here, as here:_ [Earlier Chapter](Debugger.ipynb). | import bookutils | _____no_output_____ | MIT | docs/notebooks/ClassDiagram.ipynb | bjrnmath/debuggingbook |
SynopsisTo [use the code provided in this chapter](Importing.ipynb), write```python>>> from debuggingbook.ClassDiagram import ```and then make use of the following features.The function `display_class_hierarchy()` function shows the class hierarchy for the given class (or list of classes). * The keyword parameter `pub... | import inspect | _____no_output_____ | MIT | docs/notebooks/ClassDiagram.ipynb | bjrnmath/debuggingbook |
Using `mro()`, we can access the class hierarchy. We make sure to avoid duplicates created by `class X(X)`. | # ignore
from typing import Callable, Dict, Type, Set, List, Union, Any, Tuple, Optional
def class_hierarchy(cls: Type) -> List[Type]:
superclasses = cls.mro()
hierarchy = []
last_superclass_name = ""
for superclass in superclasses:
if superclass.__name__ != last_superclass_name:
hi... | _____no_output_____ | MIT | docs/notebooks/ClassDiagram.ipynb | bjrnmath/debuggingbook |
Here's an example: | class A_Class:
"""A Class which does A thing right.
Comes with a longer docstring."""
def foo(self) -> None:
"""The Adventures of the glorious Foo"""
pass
def quux(self) -> None:
"""A method that is not used."""
pass
class A_Class(A_Class):
# We define another funct... | _____no_output_____ | MIT | docs/notebooks/ClassDiagram.ipynb | bjrnmath/debuggingbook |
Getting a Class Tree We can use `__bases__` to obtain the immediate base classes. | D_Class.__bases__ | _____no_output_____ | MIT | docs/notebooks/ClassDiagram.ipynb | bjrnmath/debuggingbook |
`class_tree()` returns a class tree, using the "lowest" (most specialized) class with the same name. | def class_tree(cls: Type, lowest: Type = None) -> List[Tuple[Type, List]]:
ret = []
for base in cls.__bases__:
if base.__name__ == cls.__name__:
if not lowest:
lowest = cls
ret += class_tree(base, lowest)
else:
if lowest:
cls = ... | _____no_output_____ | MIT | docs/notebooks/ClassDiagram.ipynb | bjrnmath/debuggingbook |
`class_set()` flattens the tree into a set: | def class_set(classes: Union[Type, List[Type]]) -> Set[Type]:
if not isinstance(classes, list):
classes = [classes]
ret = set()
def traverse_tree(tree: List[Tuple[Type, List]]) -> None:
for (cls, subtrees) in tree:
ret.add(cls)
for subtree in subtrees:
... | _____no_output_____ | MIT | docs/notebooks/ClassDiagram.ipynb | bjrnmath/debuggingbook |
Getting Docs | A_Class.__doc__
A_Class.__bases__[0].__doc__
A_Class.__bases__[0].__name__
D_Class.foo
D_Class.foo.__doc__
A_Class.foo.__doc__
def docstring(obj: Any) -> str:
doc = inspect.getdoc(obj)
return doc if doc else ""
docstring(A_Class)
docstring(D_Class.foo)
def unknown() -> None:
pass
docstring(unknown)
import h... | 'Hello
{You|Me}'
| MIT | docs/notebooks/ClassDiagram.ipynb | bjrnmath/debuggingbook |
Getting Methods and Variables | inspect.getmembers(D_Class)
def class_items(cls: Type, pred: Callable) -> List[Tuple[str, Any]]:
def _class_items(cls: Type) -> List:
all_items = inspect.getmembers(cls, pred)
for base in cls.__bases__:
all_items += _class_items(base)
return all_items
unique_items = []
... | _____no_output_____ | MIT | docs/notebooks/ClassDiagram.ipynb | bjrnmath/debuggingbook |
We're only interested in * functions _defined_ in that class* functions that come with a docstring | def public_class_methods(cls: Type) -> List[Tuple[str, Callable]]:
return [(name, method) for (name, method) in class_methods(cls)
if method.__qualname__.startswith(cls.__name__)]
def doc_class_methods(cls: Type) -> List[Tuple[str, Callable]]:
return [(name, method) for (name, method) in public_cla... | _____no_output_____ | MIT | docs/notebooks/ClassDiagram.ipynb | bjrnmath/debuggingbook |
Drawing Class Hierarchy with Method Names | from inspect import signature
import warnings
def display_class_hierarchy(classes: Union[Type, List[Type]],
public_methods: Optional[List] = None,
abstract_classes: Optional[List] = None,
include_methods: bool = True,
... | _____no_output_____ | MIT | docs/notebooks/ClassDiagram.ipynb | bjrnmath/debuggingbook |
Here is a variant with abstract classes and logging: | display_class_hierarchy([A_Class, B_Class],
abstract_classes=[A_Class],
public_methods=[
A_Class.quux,
], log=True) | Drawing class A_Class
Drawing quux()
Drawing foo()
Drawing second()
Drawing class B_Class
Drawing VAR
Drawing bar()
Drawing foo()
| MIT | docs/notebooks/ClassDiagram.ipynb | bjrnmath/debuggingbook |
Synopsis The function `display_class_hierarchy()` function shows the class hierarchy for the given class (or list of classes). * The keyword parameter `public_methods`, if given, is a list of "public" methods to be used by clients (default: all methods with docstrings).* The keyword parameter `abstract_classes`, if gi... | display_class_hierarchy(D_Class, abstract_classes=[A_Class]) | _____no_output_____ | MIT | docs/notebooks/ClassDiagram.ipynb | bjrnmath/debuggingbook |
Bayesian GAN Bayesian GAN (Saatchi and Wilson, 2017) is a Bayesian formulation of Generative Adversarial Networks (Goodfellow, 2014) where we learn the **distributions** of the generator parameters $\theta_g$ and the discriminator parameters $\theta_d$ instead of optimizing for point estimates. The benefits of the Bay... | from IPython.display import HTML
HTML('<iframe width="1000" height="400" src="https://chi-feng.github.io/mcmc-demo/app.html#HamiltonianMC,banana" frameborder="0" allowfullscreen></iframe>') | _____no_output_____ | MIT | mltrain-nips-2017/ben_athiwaratkun/pytorch-bayesgan/Bayesian GAN in PyTorch.ipynb | gopala-kr/ds-notebooks |
Hamiltonian Monte Carlo allows us to learn arbitrary distributions, including multimodal distributions where other Bayesian approach such as variational inference cannot model. | HTML('<iframe width="1000" height="400" src="https://chi-feng.github.io/mcmc-demo/app.html#HamiltonianMC,multimodal" frameborder="0" allowfullscreen></iframe>') | _____no_output_____ | MIT | mltrain-nips-2017/ben_athiwaratkun/pytorch-bayesgan/Bayesian GAN in PyTorch.ipynb | gopala-kr/ds-notebooks |
TrainingWe show that Bayesian GAN can capture the data distribution by measuring its performance in the semi-supervised setting. We will perform the posterior update as outline in Algorithm 1 in Saatchi (2017). This algorithm can be implemented quite simply by adding noise to standard optimizers such as SGD with momen... | !pip install tensorboard_logger
from __future__ import print_function
import os, pickle
import numpy as np
import random, math
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim as optim
import torch.utils.data
import torchvision.datasets as dset
import t... | _____no_output_____ | MIT | mltrain-nips-2017/ben_athiwaratkun/pytorch-bayesgan/Bayesian GAN in PyTorch.ipynb | gopala-kr/ds-notebooks |
The results show that the Bayesian discriminator trained with the Bayesian generator outperforms the discriminator trained on partial data. | %matplotlib inline
p = ggplot(df, aes(x='Iteration', y='Accuracy', color='Classification', label='Classification')) + geom_point(size=0.5)
print(p) | _____no_output_____ | MIT | mltrain-nips-2017/ben_athiwaratkun/pytorch-bayesgan/Bayesian GAN in PyTorch.ipynb | gopala-kr/ds-notebooks |
Electronic Health Record (EHR) Incentive Program Payments for Eligible Providers Data Cleaninghttps://data.chhs.ca.gov/dataset/electronic-health-record-ehr-incentive-program-payments-for-eligible-providers3 | import pandas as pd
import numpy as np
ehr_data = pd.read_csv("Electronic_Health_Record_Program_Payments.csv")
ehr_data.head()
ehr_data.tail()
ehr_data.info()
print("Exploratory Data Analysis")
print("Electronic Health Record Data")
print('-'*40)
print("Dataset information")
print(ehr_data.info(memory_usage='deep',ver... | _____no_output_____ | MIT | California_Medicaid_Eligibility/Electronic_Health_Record_Program_Payments_Data_Cleaning.ipynb | LastAncientOne/Kaggle-Project |
Creating a Sentiment Analysis Web App Using PyTorch and SageMaker_Deep Learning Nanodegree Program | Deployment_---Now that we have a basic understanding of how SageMaker works we will try to use it to construct a complete project from end to end. Our goal will be to have a simple web page which a user can use to ente... | %mkdir ../data
!wget -O ../data/aclImdb_v1.tar.gz http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz
!tar -zxf ../data/aclImdb_v1.tar.gz -C ../data | mkdir: cannot create directory ‘../data’: File exists
--2020-07-01 11:14:49-- http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz
Resolving ai.stanford.edu (ai.stanford.edu)... 171.64.68.10
Connecting to ai.stanford.edu (ai.stanford.edu)|171.64.68.10|:80... connected.
HTTP request sent, awaiting response...... | MIT | Project/SageMaker Project.ipynb | JasperEssien2/SagemakerDeployment |
Step 2: Preparing and Processing the dataAlso, as in the XGBoost notebook, we will be doing some initial data processing. The first few steps are the same as in the XGBoost example. To begin with, we will read in each of the reviews and combine them into a single input structure. Then, we will split the dataset into a... | import os
import glob
def read_imdb_data(data_dir='../data/aclImdb'):
data = {}
labels = {}
for data_type in ['train', 'test']:
data[data_type] = {}
labels[data_type] = {}
for sentiment in ['pos', 'neg']:
data[data_type][sentiment] = []
labels[d... | IMDB reviews: train = 12500 pos / 12500 neg, test = 12500 pos / 12500 neg
| MIT | Project/SageMaker Project.ipynb | JasperEssien2/SagemakerDeployment |
Now that we've read the raw training and testing data from the downloaded dataset, we will combine the positive and negative reviews and shuffle the resulting records. | from sklearn.utils import shuffle
def prepare_imdb_data(data, labels):
"""Prepare training and test sets from IMDb movie reviews."""
#Combine positive and negative reviews and labels
data_train = data['train']['pos'] + data['train']['neg']
data_test = data['test']['pos'] + data['test']['neg']
... | IMDb reviews (combined): train = 25000, test = 25000
| MIT | Project/SageMaker Project.ipynb | JasperEssien2/SagemakerDeployment |
Now that we have our training and testing sets unified and prepared, we should do a quick check and see an example of the data our model will be trained on. This is generally a good idea as it allows you to see how each of the further processing steps affects the reviews and it also ensures that the data has been loade... | print(train_X[100])
print(train_y[100]) | Upon The Straight Story release in 1999, it was praised for being David Lynch's first film that ignored his regular themes of the macabre and the surreal. Based on a true story of one man and his journey to visit his estranged brother on a John Deere '66 mower, at first glance its an odd story for Lynch to direct. Yet ... | MIT | Project/SageMaker Project.ipynb | JasperEssien2/SagemakerDeployment |
The first step in processing the reviews is to make sure that any html tags that appear should be removed. In addition we wish to tokenize our input, that way words such as *entertained* and *entertaining* are considered the same with regard to sentiment analysis. | import nltk
from nltk.corpus import stopwords
from nltk.stem.porter import *
import re
from bs4 import BeautifulSoup
def review_to_words(review):
nltk.download("stopwords", quiet=True)
stemmer = PorterStemmer()
text = BeautifulSoup(review, "html.parser").get_text() # Remove HTML tags
text = re.su... | _____no_output_____ | MIT | Project/SageMaker Project.ipynb | JasperEssien2/SagemakerDeployment |
The `review_to_words` method defined above uses `BeautifulSoup` to remove any html tags that appear and uses the `nltk` package to tokenize the reviews. As a check to ensure we know how everything is working, try applying `review_to_words` to one of the reviews in the training set. | # TODO: Apply review_to_words to a review (train_X[100] or any other review)
review = review_to_words(train_X[100])
print(review) | ['upon', 'straight', 'stori', 'releas', '1999', 'prais', 'david', 'lynch', 'first', 'film', 'ignor', 'regular', 'theme', 'macabr', 'surreal', 'base', 'true', 'stori', 'one', 'man', 'journey', 'visit', 'estrang', 'brother', 'john', 'deer', '66', 'mower', 'first', 'glanc', 'odd', 'stori', 'lynch', 'direct', 'yet', 'stori... | MIT | Project/SageMaker Project.ipynb | JasperEssien2/SagemakerDeployment |
**Question:** Above we mentioned that `review_to_words` method removes html formatting and allows us to tokenize the words found in a review, for example, converting *entertained* and *entertaining* into *entertain* so that they are treated as though they are the same word. What else, if anything, does this method do t... | import pickle
cache_dir = os.path.join("../cache", "sentiment_analysis") # where to store cache files
os.makedirs(cache_dir, exist_ok=True) # ensure cache directory exists
def preprocess_data(data_train, data_test, labels_train, labels_test,
cache_dir=cache_dir, cache_file="preprocessed_data.pkl... | Read preprocessed data from cache file: preprocessed_data.pkl
| MIT | Project/SageMaker Project.ipynb | JasperEssien2/SagemakerDeployment |
Transform the dataIn the XGBoost notebook we transformed the data from its word representation to a bag-of-words feature representation. For the model we are going to construct in this notebook we will construct a feature representation which is very similar. To start, we will represent each word as an integer. Of cou... | import numpy as np
from collections import Counter
def build_dict(data, vocab_size = 5000):
"""Construct and return a dictionary mapping each of the most frequently appearing words to a unique integer."""
# TODO: Determine how often each word appears in `data`. Note that `data` is a list of sentences and ... | _____no_output_____ | MIT | Project/SageMaker Project.ipynb | JasperEssien2/SagemakerDeployment |
**Question:** What are the five most frequently appearing (tokenized) words in the training set? Does it makes sense that these words appear frequently in the training set? **Answer:**The most frequently appearing words are:['movi', 'film', 'one', 'like', 'time']and it makes sense that this words appear frequently beca... | # TODO: Use this space to determine the five most frequently appearing words in the training set.
print(list(word_dict)[0:5])
# print() | ['movi', 'film', 'one', 'like', 'time']
| MIT | Project/SageMaker Project.ipynb | JasperEssien2/SagemakerDeployment |
Save `word_dict`Later on when we construct an endpoint which processes a submitted review we will need to make use of the `word_dict` which we have created. As such, we will save it to a file now for future use. | data_dir = '../data/pytorch' # The folder we will use for storing data
if not os.path.exists(data_dir): # Make sure that the folder exists
os.makedirs(data_dir)
with open(os.path.join(data_dir, 'word_dict.pkl'), "wb") as f:
pickle.dump(word_dict, f) | _____no_output_____ | MIT | Project/SageMaker Project.ipynb | JasperEssien2/SagemakerDeployment |
Transform the reviewsNow that we have our word dictionary which allows us to transform the words appearing in the reviews into integers, it is time to make use of it and convert our reviews to their integer sequence representation, making sure to pad or truncate to a fixed length, which in our case is `500`. | def convert_and_pad(word_dict, sentence, pad=500):
NOWORD = 0 # We will use 0 to represent the 'no word' category
INFREQ = 1 # and we use 1 to represent the infrequent words, i.e., words not appearing in word_dict
working_sentence = [NOWORD] * pad
for word_index, word in enumerate(sentence[:pa... | _____no_output_____ | MIT | Project/SageMaker Project.ipynb | JasperEssien2/SagemakerDeployment |
As a quick check to make sure that things are working as intended, check to see what one of the reviews in the training set looks like after having been processeed. Does this look reasonable? What is the length of a review in the training set? | # Use this cell to examine one of the processed reviews to make sure everything is working as intended.
print(len(train_X[10]))
print(test_X_len[12]) | 500
26
| MIT | Project/SageMaker Project.ipynb | JasperEssien2/SagemakerDeployment |
**Question:** In the cells above we use the `preprocess_data` and `convert_and_pad_data` methods to process both the training and testing set. Why or why not might this be a problem? **Answer:**Why this might be a problem is, some sentences length are way less than 500, so we are just populating the rest of words with ... | import pandas as pd
pd.concat([pd.DataFrame(train_y), pd.DataFrame(train_X_len), pd.DataFrame(train_X)], axis=1) \
.to_csv(os.path.join(data_dir, 'train.csv'), header=False, index=False) | _____no_output_____ | MIT | Project/SageMaker Project.ipynb | JasperEssien2/SagemakerDeployment |
Uploading the training dataNext, we need to upload the training data to the SageMaker default S3 bucket so that we can provide access to it while training our model. | import sagemaker
sagemaker_session = sagemaker.Session()
bucket = sagemaker_session.default_bucket()
prefix = 'sagemaker/sentiment_rnn'
role = sagemaker.get_execution_role()
input_data = sagemaker_session.upload_data(path=data_dir, bucket=bucket, key_prefix=prefix) | _____no_output_____ | MIT | Project/SageMaker Project.ipynb | JasperEssien2/SagemakerDeployment |
**NOTE:** The cell above uploads the entire contents of our data directory. This includes the `word_dict.pkl` file. This is fortunate as we will need this later on when we create an endpoint that accepts an arbitrary review. For now, we will just take note of the fact that it resides in the data directory (and so also ... | !pygmentize train/model.py | [34mimport[39;49;00m [04m[36mtorch[39;49;00m[04m[36m.[39;49;00m[04m[36mnn[39;49;00m [34mas[39;49;00m [04m[36mnn[39;49;00m
[34mclass[39;49;00m [04m[32mLSTMClassifier[39;49;00m(nn.Module):
[33m"""[39;49;00m
[33m This is the simple RNN model we will be using to perform Sentiment Analysi... | MIT | Project/SageMaker Project.ipynb | JasperEssien2/SagemakerDeployment |
The important takeaway from the implementation provided is that there are three parameters that we may wish to tweak to improve the performance of our model. These are the embedding dimension, the hidden dimension and the size of the vocabulary. We will likely want to make these parameters configurable in the training ... | import torch
import torch.utils.data
# Read in only the first 250 rows
train_sample = pd.read_csv(os.path.join(data_dir, 'train.csv'), header=None, names=None, nrows=250)
# Turn the input pandas dataframe into tensors
train_sample_y = torch.from_numpy(train_sample[[0]].values).float().squeeze()
train_sample_X = torch... | _____no_output_____ | MIT | Project/SageMaker Project.ipynb | JasperEssien2/SagemakerDeployment |
(TODO) Writing the training methodNext we need to write the training code itself. This should be very similar to training methods that you have written before to train PyTorch models. We will leave any difficult aspects such as model saving / loading and parameter loading until a little later. | def train(model, train_loader, epochs, optimizer, loss_fn, device):
for epoch in range(1, epochs + 1):
model.train()
total_loss = 0
for batch in train_loader:
batch_X, batch_y = batch
batch_X = batch_X.to(device)
batch_y = batch_y.to(... | _____no_output_____ | MIT | Project/SageMaker Project.ipynb | JasperEssien2/SagemakerDeployment |
Supposing we have the training method above, we will test that it is working by writing a bit of code in the notebook that executes our training method on the small sample training set that we loaded earlier. The reason for doing this in the notebook is so that we have an opportunity to fix any errors that arise early ... | import torch.optim as optim
from train.model import LSTMClassifier
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = LSTMClassifier(32, 100, 5000).to(device)
optimizer = optim.Adam(model.parameters())
loss_fn = torch.nn.BCELoss()
train(model, train_sample_dl, 5, optimizer, loss_fn, device) | Epoch: 1, BCELoss: 0.6959220886230468
Epoch: 2, BCELoss: 0.6813374280929565
Epoch: 3, BCELoss: 0.6672957181930542
Epoch: 4, BCELoss: 0.6517896890640259
Epoch: 5, BCELoss: 0.6320561170578003
| MIT | Project/SageMaker Project.ipynb | JasperEssien2/SagemakerDeployment |
In order to construct a PyTorch model using SageMaker we must provide SageMaker with a training script. We may optionally include a directory which will be copied to the container and from which our training code will be run. When the training container is executed it will check the uploaded directory (if there is one)... | from sagemaker.pytorch import PyTorch
estimator = PyTorch(entry_point="train.py",
source_dir="train",
role=role,
framework_version='0.4.0',
train_instance_count=1,
train_instance_type='ml.p2.xlarge',
# ... | 'create_image_uri' will be deprecated in favor of 'ImageURIProvider' class in SageMaker Python SDK v2.
's3_input' class will be renamed to 'TrainingInput' in SageMaker Python SDK v2.
'create_image_uri' will be deprecated in favor of 'ImageURIProvider' class in SageMaker Python SDK v2.
| MIT | Project/SageMaker Project.ipynb | JasperEssien2/SagemakerDeployment |
Step 5: Testing the modelAs mentioned at the top of this notebook, we will be testing this model by first deploying it and then sending the testing data to the deployed endpoint. We will do this so that we can make sure that the deployed model is working correctly. Step 6: Deploy the model for testingNow that we have ... | # TODO: Deploy the trained model
predictor = estimator.deploy(initial_instance_count=1,
instance_type='ml.m4.xlarge')
# from sagemaker.pytorch import PyTorch
# my_training_job_name = 'sagemaker-pytorch-2020-06-29-22-56-57-261'
# estimator = PyTorch.attach(my_training_job_name)
# estima... | _____no_output_____ | MIT | Project/SageMaker Project.ipynb | JasperEssien2/SagemakerDeployment |
Step 7 - Use the model for testingOnce deployed, we can read in the test data and send it off to our deployed model to get some results. Once we collect all of the results we can determine how accurate our model is. | test_X = pd.concat([pd.DataFrame(test_X_len), pd.DataFrame(test_X)], axis=1)
# We split the data into chunks and send each chunk seperately, accumulating the results.
def predict(data, rows=512):
split_array = np.array_split(data, int(data.shape[0] / float(rows) + 1))
predictions = np.array([])
for array i... | _____no_output_____ | MIT | Project/SageMaker Project.ipynb | JasperEssien2/SagemakerDeployment |
**Question:** How does this model compare to the XGBoost model you created earlier? Why might these two models perform differently on this dataset? Which do *you* think is better for sentiment analysis? **Answer:**The XGBoost model performs more great than the custom model, custom model has an accuracy of 0.7728, but t... | test_review = 'The simplest pleasures in life are the best, and this film is one of them. Combining a rather basic storyline of love and adventure this movie transcends the usual weekend fair with wit and unmitigated charm.' | _____no_output_____ | MIT | Project/SageMaker Project.ipynb | JasperEssien2/SagemakerDeployment |
The question we now need to answer is, how do we send this review to our model?Recall in the first section of this notebook we did a bunch of data processing to the IMDb dataset. In particular, we did two specific things to the provided reviews. - Removed any html tags and stemmed the input - Encoded the review as a se... | # TODO: Convert test_review into a form usable by the model and save the results in test_data
sentences, length = convert_and_pad(word_dict, review_to_words(test_review))
test_data = [0]
test_data[0] = np.append(np.array(length),np.array(sentences)) | _____no_output_____ | MIT | Project/SageMaker Project.ipynb | JasperEssien2/SagemakerDeployment |
Now that we have processed the review, we can send the resulting array to our model to predict the sentiment of the review. | predictor.predict(test_data) | _____no_output_____ | MIT | Project/SageMaker Project.ipynb | JasperEssien2/SagemakerDeployment |
Since the return value of our model is close to `1`, we can be certain that the review we submitted is positive. Delete the endpointOf course, just like in the XGBoost notebook, once we've deployed an endpoint it continues to run until we tell it to shut down. Since we are done using our endpoint for now, we can delet... | estimator.delete_endpoint() | _____no_output_____ | MIT | Project/SageMaker Project.ipynb | JasperEssien2/SagemakerDeployment |
Step 6 (again) - Deploy the model for the web appNow that we know that our model is working, it's time to create some custom inference code so that we can send the model a review which has not been processed and have it determine the sentiment of the review.As we saw above, by default the estimator which we created, w... | !pygmentize serve/predict.py | [34mimport[39;49;00m [04m[36margparse[39;49;00m
[34mimport[39;49;00m [04m[36mjson[39;49;00m
[34mimport[39;49;00m [04m[36mos[39;49;00m
[34mimport[39;49;00m [04m[36mpickle[39;49;00m
[34mimport[39;49;00m [04m[36msys[39;49;00m
[34mimport[39;49;00m [04m[36msagemaker_containers[39;49;00m
[34mim... | MIT | Project/SageMaker Project.ipynb | JasperEssien2/SagemakerDeployment |
As mentioned earlier, the `model_fn` method is the same as the one provided in the training code and the `input_fn` and `output_fn` methods are very simple and your task will be to complete the `predict_fn` method. Make sure that you save the completed file as `predict.py` in the `serve` directory.**TODO**: Complete th... | from sagemaker.predictor import RealTimePredictor
from sagemaker.pytorch import PyTorchModel
from sagemaker.pytorch import PyTorch
my_training_job_name = 'sagemaker-pytorch-2020-07-01-07-19-11-965'
estimator = PyTorch.attach(my_training_job_name)
class StringPredictor(RealTimePredictor):
def __init__(self, endp... | Parameter image will be renamed to image_uri in SageMaker Python SDK v2.
| MIT | Project/SageMaker Project.ipynb | JasperEssien2/SagemakerDeployment |
Testing the modelNow that we have deployed our model with the custom inference code, we should test to see if everything is working. Here we test our model by loading the first `250` positive and negative reviews and send them to the endpoint, then collect the results. The reason for only sending some of the data is t... | import glob
def test_reviews(data_dir='../data/aclImdb', stop=250):
results = []
ground = []
# We make sure to test both positive and negative reviews
for sentiment in ['pos', 'neg']:
path = os.path.join(data_dir, 'test', sentiment, '*.txt')
files = glob.glob(path... | _____no_output_____ | MIT | Project/SageMaker Project.ipynb | JasperEssien2/SagemakerDeployment |
As an additional test, we can try sending the `test_review` that we looked at earlier. | test_review = "a very very bad review"
predictor.predict(test_review) | _____no_output_____ | MIT | Project/SageMaker Project.ipynb | JasperEssien2/SagemakerDeployment |
Now that we know our endpoint is working as expected, we can set up the web page that will interact with it. If you don't have time to finish the project now, make sure to skip down to the end of this notebook and shut down your endpoint. You can deploy it again when you come back. Step 7 (again): Use the model for th... | predictor.endpoint | _____no_output_____ | MIT | Project/SageMaker Project.ipynb | JasperEssien2/SagemakerDeployment |
Once you have added the endpoint name to the Lambda function, click on **Save**. Your Lambda function is now up and running. Next we need to create a way for our web app to execute the Lambda function. Setting up API GatewayNow that our Lambda function is set up, it is time to create a new API using API Gateway that wi... | predictor.delete_endpoint() | _____no_output_____ | MIT | Project/SageMaker Project.ipynb | JasperEssien2/SagemakerDeployment |
FiLM Structures | from project.film_model import FiLMNetwork, ConcatNetwork
bar = ConcatNetwork(978, 513)
bar.hparams
bar.inputs_emb.out_sz + bar.conds_emb.out_sz | _____no_output_____ | Apache-2.0 | notebooks/2020.09.30_models.ipynb | wconnell/film-gex |
Gaussian discriminant analysis con stessa matrice di covarianza per le distribuzioni delle due classi e conseguente separatore lineare. Implementata in scikit-learn. Valutazione con cross validation. | import warnings
warnings.filterwarnings('ignore')
%matplotlib inline
import pandas as pd
import numpy as np
import scipy.stats as st
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.model_selection import cross_val_score
import sklearn.metrics as mt
import matplotlib.pyplot as plt
impo... | _____no_output_____ | MIT | codici/gda-lin-sk-cv.ipynb | tvml/ml2122 |
Leggiamo i dati da un file csv in un dataframe pandas. I dati hanno 3 valori: i primi due corrispondono alle features e sono assegnati alle colonne x1 e x2 del dataframe; il terzo è il valore target, assegnato alla colonna t. Vengono poi creati una matrice X delle features e un vettore target t | # legge i dati in dataframe pandas
data = pd.read_csv("../../data/ex2data1.txt", header= None,delimiter=',', names=['x1','x2','t'])
# calcola dimensione dei dati
n = len(data)
n0 = len(data[data.t==0])
# calcola dimensionalità delle features
features = data.columns
nfeatures = len(features)-1
X = np.array(data[featu... | _____no_output_____ | MIT | codici/gda-lin-sk-cv.ipynb | tvml/ml2122 |
Visualizza il dataset. | fig = plt.figure(figsize=(16,8))
ax = fig.gca()
ax.scatter(data[data.t==0].x1, data[data.t==0].x2, s=40, color=colors[0], alpha=.7)
ax.scatter(data[data.t==1].x1, data[data.t==1].x2, s=40,c=colors[1], alpha=.7)
plt.xlabel('$x_1$', fontsize=12)
plt.ylabel('$x_2$', fontsize=12)
plt.xticks(fontsize=10)
plt.yticks(fontsize... | _____no_output_____ | MIT | codici/gda-lin-sk-cv.ipynb | tvml/ml2122 |
Definisce un classificatore basato su GDA quadratica ed effettua il training sul dataset. | clf = LinearDiscriminantAnalysis(store_covariance=True)
clf.fit(X, t) | _____no_output_____ | MIT | codici/gda-lin-sk-cv.ipynb | tvml/ml2122 |
Definiamo la griglia 100x100 da utilizzare per la visualizzazione delle varie distribuzioni. | # insieme delle ascisse dei punti
u = np.linspace(min(X[:,0]), max(X[:,0]), 100)
# insieme delle ordinate dei punti
v = np.linspace(min(X[:,1]), max(X[:,1]), 100)
# deriva i punti della griglia: il punto in posizione i,j nella griglia ha ascissa U(i,j) e ordinata V(i,j)
U, V = np.meshgrid(u, v) | _____no_output_____ | MIT | codici/gda-lin-sk-cv.ipynb | tvml/ml2122 |
Calcola sui punti della griglia le probabilità delle classi $p(x|C_0), p(x|C_1)$ e le probabilità a posteriori delle classi $p(C_0|x), p(C_1|x)$ | # probabilità a posteriori delle due distribuzioni sulla griglia
Z = clf.predict_proba(np.c_[U.ravel(), V.ravel()])
pp0 = Z[:, 0].reshape(U.shape)
pp1 = Z[:, 1].reshape(V.shape)
# rapporto tra le probabilità a posteriori delle classi per tutti i punti della griglia
z=pp0/pp1
# probabilità per le due classi sulla gr... | _____no_output_____ | MIT | codici/gda-lin-sk-cv.ipynb | tvml/ml2122 |
Visualizzazione della distribuzione di $p(x|C_0)$ | fig = plt.figure(figsize=(16,8))
ax = fig.gca()
# inserisce una rappresentazione della probabilità della classe C0 sotto forma di heatmap
imshow_handle = plt.imshow(p0, origin='lower', extent=(min(X[:,0]), max(X[:,0]), min(X[:,1]), max(X[:,1])), alpha=.7)
plt.contour(U, V, p0, linewidths=[.7], colors=[colors[6]])
# rap... | _____no_output_____ | MIT | codici/gda-lin-sk-cv.ipynb | tvml/ml2122 |
Visualizzazione della distribuzione di $p(x|C1)$ | fig = plt.figure(figsize=(16,8))
ax = fig.gca()
# inserisce una rappresentazione della probabilità della classe C0 sotto forma di heatmap
imshow_handle = plt.imshow(p1, origin='lower', extent=(min(X[:,0]), max(X[:,0]), min(X[:,1]), max(X[:,1])), alpha=.7)
plt.contour(U, V, p1, linewidths=[.7], colors=[colors[6]])
# rap... | _____no_output_____ | MIT | codici/gda-lin-sk-cv.ipynb | tvml/ml2122 |
Visualizzazione di $p(C_0|x)$ | fig = plt.figure(figsize=(8,8))
ax = fig.gca()
imshow_handle = plt.imshow(pp0, origin='lower', extent=(min(X[:,0]), max(X[:,0]), min(X[:,1]), max(X[:,1])), alpha=.7)
ax.scatter(data[data.t==0].x1, data[data.t==0].x2, s=40, c=colors[0], alpha=.7)
ax.scatter(data[data.t==1].x1, data[data.t==1].x2, s=40,c=colors[1], alpha... | _____no_output_____ | MIT | codici/gda-lin-sk-cv.ipynb | tvml/ml2122 |
Visualizzazione di $p(C_1|x)$ | fig = plt.figure(figsize=(8,8))
ax = fig.gca()
imshow_handle = plt.imshow(pp1, origin='lower', extent=(min(X[:,0]), max(X[:,0]), min(X[:,1]), max(X[:,1])), alpha=.7)
ax.scatter(data[data.t==0].x1, data[data.t==0].x2, s=40, c=colors[0], alpha=.7)
ax.scatter(data[data.t==1].x1, data[data.t==1].x2, s=40,c=colors[1], alpha... | _____no_output_____ | MIT | codici/gda-lin-sk-cv.ipynb | tvml/ml2122 |
Applica la cross validation (5-fold) per calcolare l'accuracy effettuando la media sui 5 valori restituiti. | print("Accuracy: {0:5.3f}".format(cross_val_score(clf, X, t, cv=5, scoring='accuracy').mean())) | Accuracy: 0.870
| MIT | codici/gda-lin-sk-cv.ipynb | tvml/ml2122 |
ML Pipeline PreparationFollow the instructions below to help you create your ML pipeline. 1. Import libraries and load data from database.- Import Python libraries- Load dataset from database with [`read_sql_table`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_sql_table.html)- Define feature and ... | # import basic libraries
import os
import pickle
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sqlalchemy import create_engine
# import nltk and text processing (like regular expresion) libraries
import nltk
nltk.download(['punkt', 'wordnet','stopwords'])
from nltk.t... | _____no_output_____ | CNRI-Python | notebooks/ML Pipeline Preparation.ipynb | inmaugarc/DataScience_Disaster_Response_Pipeline |
Exploratory Data Analysis (EDA) Let's do some Exploratory Data Analysis.First of all we'll see an overview of the dataset | df.info()
df.describe() | _____no_output_____ | CNRI-Python | notebooks/ML Pipeline Preparation.ipynb | inmaugarc/DataScience_Disaster_Response_Pipeline |
We can see there are 40 columns and 26216 entries and our dataset has a memory usage: of 8.0+ MBThe dataset is pretty complete, with almost all its values (non-null).There are three string fields and the rest of fields are of type integerIf we look at the fields, the major part of them are values between [0-1] except t... | df.groupby("related").count()
df[df['related'] ==2].head()
df[df['related'] ==2].describe()
df[df['related'] ==0].describe()
df[df['related'] ==1].describe() | _____no_output_____ | CNRI-Python | notebooks/ML Pipeline Preparation.ipynb | inmaugarc/DataScience_Disaster_Response_Pipeline |
After exploring this field, there is not much information. Only that there are few entries of related field with value=2 compare to the rest of the values.With the related value=2 we have two ways of working: 1. We could impute them with another value, for instance value=1 that is the most often 2. Drop themAnd I... | df = df[df.related !=2] | _____no_output_____ | CNRI-Python | notebooks/ML Pipeline Preparation.ipynb | inmaugarc/DataScience_Disaster_Response_Pipeline |
And we'll check | df['related'].describe()
df.groupby("related").count() | _____no_output_____ | CNRI-Python | notebooks/ML Pipeline Preparation.ipynb | inmaugarc/DataScience_Disaster_Response_Pipeline |
Now we'll check the 10 first lines of the dataset | df.head(10) | _____no_output_____ | CNRI-Python | notebooks/ML Pipeline Preparation.ipynb | inmaugarc/DataScience_Disaster_Response_Pipeline |
Pearson correlation between variablesLet's build a heatmap, to see the correlation of each variable | data = df.copy()
f,ax = plt.subplots(figsize=(15, 15))
sns.heatmap(data.corr(), annot=True, linewidths=.5, fmt= '.1f',ax=ax)
plt.show() | _____no_output_____ | CNRI-Python | notebooks/ML Pipeline Preparation.ipynb | inmaugarc/DataScience_Disaster_Response_Pipeline |
From this Pearson map, we clearly see there is a strange column "child_alone"Let's explore more in detail | df.groupby("child_alone").count() | _____no_output_____ | CNRI-Python | notebooks/ML Pipeline Preparation.ipynb | inmaugarc/DataScience_Disaster_Response_Pipeline |
We see that column only contains zero values so we are going to delete them, as it doesn't bring us much help | df = df.drop(["child_alone"],axis=1) | _____no_output_____ | CNRI-Python | notebooks/ML Pipeline Preparation.ipynb | inmaugarc/DataScience_Disaster_Response_Pipeline |
Let's see the Pearson again | data = df.copy()
f,ax = plt.subplots(figsize=(15, 15))
sns.heatmap(data.corr(), annot=True, linewidths=.5, fmt= '.1f',ax=ax)
plt.show() | _____no_output_____ | CNRI-Python | notebooks/ML Pipeline Preparation.ipynb | inmaugarc/DataScience_Disaster_Response_Pipeline |
We have a glimpse of the data!! Now, we will start with the Machine Learning tasks | # We separate the features from the variables we are going to predict
X = df ['message']
y = df.drop(columns = ['id', 'message', 'original', 'genre']) | _____no_output_____ | CNRI-Python | notebooks/ML Pipeline Preparation.ipynb | inmaugarc/DataScience_Disaster_Response_Pipeline |
2. Tokenization function to process your text data | def tokenize(text):
# normalize case and remove punctuation
text = re.sub(r"[^a-zA-Z0-9]", " ", text.lower())
# tokenize text
tokens = word_tokenize(text)
# lemmatize andremove stop words
tokens = [lemmatizer.lemmatize(word) for word in tokens if word not in stop_words]
return tok... | _____no_output_____ | CNRI-Python | notebooks/ML Pipeline Preparation.ipynb | inmaugarc/DataScience_Disaster_Response_Pipeline |
3. Build a machine learning pipelineThis machine pipeline should take in the `message` column as input and output classification results on the other 36 categories in the dataset. You may find the [MultiOutputClassifier](http://scikit-learn.org/stable/modules/generated/sklearn.multioutput.MultiOutputClassifier.html) h... | pipeline = Pipeline([
('vect', CountVectorizer(tokenizer=tokenize)),
('tfidf', TfidfTransformer()),
('clf', MultiOutputClassifier (RandomForestClassifier()))
]) | _____no_output_____ | CNRI-Python | notebooks/ML Pipeline Preparation.ipynb | inmaugarc/DataScience_Disaster_Response_Pipeline |
4. Train pipeline- Split data into train and test sets- Train pipeline | X_train, X_test, y_train, y_test = train_test_split(X, y)
# train classifier
pipeline.fit(X_train, y_train) | _____no_output_____ | CNRI-Python | notebooks/ML Pipeline Preparation.ipynb | inmaugarc/DataScience_Disaster_Response_Pipeline |
5. Test your modelReport the f1 score, precision and recall for each output category of the dataset. You can do this by iterating through the columns and calling sklearn's `classification_report` on each. | # predict on test data
y_pred = pipeline.predict(X_test)
# we check dimensions
X_train.shape, y_train.shape, y.shape, X.shape
# and print metrics
accuracy = (y_pred == y_test).mean()
print("Accuracy:", accuracy, "\n")
category_names = list(y.columns)
for i in range(len(category_names)):
print("Output Category:", ... | Accuracy: related 0.805920
request 0.884803
offer 0.994355
aid_related 0.763198
medical_help 0.922338
medical_products 0.950717
search_and_rescue 0.973451
security 0.982606
military 0.97... | CNRI-Python | notebooks/ML Pipeline Preparation.ipynb | inmaugarc/DataScience_Disaster_Response_Pipeline |
6. Improve your modelUse grid search to find better parameters. | base = Pipeline([
('vect', CountVectorizer(tokenizer=tokenize)),
('tfidf', TfidfTransformer()),
('clf', MultiOutputClassifier(RandomForestClassifier()))
])
parameters = {'clf__estimator__n_estimators': [10, 20],
'clf__estimator__max_depth': [2, 5],
'clf__... | Fitting 2 folds for each of 12 candidates, totalling 24 fits
[CV] clf__estimator__criterion=entropy, clf__estimator__max_depth=2, clf__estimator__min_samples_split=2, clf__estimator__n_estimators=10
[CV] clf__estimator__criterion=entropy, clf__estimator__max_depth=2, clf__estimator__min_samples_split=2, clf__estimato... | CNRI-Python | notebooks/ML Pipeline Preparation.ipynb | inmaugarc/DataScience_Disaster_Response_Pipeline |
7. Test your modelShow the accuracy, precision, and recall of the tuned model. Since this project focuses on code quality, process, and pipelines, there is no minimum performance metric needed to pass. However, make sure to fine tune your models for accuracy, precision and recall to make your project stand out - esp... | y_pred = cv.predict(X_test)
accuracy = (y_pred == y_test).mean()
print("Accuracy:", accuracy, "\n")
for i in range(len(category_names)):
print("Output Category:", category_names[i],"\n", classification_report(y_test.iloc[:, i].values, y_pred[:, i]))
print('Accuracy of %25s: %.2f' %(category_names[i], accuracy_s... | Accuracy: related 0.758621
request 0.827739
offer 0.994355
aid_related 0.591700
medical_help 0.921575
medical_products 0.949649
search_and_rescue 0.971926
security 0.983064
military 0.97... | CNRI-Python | notebooks/ML Pipeline Preparation.ipynb | inmaugarc/DataScience_Disaster_Response_Pipeline |
8. Try improving your model further. Here are a few ideas:* try other machine learning algorithms* add other features besides the TF-IDF | from sklearn.decomposition import TruncatedSVD
import sklearn
base = Pipeline([
('vect',CountVectorizer(tokenizer=tokenize)),
('tfidf', TfidfTransformer()),
('lsa', TruncatedSVD(random_state=42, n_components=100)),
# ('clf', MultiOutputClassifier(sklearn.s... | _____no_output_____ | CNRI-Python | notebooks/ML Pipeline Preparation.ipynb | inmaugarc/DataScience_Disaster_Response_Pipeline |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.