markdown
stringlengths
0
1.02M
code
stringlengths
0
832k
output
stringlengths
0
1.02M
license
stringlengths
3
36
path
stringlengths
6
265
repo_name
stringlengths
6
127
We have to use the tokenizer to encode the text:
encoded_review = tokenizer.encode_plus( review_text, max_length=MAX_LEN, add_special_tokens=True, return_token_type_ids=False, pad_to_max_length=True, return_attention_mask=True, return_tensors='pt', )
_____no_output_____
MIT
bert4sentiment_pytorch.ipynb
nluninja/bert4sentiment_pytorch
Let's get the predictions from our model:
input_ids = encoded_review['input_ids'].to(device) attention_mask = encoded_review['attention_mask'].to(device) output = model(input_ids, attention_mask) _, prediction = torch.max(output, dim=1) print(f'Review text: {review_text}') print(f'Sentiment : {class_names[prediction]}')
_____no_output_____
MIT
bert4sentiment_pytorch.ipynb
nluninja/bert4sentiment_pytorch
1. Introduction to Natural Language ProcessingNatural Language Processing is certainly one of the most fascinating and exciting areas to be involved with at this point in time. It is a wonderful intersection of computer science, artificial intelligence, machine learning and linguistics. With the (somewhat) recent rise...
from sklearn.naive_bayes import MultinomialNB import pandas as pd import numpy as np data = pd.read_csv('../../data/nlp/spambase.data') data.head() data = data.values np.random.shuffle(data) # randomly split data into train and test sets X = data[:, :48] Y = data[:, -1] Xtrain = X[:-100,] Ytrain = Y[:-100,] Xtest ...
Classifcation Rate for NB: 0.87
MIT
NLP/01-Introduction_to_NLP-01-Introduction.ipynb
NathanielDake/NathanielDake.github.io
Excellent, a classification rate of 92%! Let's now look utilize `AdaBoost`:
from sklearn.ensemble import AdaBoostClassifier model = AdaBoostClassifier() model.fit(Xtrain, Ytrain) print ("Classifcation Rate for Adaboost: ", model.score(Xtest, Ytest))
Classifcation Rate for Adaboost: 0.94
MIT
NLP/01-Introduction_to_NLP-01-Introduction.ipynb
NathanielDake/NathanielDake.github.io
Great, a nice improvement, but more importantly, we have shown that we can take text data and that via correct preprocessing we are able to utilize it with standard machine learning API's. The next step is to dig into _how_ basic preprocessing is performed. --- 3. Sentiment AnalysisTo go through the basic preprocessing...
import nltk import numpy as np from nltk.stem import WordNetLemmatizer from sklearn.linear_model import LogisticRegression from bs4 import BeautifulSoup wordnet_lemmatizer = WordNetLemmatizer() # this turns words into their base form stopwords = set(w.rstrip() for w in open('../../dat...
_____no_output_____
MIT
NLP/01-Introduction_to_NLP-01-Introduction.ipynb
NathanielDake/NathanielDake.github.io
3.3.1 Class ImbalanceThere are more positive than negative reviews, so we are going to shuffle the positive reviews and then cut off any extra that we may have so that they are both the same size.
np.random.shuffle(positive_reviews) positive_reviews = positive_reviews[:len(negative_reviews)]
_____no_output_____
MIT
NLP/01-Introduction_to_NLP-01-Introduction.ipynb
NathanielDake/NathanielDake.github.io
3.3.2 Tokenizer functionLets now create a tokenizer function that can be used on our specific reviews.
def my_tokenizer(s): s = s.lower() tokens = nltk.tokenize.word_tokenize(s) # essentially string.split() tokens = [t for t in tokens if len(t) > 2] # get rid of short words tokens = [wordnet_lemmatizer.lemmatize(t) for t in tokens] # get words to base form ...
_____no_output_____
MIT
NLP/01-Introduction_to_NLP-01-Introduction.ipynb
NathanielDake/NathanielDake.github.io
3.3.3 Index each wordWe now need to create an index for each of the words, so that each word has an index in the final data vector. However, to able able to do that we need to know the size of the final data vector, and to be able to know that we need to know how big the vocabulary is. Remember, the **vocabulary** is ...
word_index_map = {} # our vocabulary - dictionary that will map words to dictionaries current_index = 0 # counter increases whenever we see a new word positive_tokenized = [] negative_tokenized = [] # --------- loop through positive reviews --------- for review ...
_____no_output_____
MIT
NLP/01-Introduction_to_NLP-01-Introduction.ipynb
NathanielDake/NathanielDake.github.io
And we can actually take a look at the contents of `word_index_map` by making use of the `random` module (part of the Python Standard Library):
import random print(dict(random.sample(word_index_map.items(), 20))) print('Vocabulary Size', len(word_index_map))
Vocabulary Size 11088
MIT
NLP/01-Introduction_to_NLP-01-Introduction.ipynb
NathanielDake/NathanielDake.github.io
3.3.4 Convert tokens into vectorNow that we have our tokens and vocabulary, we need to convert our tokens into a vector. Because we are going to shuffle our train and test sets again, we are going to want to put labels and vector into same array for now since it makes it easier to shuffle. Note, this function operates...
def tokens_to_vector(tokens, label): xy_data = np.zeros(len(word_index_map) + 1) # equal to the vocab size + 1 for the label for t in tokens: # loop through every token i = word_index_map[t] # get index from word index map ...
_____no_output_____
MIT
NLP/01-Introduction_to_NLP-01-Introduction.ipynb
NathanielDake/NathanielDake.github.io
Time to actually assign these tokens to vectors.
N = len(positive_tokenized) + len(negative_tokenized) # total number of examples data = np.zeros((N, len(word_index_map) + 1)) # N examples x vocab size + 1 for label i = 0 # counter to keep track of sample for tokens in...
(2000, 11089)
MIT
NLP/01-Introduction_to_NLP-01-Introduction.ipynb
NathanielDake/NathanielDake.github.io
Our data is now 1000 rows of positively labeled reviews, followed by 1000 rows of negatively labeled reviews. We have `11089` columns, which is one more than our vocabulary size because we have a column for the label (positive or negative). Lets shuffle before getting our train and test set.
np.random.shuffle(data) X = data[:, :-1] Y = data[:, -1] Xtrain = X[:-100,] Ytrain = Y[:-100,] Xtest = X[-100:,] Ytest = Y[-100:,] model = LogisticRegression() model.fit(Xtrain, Ytrain) print("Classification Rate: ", model.score(Xtest, Ytest))
Classification Rate: 0.7
MIT
NLP/01-Introduction_to_NLP-01-Introduction.ipynb
NathanielDake/NathanielDake.github.io
3.3.5 Classification RateWe end up with a classification rate of 0.71, which is not ideal, but it is better than random guessing. 3.3.6 Sentiment AnalysisSomething interesting that we can do is look at the weights of each word, to see if that word has positive or negative sentiment.
threshold = 0.7 large_magnitude_weights = [] for word, index in word_index_map.items(): weight = model.coef_[0][index] if weight > threshold or weight < -threshold: large_magnitude_weights.append((word, weight)) def sort_by_magnitude(sentiment_dict): return sentiment_dict[1] large_magnitude_weigh...
[('price', 2.808163204024058), ('easy', 1.7646511704661152), ('quality', 1.3716522244882545), ('excellent', 1.319811182219224), ('love', 1.237745876552362), ('you', 1.155006377913112), ('perfect', 1.0324004425098248), ('sound', 0.9780126530219685), ('highly', 0.9778749978617105), ('memory', 0.9398953342479317), ('littl...
MIT
NLP/01-Introduction_to_NLP-01-Introduction.ipynb
NathanielDake/NathanielDake.github.io
Clearly the above list is not perfect, _but_ it should give some insight on what is possible for us already. The logistic regression model was able to pick out `easy`, `quality`, and `excellent` as words that correlate to a positive response, and it was able to find `poor`, `returned`, and `waste` as words the correlat...
import nltk nltk.pos_tag("Bob is great".split()) nltk.pos_tag("Machine learning is great".split())
_____no_output_____
MIT
NLP/01-Introduction_to_NLP-01-Introduction.ipynb
NathanielDake/NathanielDake.github.io
The second entry in the above tuples `NN`, `VBZ`, etc, represents the determined tag of the word. For a description of each tag, check out [this link](https://www.ling.upenn.edu/courses/Fall_2003/ling001/penn_treebank_pos.html). 4.2 Stemming and LemmatizationBoth the process of **stemming** and **lemmatization** are ...
porter_stemmer = nltk.stem.porter.PorterStemmer() print(porter_stemmer.stem('dogs')) print(porter_stemmer.stem('wolves')) lemmatizer = nltk.stem.WordNetLemmatizer() print(lemmatizer.lemmatize('dogs')) print(lemmatizer.lemmatize('wolves'))
wolf
MIT
NLP/01-Introduction_to_NLP-01-Introduction.ipynb
NathanielDake/NathanielDake.github.io
Both the stemmer and lemmatizer managed to get `dogs` correct, but only the lemmatizer managed to correctly convert `wolves` to base form. 4.3 Named Entity Recognition Finally there is **Named Entity** recognition. Entities refer to nouns such as:* "Albert Einstein" - a person* "Apple" - an organization
s = "Albert Einstein was born on March 14, 1879" tags = nltk.pos_tag(s.split()) print(tags) nltk.ne_chunk(tags) s = "Steve Jobs was the CEO of Apple Corp." tags = nltk.pos_tag(s.split()) print(tags) nltk.ne_chunk(tags)
_____no_output_____
MIT
NLP/01-Introduction_to_NLP-01-Introduction.ipynb
NathanielDake/NathanielDake.github.io
--- 5. Latent Semantic AnalysisWe will now take a moment to extend our semantic analysis example from before, instead now performing **Latent Semantic Analysis**. Latent semantic analysis is utilized to deal with the reality that we will often have _multiple_ words with the _same_ meaning, or on the other hand, _one_ w...
import nltk import numpy as np import matplotlib.pyplot as plt from nltk.stem import WordNetLemmatizer from sklearn.decomposition import TruncatedSVD
_____no_output_____
MIT
NLP/01-Introduction_to_NLP-01-Introduction.ipynb
NathanielDake/NathanielDake.github.io
Process:* we start by pulling in all of the titles, and all of the stop words. Our titles will look like:```['Philosophy of Sex and Love A Reader', 'Readings in Judaism, Christianity, and Islam', 'Microprocessors Principles and Applications', 'Bernhard Edouard Fernow: Story of North American Forestry', 'Encyclopedia o...
wordnet_lemmatizer = WordNetLemmatizer() titles = [line.rstrip() for line in open('../../data/nlp/all_book_titles.txt')] # Load all book titles in to an array stopwords = set(w.rstrip() for w in open('../../data/nlp/stopwords.txt')) # loading stop words (irrelevant) stopwords = stopwords.union({ ...
_____no_output_____
MIT
NLP/01-Introduction_to_NLP-01-Introduction.ipynb
NathanielDake/NathanielDake.github.io
Plagiarism Detection ModelNow that you've created training and test data, you are ready to define and train a model. Your goal in this notebook, will be to train a binary classification model that learns to label an answer file as either plagiarized or not, based on the features you provide the model.This task will be...
import pandas as pd import boto3 import sagemaker """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ # session and role sagemaker_session = sagemaker.Session() role = sagemaker.get_execution_role() # create an S3 bucket bucket = sagemaker_session.default_bucket()
_____no_output_____
MIT
Project_Plagiarism_Detection/3_Training_a_Model.ipynb
csuquanyanfei/ML_Sagemaker_Studies_Project2
EXERCISE: Upload your training data to S3Specify the `data_dir` where you've saved your `train.csv` file. Decide on a descriptive `prefix` that defines where your data will be uploaded in the default S3 bucket. Finally, create a pointer to your training data by calling `sagemaker_session.upload_data` and passing in th...
# should be the name of directory you created to save your features data data_dir = 'plagiarism_data' # set prefix, a descriptive name for a directory prefix = 'sagemaker/plagiarism-detection' # upload all data to S3 input_data = sagemaker_session.upload_data(path=data_dir, bucket=bucket, key_prefix=prefix)
_____no_output_____
MIT
Project_Plagiarism_Detection/3_Training_a_Model.ipynb
csuquanyanfei/ML_Sagemaker_Studies_Project2
Test cellTest that your data has been successfully uploaded. The below cell prints out the items in your S3 bucket and will throw an error if it is empty. You should see the contents of your `data_dir` and perhaps some checkpoints. If you see any other files listed, then you may have some old model files that you can ...
""" DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ # confirm that data is in S3 bucket empty_check = [] for obj in boto3.resource('s3').Bucket(bucket).objects.all(): empty_check.append(obj.key) print(obj.key) assert len(empty_check) !=0, 'S3 bucket is empty.' print('Test passed!')
Lambda/ Lambda/lambda_function.zip Lambda/package.zip Lambda/plagiarism_detection_func-8a2856a0-4389-44ac-a08f-24e25d799fca.zip Lambda/sample-site-packages-2016-02-20.zip Panda_Layer.zip boston-update-endpoints/train.csv boston-update-endpoints/validation.csv boston-xgboost-HL/output/xgboost-2020-10-05-09-40-13-851/out...
MIT
Project_Plagiarism_Detection/3_Training_a_Model.ipynb
csuquanyanfei/ML_Sagemaker_Studies_Project2
--- ModelingNow that you've uploaded your training data, it's time to define and train a model!The type of model you create is up to you. For a binary classification task, you can choose to go one of three routes:* Use a built-in classification algorithm, like LinearLearner.* Define a custom Scikit-learn classifier, a ...
# directory can be changed to: source_sklearn or source_pytorch !pygmentize source_sklearn/train.py
from __future__ import print_function import argparse import os import pandas as pd from ...
MIT
Project_Plagiarism_Detection/3_Training_a_Model.ipynb
csuquanyanfei/ML_Sagemaker_Studies_Project2
Provided codeIf you read the code above, you can see that the starter code includes a few things:* Model loading (`model_fn`) and saving code* Getting SageMaker's default hyperparameters* Loading the training data by name, `train.csv` and extracting the features and labels, `train_x`, and `train_y`If you'd like to rea...
# your import and estimator code, here from sagemaker.sklearn.estimator import SKLearn # specify an output path prefix = 'sagemaker/plagiarism-detection/output' # define location to store model artifacts output_path='s3://{}/{}/'.format(bucket, prefix) # instantiate a pytorch estimator estimator = SKLearn(entry_poi...
This is not the latest supported version. If you would like to use version 0.23-1, please add framework_version=0.23-1 to your constructor.
MIT
Project_Plagiarism_Detection/3_Training_a_Model.ipynb
csuquanyanfei/ML_Sagemaker_Studies_Project2
EXERCISE: Train the estimatorTrain your estimator on the training data stored in S3. This should create a training job that you can monitor in your SageMaker console.
%%time # Train your estimator on S3 training data estimator.fit({'train': input_data})
's3_input' class will be renamed to 'TrainingInput' in SageMaker Python SDK v2.
MIT
Project_Plagiarism_Detection/3_Training_a_Model.ipynb
csuquanyanfei/ML_Sagemaker_Studies_Project2
EXERCISE: Deploy the trained modelAfter training, deploy your model to create a `predictor`. If you're using a PyTorch model, you'll need to create a trained `PyTorchModel` that accepts the trained `.model_data` as an input parameter and points to the provided `source_pytorch/predict.py` file as an entry point. To dep...
%%time #from sagemaker.sklearn.model import SKLearnModel # uncomment, if needed # from sagemaker.pytorch import PyTorchModel #model=SKLearnModel(model_data=estimator.model_data, # role = role, # framework_version='0.23-1', # entry_point='train.py', ...
Parameter image will be renamed to image_uri in SageMaker Python SDK v2.
MIT
Project_Plagiarism_Detection/3_Training_a_Model.ipynb
csuquanyanfei/ML_Sagemaker_Studies_Project2
--- Evaluating Your ModelOnce your model is deployed, you can see how it performs when applied to our test data.The provided cell below, reads in the test data, assuming it is stored locally in `data_dir` and named `test.csv`. The labels and features are extracted from the `.csv` file.
""" DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ import os # read in test data, assuming it is stored locally test_data = pd.read_csv(os.path.join(data_dir, "test.csv"), header=None, names=None) # labels are in the first column test_y = test_data.iloc[:,0] test_x = test_data.iloc[:,1:]
_____no_output_____
MIT
Project_Plagiarism_Detection/3_Training_a_Model.ipynb
csuquanyanfei/ML_Sagemaker_Studies_Project2
EXERCISE: Determine the accuracy of your modelUse your deployed `predictor` to generate predicted, class labels for the test data. Compare those to the *true* labels, `test_y`, and calculate the accuracy as a value between 0 and 1.0 that indicates the fraction of test data that your model classified correctly. You may...
import numpy as np # First: generate predicted, class labels test_y_preds = np.squeeze(np.round(predictor.predict(test_x))) """ DON'T MODIFY ANYTHING IN THIS CELL THAT IS BELOW THIS LINE """ # test that your model generates the correct number of labels assert len(test_y_preds)==len(test_y), 'Unexpected number of pre...
tp:15 fp:1 tn:9 fn:0 0.96 Predicted class labels: [1 1 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1 1 0 1 1 1 1 0 0] True class labels: [1 1 1 1 1 1 0 0 0 0 0 0 1 1 1 1 1 1 0 1 0 1 1 0 0]
MIT
Project_Plagiarism_Detection/3_Training_a_Model.ipynb
csuquanyanfei/ML_Sagemaker_Studies_Project2
Question 1: How many false positives and false negatives did your model produce, if any? And why do you think this is? ** Answer**: Case 1, when use selected_features ['c_11', 'lcs_word'], and Classfier "LinearSVC", we have one false negative. Case 2, when use selected_features ['c_11', 'lcs_word'], and C...
#Case 1 Check: predict_df = pd.concat([pd.DataFrame(test_x), pd.DataFrame(test_y_preds), pd.DataFrame(test_y)], axis=1) predict_df.columns=['c_11', 'lcs_word', 'predicted class','true class'] predict_df #Case 2 Check: predict_df = pd.concat([pd.DataFrame(test_x), pd.DataFrame(test_y_preds), pd.DataFrame(test_y)], axis=...
_____no_output_____
MIT
Project_Plagiarism_Detection/3_Training_a_Model.ipynb
csuquanyanfei/ML_Sagemaker_Studies_Project2
Question 2: How did you decide on the type of model to use? ** Answer**: If the problem need only binary output (is 0 or 1)/(is true or false), binary classifier is a good choice. When the noise in the training data is minimized, then we can also use simpler classifier for good performance. Otherwise, we need use mor...
a=pd.DataFrame(np.array([[0.765306, 0.394366, 0.621711]]),columns=[1, 2, 3]) test_file.getvalue() import boto3 import io from io import StringIO test_file = io.StringIO() check_data=test_x.iloc[:2,1:] #data.iloc[:2,1:] check_data.to_csv(test_file,header = None, index = None) runtime = boto3.Session().client('sagemak...
_____no_output_____
MIT
Project_Plagiarism_Detection/3_Training_a_Model.ipynb
csuquanyanfei/ML_Sagemaker_Studies_Project2
---- EXERCISE: Clean up ResourcesAfter you're done evaluating your model, **delete your model endpoint**. You can do this with a call to `.delete_endpoint()`. You need to show, in this notebook, that the endpoint was deleted. Any other resources, you may delete from the AWS console, and you will find more instructions ...
# uncomment and fill in the line below! # <name_of_deployed_predictor>.delete_endpoint() def delete_endpoint(predictor): try: boto3.client('sagemaker').delete_endpoint(EndpointName=predictor.endpoint) print('Deleted {}'.format(predictor.endpoint)) except: print('Alrea...
Deleted sagemaker-scikit-learn-2020-10-23-18-36-19-083
MIT
Project_Plagiarism_Detection/3_Training_a_Model.ipynb
csuquanyanfei/ML_Sagemaker_Studies_Project2
Deleting S3 bucketWhen you are *completely* done with training and testing models, you can also delete your entire S3 bucket. If you do this before you are done training your model, you'll have to recreate your S3 bucket and upload your training data again.
# deleting bucket, uncomment lines below bucket_to_delete = boto3.resource('s3').Bucket(bucket) bucket_to_delete.objects.all().delete()
_____no_output_____
MIT
Project_Plagiarism_Detection/3_Training_a_Model.ipynb
csuquanyanfei/ML_Sagemaker_Studies_Project2
Exercise check if x >10, return T/F
x = 12 if x>10: print('True') else: print('F')
True
MIT
Python_Class/Class_7.ipynb
rickchen123/Portfolio
define a function called square that returns the squared value of input x
def square(x): return(x**2) square(12)
_____no_output_____
MIT
Python_Class/Class_7.ipynb
rickchen123/Portfolio
Library Importing
##First way import numpy numpy.absolute(-7) numpy.sqrt(8) ##Second way from numpy import sqrt sqrt(8) absolute(-7) import numpy as np np.sqrt(8) import random random.randint(a= 0 ,b= 10 ) from random import randint randint(0,10)
_____no_output_____
MIT
Python_Class/Class_7.ipynb
rickchen123/Portfolio
Turtle
import turtle as t import numpy as np import random ##set up screen screen = t.Screen() ## set up background color screen.bgcolor('lightgreen') ## set screen title screen.title("Rick's Program") ##set up a turtle rick = t.Turtle() ## move forward rick.forward(100) # rick.fd(100) ## move backward # rick.backward(100)...
_____no_output_____
MIT
Python_Class/Class_7.ipynb
rickchen123/Portfolio
Question: how do we draw a square?
for i in range(1,5): t.fd(90) t.left(90) t.exitonclick()
_____no_output_____
MIT
Python_Class/Class_7.ipynb
rickchen123/Portfolio
Question: how do we draw a circle?
t.circle(100) t.exitonclick()
_____no_output_____
MIT
Python_Class/Class_7.ipynb
rickchen123/Portfolio
Question: How to we draw this graph using turtle?
##First Square t.left(20) for i in range(1,5): t.fd(90) t.left(90) ##Second Square t.left(20) for i in range(1,5): t.fd(90) t.left(90) ##Third Square t.left(20) for i in range(1,5): t.fd(90) t.left(90) t.exitonclick() for i in range(1,4): t.left(20) for i in range(1,5): t.fd...
_____no_output_____
MIT
Python_Class/Class_7.ipynb
rickchen123/Portfolio
Game
screen = t.Screen() ## set up background color screen.bgcolor('lightgreen') ## set screen title screen.title("Rick's Program") ##Draw a Border border = t.Turtle() border.color('white') border.penup() border.setposition(-300,-300) border.pendown() border.pensize(3) for side in range(4): border.fd(600) border.lt...
_____no_output_____
MIT
Python_Class/Class_7.ipynb
rickchen123/Portfolio
s3 configuration
s3 = boto3.resource("s3", endpoint_url = "http://192.168.0.29", aws_access_key_id="AKIAPo19vPR_TJaeVgleCiOSUw", aws_secret_access_key="7cSWM1KCXvRpK4ICeDEAfuicEm+QQeuhqOi7cejZ", region_name = 'eu-central-1', ) kwargs = {'en...
_____no_output_____
Apache-2.0
doc/integrations/pytorch/Cortx-PyTroch Integration - 2, Loading Data from Cotrx-S3 and Train the model.ipynb
sarthakarora1208/cortx
Create Custom Dataset to Load data- Pytorch do not have any existing Dataset Loader classes that fetch data from s3. Therefore we need to create a custom Dataset Loader that will fetch the data from Cortx-s3.
class ImageDataset(Dataset): def __init__(self, path="s3://sample-dataset/sample_data/", transform=None): self.path = path self.classes = [folder["name"] for folder in client.listdir(path)][2:] self.files = [] for directory in self.classes: self.files += [file for fi...
_____no_output_____
Apache-2.0
doc/integrations/pytorch/Cortx-PyTroch Integration - 2, Loading Data from Cotrx-S3 and Train the model.ipynb
sarthakarora1208/cortx
pip install pygame pip install neat-python import pygame import neat import time import os import random #Window and object images WIN_WIDTH = 600 WIN_HEIGHT = 800 BIRD_IMGS = [pygame.transorm.scale2x(pygame.image.load(os.path.join("imgs", "bird1.png"))), [pygame.transorm.scale2x(pygame.image.load(os.path.jo...
_____no_output_____
MIT
FlappyBird.ipynb
Jack-TBarnett/github-slideshow
Prediction APIProgrammatically use OpenPifPaf to run multi-person pose estimation on an image.The API is for more advanced use cases. Please read {doc}`predict_cli` as well.
import io import numpy as np import openpifpaf import PIL import requests import torch %matplotlib inline openpifpaf.show.Canvas.show = True device = torch.device('cpu') # device = torch.device('cuda') # if cuda is available print(openpifpaf.__version__) print(torch.__version__)
_____no_output_____
CC-BY-2.0
guide/predict_api.ipynb
adujardin/openpifpaf
Load an Example ImageImage credit: "[Learning to surf](https://www.flickr.com/photos/fotologic/6038911779/in/photostream/)" by fotologic which is licensed under [CC-BY-2.0].[CC-BY-2.0]: https://creativecommons.org/licenses/by/2.0/
image_response = requests.get('https://raw.githubusercontent.com/vita-epfl/openpifpaf/master/docs/coco/000000081988.jpg') pil_im = PIL.Image.open(io.BytesIO(image_response.content)).convert('RGB') im = np.asarray(pil_im) with openpifpaf.show.image_canvas(im) as ax: pass
_____no_output_____
CC-BY-2.0
guide/predict_api.ipynb
adujardin/openpifpaf
Load a Trained Neural Network
net_cpu, _ = openpifpaf.network.Factory(checkpoint='shufflenetv2k16', download_progress=False).factory() net = net_cpu.to(device) openpifpaf.decoder.utils.CifSeeds.threshold = 0.5 openpifpaf.decoder.utils.nms.Keypoints.keypoint_threshold = 0.2 openpifpaf.decoder.utils.nms.Keypoints.instance_threshold = 0.2 processor =...
_____no_output_____
CC-BY-2.0
guide/predict_api.ipynb
adujardin/openpifpaf
Preprocessing, DatasetSpecify the image preprocossing. Beyond the default transforms, we also use `CenterPadTight(16)` which adds padding to the image such that both the height and width are multiples of 16 plus 1. With this padding, the feature map covers the entire image. Without it, there would be a gap on the righ...
preprocess = openpifpaf.transforms.Compose([ openpifpaf.transforms.NormalizeAnnotations(), openpifpaf.transforms.CenterPadTight(16), openpifpaf.transforms.EVAL_TRANSFORM, ]) data = openpifpaf.datasets.PilImageList([pil_im], preprocess=preprocess)
_____no_output_____
CC-BY-2.0
guide/predict_api.ipynb
adujardin/openpifpaf
Dataloader, Visualizer
loader = torch.utils.data.DataLoader( data, batch_size=1, pin_memory=True, collate_fn=openpifpaf.datasets.collate_images_anns_meta) annotation_painter = openpifpaf.show.AnnotationPainter()
_____no_output_____
CC-BY-2.0
guide/predict_api.ipynb
adujardin/openpifpaf
Prediction
for images_batch, _, __ in loader: predictions = processor.batch(net, images_batch, device=device)[0] with openpifpaf.show.image_canvas(im) as ax: annotation_painter.annotations(ax, predictions)
_____no_output_____
CC-BY-2.0
guide/predict_api.ipynb
adujardin/openpifpaf
Each prediction in the `predictions` list above is of type `Annotation`. You can access the joint coordinates in the `data` attribute. It is a numpy array that contains the $x$ and $y$ coordinates and the confidence for every joint:
predictions[0].data
_____no_output_____
CC-BY-2.0
guide/predict_api.ipynb
adujardin/openpifpaf
FieldsBelow are visualizations of the fields.When using the API here, the visualization types are individually enabled.Then, the index for every field to visualize must be specified. In the example below, the fifth CIF (left shoulder) and the fifth CAF (left shoulder to left hip) are activated.These plots are also acc...
openpifpaf.visualizer.Base.set_all_indices(['cif,caf:5:confidence']) for images_batch, _, __ in loader: predictions = processor.batch(net, images_batch, device=device)[0] openpifpaf.visualizer.Base.set_all_indices(['cif,caf:5:regression']) for images_batch, _, __ in loader: predictions = processor.batch(net, imag...
_____no_output_____
CC-BY-2.0
guide/predict_api.ipynb
adujardin/openpifpaf
From the CIF field, a high resolution accumulation (in the code it's called `CifHr`) is generated.This is also the basis for the seeds. Both are shown below.
openpifpaf.visualizer.Base.set_all_indices(['cif:5:hr', 'seeds']) for images_batch, _, __ in loader: predictions = processor.batch(net, images_batch, device=device)[0]
_____no_output_____
CC-BY-2.0
guide/predict_api.ipynb
adujardin/openpifpaf
Starting from a seed, the poses are constructed. At every joint position, an occupancy map marks whether a previous pose was already constructed here. This reduces the number of poses that are constructed from multiple seeds for the same person. The final occupancy map is below:
openpifpaf.visualizer.Base.set_all_indices(['occupancy:5']) for images_batch, _, __ in loader: predictions = processor.batch(net, images_batch, device=device)[0]
_____no_output_____
CC-BY-2.0
guide/predict_api.ipynb
adujardin/openpifpaf
命令式和符号式混合编程本书到目前为止一直都在使用命令式编程,它使用编程语句改变程序状态。考虑下面这段简单的命令式编程代码。
def add(a, b): return a + b def fancy_func(a, b, c, d): e = add(a, b) f = add(c, d) g = add(e, f) return g fancy_func(1, 2, 3, 4)
_____no_output_____
Apache-2.0
chapter_computational-performance/hybridize.ipynb
femj007/d2l-zh
和我们预期的一样,在运行语句`e = add(a, b)`时,Python会做加法运算并将结果存储在变量`e`,从而令程序的状态发生了改变。类似地,后面的两个语句`f = add(c, d)`和`g = add(e, f)`会依次做加法运算并存储变量。虽然使用命令式编程很方便,但它的运行可能会慢。一方面,即使`fancy_func`函数中的`add`是被重复调用的函数,Python也会逐一执行这三个函数调用语句。另一方面,我们需要保存变量`e`和`f`的值直到`fancy_func`中所有语句执行结束。这是因为在执行`e = add(a, b)`和`f = add(c, d)`这两个语句之后我们并不知道变量`e`和`f`是否会被程序...
def add_str(): return ''' def add(a, b): return a + b ''' def fancy_func_str(): return ''' def fancy_func(a, b, c, d): e = add(a, b) f = add(c, d) g = add(e, f) return g ''' def evoke_str(): return add_str() + fancy_func_str() + ''' print(fancy_func(1, 2, 3, 4)) ''' prog = evoke_str()...
def add(a, b): return a + b def fancy_func(a, b, c, d): e = add(a, b) f = add(c, d) g = add(e, f) return g print(fancy_func(1, 2, 3, 4)) 10
Apache-2.0
chapter_computational-performance/hybridize.ipynb
femj007/d2l-zh
以上定义的三个函数都仅以字符串的形式返回计算流程。最后,我们通过`compile`函数编译完整的计算流程并运行。由于在编译时系统能够完整地看到整个程序,因此有更多空间优化计算。例如,编译的时候可以将程序改写成`print((1 + 2) + (3 + 4))`,甚至直接改写成`print(10)`。这样不仅减少了函数调用,还节省了内存。对比这两种编程方式,我们可以看到* 命令式编程更方便。当我们在Python里使用命令式编程时,大部分代码编写起来都很直观。同时,命令式编程更容易排错。这是因为我们可以很方便地获取并打印所有的中间变量值,或者使用Python的排错工具。* 符号式编程更高效并更容易移植。一方面,在编译的时候系统容易做更多...
from mxnet import nd, sym from mxnet.gluon import nn import time def get_net(): net = nn.HybridSequential() # 这里创建HybridSequential实例 net.add(nn.Dense(256, activation='relu'), nn.Dense(128, activation='relu'), nn.Dense(2)) net.initialize() return net x = nd.random.normal(shape=...
_____no_output_____
Apache-2.0
chapter_computational-performance/hybridize.ipynb
femj007/d2l-zh
我们可以通过调用`hybridize`函数来编译和优化HybridSequential实例中串联层的计算。模型的计算结果不变。
net.hybridize() net(x)
_____no_output_____
Apache-2.0
chapter_computational-performance/hybridize.ipynb
femj007/d2l-zh
需要注意的是,只有继承HybridBlock类的层才会被优化计算。例如,HybridSequential类和Gluon提供的`Dense`类都是HybridBlock类的子类,它们都会被优化计算。如果一个层只是继承自Block类而不是HybridBlock类,那么它将不会被优化。 计算性能我们比较调用`hybridize`函数前后的计算时间来展示符号式编程的性能提升。这里我们计时1000次`net`模型计算。在`net`调用`hybridize`函数前后,它分别依据命令式编程和符号式编程做模型计算。
def benchmark(net, x): start = time.time() for i in range(1000): _ = net(x) nd.waitall() # 等待所有计算完成方便计时 return time.time() - start net = get_net() print('before hybridizing: %.4f sec' % (benchmark(net, x))) net.hybridize() print('after hybridizing: %.4f sec' % (benchmark(net, x)))
before hybridizing: 0.3017 sec
Apache-2.0
chapter_computational-performance/hybridize.ipynb
femj007/d2l-zh
由上面结果可见,在一个HybridSequential实例调用`hybridize`函数后,它可以通过符号式编程提升计算性能。 获取符号式程序在模型`net`根据输入计算模型输出后,例如`benchmark`函数中的`net(x)`,我们就可以通过`export`函数来保存符号式程序和模型参数到硬盘。
net.export('my_mlp')
_____no_output_____
Apache-2.0
chapter_computational-performance/hybridize.ipynb
femj007/d2l-zh
此时生成的.json和.params文件分别为符号式程序和模型参数。它们可以被Python或MXNet支持的其他前端语言读取,例如C++、R、Scala、Perl和其它语言。这样,我们就可以很方便地使用其他前端语言或在其他设备上部署训练好的模型。同时,由于部署时使用的是基于符号式编程的程序,计算性能往往比基于命令式编程时更好。在MXNet中,符号式程序指的是Symbol类型的程序。我们知道,当给`net`提供NDArray类型的输入`x`后,`net(x)`会根据`x`直接计算模型输出并返回结果。对于调用过`hybridize`函数后的模型,我们还可以给它输入一个Symbol类型的变量,`net(x)`会返回Symbol类型的结果。
x = sym.var('data') net(x)
_____no_output_____
Apache-2.0
chapter_computational-performance/hybridize.ipynb
femj007/d2l-zh
使用HybridBlock类构造模型和Sequential类与Block类之间的关系一样,HybridSequential类是HybridBlock类的子类。跟Block实例需要实现`forward`函数不太一样的是,对于HybridBlock实例我们需要实现`hybrid_forward`函数。前面我们展示了调用`hybridize`函数后的模型可以获得更好的计算性能和可移植性。另一方面,调用`hybridize`函数后的模型会影响灵活性。为了解释这一点,我们先使用HybridBlock类构造模型。
class HybridNet(nn.HybridBlock): def __init__(self, **kwargs): super(HybridNet, self).__init__(**kwargs) self.hidden = nn.Dense(10) self.output = nn.Dense(2) def hybrid_forward(self, F, x): print('F: ', F) print('x: ', x) x = F.relu(self.hidden(x)) print(...
_____no_output_____
Apache-2.0
chapter_computational-performance/hybridize.ipynb
femj007/d2l-zh
在继承HybridBlock类时,我们需要在`hybrid_forward`函数中添加额外的输入`F`。我们知道,MXNet既有基于命令式编程的NDArray类,又有基于符号式编程的Symbol类。由于这两个类的函数基本一致,MXNet会根据输入来决定`F`使用NDArray或Symbol。下面创建了一个HybridBlock实例。可以看到默认下`F`使用NDArray。而且,我们打印出了输入`x`和使用ReLU激活函数的隐藏层的输出。
net = HybridNet() net.initialize() x = nd.random.normal(shape=(1, 4)) net(x)
F: <module 'mxnet.ndarray' from '/var/lib/jenkins/miniconda2/envs/d2l-zh-build/lib/python3.6/site-packages/mxnet/ndarray/__init__.py'> x: [[-0.12225834 0.5429998 -0.9469352 0.59643304]] <NDArray 1x4 @cpu(0)> hidden: [[0.11134676 0.04770704 0.05341475 0. 0.08091211 0. 0. 0.04143535 0. ...
Apache-2.0
chapter_computational-performance/hybridize.ipynb
femj007/d2l-zh
再运行一次前向计算会得到同样的结果。
net(x)
F: <module 'mxnet.ndarray' from '/var/lib/jenkins/miniconda2/envs/d2l-zh-build/lib/python3.6/site-packages/mxnet/ndarray/__init__.py'> x: [[-0.12225834 0.5429998 -0.9469352 0.59643304]] <NDArray 1x4 @cpu(0)> hidden: [[0.11134676 0.04770704 0.05341475 0. 0.08091211 0. 0. 0.04143535 0. ...
Apache-2.0
chapter_computational-performance/hybridize.ipynb
femj007/d2l-zh
接下来看看调用`hybridize`函数后会发生什么。
net.hybridize() net(x)
F: <module 'mxnet.symbol' from '/var/lib/jenkins/miniconda2/envs/d2l-zh-build/lib/python3.6/site-packages/mxnet/symbol/__init__.py'> x: <Symbol data> hidden: <Symbol hybridnet0_relu0>
Apache-2.0
chapter_computational-performance/hybridize.ipynb
femj007/d2l-zh
可以看到,`F`变成了Symbol。而且,虽然输入数据还是NDArray,但`hybrid_forward`函数里,相同输入和中间输出全部变成了Symbol类型。再运行一次前向计算看看。
net(x)
_____no_output_____
Apache-2.0
chapter_computational-performance/hybridize.ipynb
femj007/d2l-zh
Comprehensions: Documentation: https://python-3-patterns-idioms-test.readthedocs.io/en/latest/Comprehensions.html Situation: - We have one or more sources of iterable data. Need: - We want to do something with that data, and output it into a list, dictionary or generator format. Solution: - Python offers a cleaner/...
even_squares = [] for num in range(11): if num%2 == 0: even_squares.append(num * num) even_squares # Can we do better than the above? even_squares = [num*num for num in range(11) if num%2 == 0] even_squares
_____no_output_____
MIT
notebooks/Comprehensions.ipynb
deepettas/advanced-python-workshop
List comprehension Pattern:![alt text](https://miro.medium.com/max/1716/1*xUhlknsL6rR-s_DcVQK7kQ.png) [Figure reference](https://towardsdatascience.com/comprehending-the-concept-of-comprehensions-in-python-c9dafce5111) We can do the same with dictionaries, or generators:
first_names = ['Mark', 'Demmis', 'Elon', 'Jeff', 'Lex'] last_names = ['Zuckerberg','Hasabis', 'Musk','Bezos','Fridman'] full_names = {} for first, last in zip(first_names, last_names): full_names[first] = last full_names full_names = {first: last for first, last in zip(first_names, last_names)} full_names # ...
_____no_output_____
MIT
notebooks/Comprehensions.ipynb
deepettas/advanced-python-workshop
How about a generator?Like a comprehension but waits, and yields each item out of the expression, one by one.
# even_squares was [0, 4, 16, 36, 64, 100] with the list comprehension # generator equivallent even_squares = (num*num for num in range(11) if num%2 == 0) next(even_squares)
_____no_output_____
MIT
notebooks/Comprehensions.ipynb
deepettas/advanced-python-workshop
AI 전략경영MBA 경영자를 위한 딥러닝 원리의 이해 Perceptron 실습 예제 붓꽃 분류 문제 The original code comes from Sebastian Reschka's blog (http://sebastianraschka.com/Articles/2015_singlelayer_neurons.html).Slightly modified for the lecture. -skimaza 라이브러리 import- numpy: number, 특히 다차원 배열을 다루는 라이브러리(패키지)- pandas: 데이터를 다양한 표 형태로 취급할 수 있는 패키지- m...
import numpy as np import pandas as pd import matplotlib.pyplot as plt
_____no_output_____
MIT
perceptron_Iris.ipynb
skimaza/assist
Colab으로 배정된 가상머신 확인 현재 디렉토리(폴더) '!'로 시작하는 명령은 가상머신의 명령을 실행하라는 의미
!pwd
/content
MIT
perceptron_Iris.ipynb
skimaza/assist
현재 디렉토리의 내용
!ls -l
total 12 -rw-r--r-- 1 root root 4551 Sep 22 01:24 iris.dat drwxr-xr-x 1 root root 4096 Sep 16 13:40 sample_data
MIT
perceptron_Iris.ipynb
skimaza/assist
sample_data directory에는 Google Colab에서 기본으로 제공하는 데이터가 있음 (이번 특강에서 사용할 데이터는 아님)
!ls sample_data
anscombe.json mnist_test.csv california_housing_test.csv mnist_train_small.csv california_housing_train.csv README.md
MIT
perceptron_Iris.ipynb
skimaza/assist
예제 코드
weights = [] errors_log = [] epochs = 20 eta = 0.01 IRIS_DATA = "iris.dat" # Iris 데이터셋을 저장할 파일이름
_____no_output_____
MIT
perceptron_Iris.ipynb
skimaza/assist
os는 운영체제 관련 기능, urllib는 인터넷으로 데이터를 다운로드받기 위한 패키지 인터넷에서 Iris 데이터셋을 다운로드하여 IRIS_DATA 파일에 저장
import os from urllib.request import urlopen if not os.path.exists(IRIS_DATA): raw = urlopen('https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data').read() with open(IRIS_DATA, "wb") as f: f.write(raw) !ls -l
total 12 -rw-r--r-- 1 root root 4551 Sep 22 01:24 iris.dat drwxr-xr-x 1 root root 4096 Sep 16 13:40 sample_data
MIT
perceptron_Iris.ipynb
skimaza/assist
pandas의 read_csv 명령을 사용하여 데이터를 pandas DataFrame 구조로 읽어들임
df = pd.read_csv(IRIS_DATA, header=None) df
_____no_output_____
MIT
perceptron_Iris.ipynb
skimaza/assist
꽃받침 길이, 꽃받침 너비, 꽃잎 길이, 꽃잎 너비 (cm), 붓꽃 종류
df[4].values df.iloc[0:100, 4] df.iloc[0:100, 4].values # setosa and versicolor y = np.asarray(df.iloc[0:100, 4].values) y = np.where(y == 'Iris-setosa', -1, 1) # sepal length and petal length X = np.asarray(df.iloc[0:100, [0,2]].values) print(y) print(X) # Versicolor pos = X[[y == 1]] # Setosa neg = X[[y == -1]] prin...
[-0.04 -0.07 0.184]
MIT
perceptron_Iris.ipynb
skimaza/assist
$w_{1}x_{1} + w_{2}x_{2} + w_{0} = 0$ $x_{2} = - \frac{w_{1}}{w_{2}}x_{1} - \frac{w_{0}}{w_{2}}$
fig = plt.figure() ax = fig.add_subplot(111) # draw between 4 and 7 of x1 point_x = np.array([4, 7]) # x2 = -(w0 + w1 * x1) / w2 point_y = np.array([- (weights[0] + weights[1] * 4) / weights[2], - (weights[0] + weights[1] * 7) / weights[2]]) line, = ax.plot(point_x, point_y, 'b-', picker=5) ax.scatter(pos[:,0], pos[...
_____no_output_____
MIT
perceptron_Iris.ipynb
skimaza/assist
_Lambda School Data Science — Classification & Validation_ Baselines & ValidationObjectives- Train/Validate/Test split- Cross-Validation- Begin with baselines Weather data — mean baselineLet's try baselines for regression.You can [get Past Weather by Zip Code from Climate.gov](https://www.climate.gov/maps-data/datas...
%matplotlib inline import matplotlib.pyplot as plt import pandas as pd url = 'https://raw.githubusercontent.com/LambdaSchool/DS-Unit-2-Sprint-3-Classification-Validation/master/module2-baselines-validation/weather-normal-il.csv' weather = pd.read_csv(url, parse_dates=['DATE']).set_index('DATE') weather['2014-05':'201...
_____no_output_____
MIT
module2-baselines-validation/LS_DS_232_Baselines_Validation.ipynb
damerei/DS-Unit-2-Sprint-3-Classification-Validation
Over the years, across the seasons, the average daily high temperature in my town is about 63 degrees.
weather['TMAX'].mean()
_____no_output_____
MIT
module2-baselines-validation/LS_DS_232_Baselines_Validation.ipynb
damerei/DS-Unit-2-Sprint-3-Classification-Validation
Remember from [the preread:](https://github.com/LambdaSchool/DS-Unit-2-Sprint-3-Classification-Validation/blob/master/module2-baselines-validation/model-validation-preread.mdwhat-does-baseline-mean) "A baseline for regression can be the mean of the training labels." If I predicted that every day, the high will be 63 de...
from sklearn.metrics import mean_absolute_error predicted = [weather['TMAX'].mean()] * len(weather) mean_absolute_error(weather['TMAX'], predicted)
_____no_output_____
MIT
module2-baselines-validation/LS_DS_232_Baselines_Validation.ipynb
damerei/DS-Unit-2-Sprint-3-Classification-Validation
But, we can get a better baseline here: "A baseline for time-series regressions can be the value from the previous timestep."*Data Science for Business* explains, > Weather forecasters have two simple—but not simplistic—baseline models that they compare against. ***One (persistence) predicts that the weather tomorrow i...
weather['TMAX_yesterday'] = weather.TMAX.shift(1) weather = weather.dropna() # Drops the first date, because it doesn't have a "yesterday" mean_absolute_error(weather.TMAX, weather.TMAX_yesterday)
_____no_output_____
MIT
module2-baselines-validation/LS_DS_232_Baselines_Validation.ipynb
damerei/DS-Unit-2-Sprint-3-Classification-Validation
I applied this same concept for [my first submission to the Kaggle Instacart competition.](https://github.com/rrherr/springboard/blob/master/Kaggle%20Instacart%20first%20submission.ipynb) Bank Marketing — majority class baselinehttps://archive.ics.uci.edu/ml/datasets/Bank+Marketing>The data is related with direct mark...
!wget https://archive.ics.uci.edu/ml/machine-learning-databases/00222/bank-additional.zip !unzip bank-additional.zip bank = pd.read_csv('bank-additional/bank-additional-full.csv', sep=';')
_____no_output_____
MIT
module2-baselines-validation/LS_DS_232_Baselines_Validation.ipynb
damerei/DS-Unit-2-Sprint-3-Classification-Validation
Assign to X and y
X = bank.drop(columns='y') y = bank['y'] == 'yes'
_____no_output_____
MIT
module2-baselines-validation/LS_DS_232_Baselines_Validation.ipynb
damerei/DS-Unit-2-Sprint-3-Classification-Validation
3-way split: Train / Validation / Test We know how to do a _two-way split_, with the [**`sklearn.model_selection.train_test_split`**](https://scikit-learn.org/stable/modules/generated/sklearn.model_selection.train_test_split.html) function:
from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split( X, y, test_size=0.2, random_state=42, stratify=y)
_____no_output_____
MIT
module2-baselines-validation/LS_DS_232_Baselines_Validation.ipynb
damerei/DS-Unit-2-Sprint-3-Classification-Validation
How can we get from a two-way split, to a three-way split?We can use the same function again, to split the training data into training and validation data.
X_train, X_val, y_train, y_val = train_test_split( X_train, y_train, test_size=0.3, random_state=42, stratify=y_train) X_train.shape, X_val.shape, X_test.shape, y_train.shape, y_val.shape, y_test.shape
_____no_output_____
MIT
module2-baselines-validation/LS_DS_232_Baselines_Validation.ipynb
damerei/DS-Unit-2-Sprint-3-Classification-Validation
Majority class baseline Determine the majority class:
y_train.value_counts(normalize=True)
_____no_output_____
MIT
module2-baselines-validation/LS_DS_232_Baselines_Validation.ipynb
damerei/DS-Unit-2-Sprint-3-Classification-Validation
What if we guessed the majority class for every prediction?
majority_class = y_train.mode()[0] y_pred = [majority_class] * len(y_val)
_____no_output_____
MIT
module2-baselines-validation/LS_DS_232_Baselines_Validation.ipynb
damerei/DS-Unit-2-Sprint-3-Classification-Validation
[`sklearn.metrics.accuracy_score`](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.accuracy_score.html)Baseline accuracy by guessing the majority class for every prediction:
from sklearn.metrics import accuracy_score accuracy_score(y_val, y_pred)
_____no_output_____
MIT
module2-baselines-validation/LS_DS_232_Baselines_Validation.ipynb
damerei/DS-Unit-2-Sprint-3-Classification-Validation
[`sklearn.metrics.roc_auc_score`](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.roc_auc_score.html)Baseline "ROC AUC" score by guessing the majority class for every prediction:
from sklearn.metrics import roc_auc_score roc_auc_score(y_val, y_pred)
_____no_output_____
MIT
module2-baselines-validation/LS_DS_232_Baselines_Validation.ipynb
damerei/DS-Unit-2-Sprint-3-Classification-Validation
Fast first models Ignore rows/columns with nulls Does this dataset have nulls?
X_train.isnull().sum()
_____no_output_____
MIT
module2-baselines-validation/LS_DS_232_Baselines_Validation.ipynb
damerei/DS-Unit-2-Sprint-3-Classification-Validation
Ignore nonnumeric features Here are the numeric features:
X_train.describe(include='number')
_____no_output_____
MIT
module2-baselines-validation/LS_DS_232_Baselines_Validation.ipynb
damerei/DS-Unit-2-Sprint-3-Classification-Validation
Here are the nonnumeric features:
X_train.describe(exclude='number')
_____no_output_____
MIT
module2-baselines-validation/LS_DS_232_Baselines_Validation.ipynb
damerei/DS-Unit-2-Sprint-3-Classification-Validation
Just select the nonnumeric features:
X_train_numeric = X_train.select_dtypes('number') X_val_numeric = X_val.select_dtypes('number')
_____no_output_____
MIT
module2-baselines-validation/LS_DS_232_Baselines_Validation.ipynb
damerei/DS-Unit-2-Sprint-3-Classification-Validation
Shallow trees are good for fast, first baselines, and to look for "leakage" Shallow trees After naive baselines, *Data Science for Business* suggests ["decision stumps."](https://en.wikipedia.org/wiki/Decision_stump)> A slightly more complex alternative is a model that only considers a very small amount of feature in...
from sklearn.tree import DecisionTreeClassifier tree = DecisionTreeClassifier(max_depth=2) tree.fit(X_train_numeric,y_train) y_pred_proba = tree.predict_proba(X_val_numeric)[:,1] roc_auc_score(y_val, y_pred_proba)
_____no_output_____
MIT
module2-baselines-validation/LS_DS_232_Baselines_Validation.ipynb
damerei/DS-Unit-2-Sprint-3-Classification-Validation
Then we can visualize the tree to see which feature(s) were the "most informative":
import graphviz from sklearn.tree import export_graphviz dot_data = export_graphviz(tree, out_file=None, feature_names=X_train_numeric.columns, class_names=['No', 'Yes'], filled=True, impurity=False, proportion=True) graphviz.Source(dot_data)
_____no_output_____
MIT
module2-baselines-validation/LS_DS_232_Baselines_Validation.ipynb
damerei/DS-Unit-2-Sprint-3-Classification-Validation
This baseline has a ROC AUC score above 0.85, and it uses the `duration` feature, as well as `nr.employed`, a "social and economic context attribute" for "number of employees - quarterly indicator." Let's drop the `duration` feature
X_train = X_train.drop(columns='duration') X_val = X_val.drop(columns='duration') X_test = X_test.drop(columns='duration') X_train_numeric = X_train.select_dtypes('number') X_val_numeric = X_val_numeric.select_dtypes('number')
_____no_output_____
MIT
module2-baselines-validation/LS_DS_232_Baselines_Validation.ipynb
damerei/DS-Unit-2-Sprint-3-Classification-Validation
When the `duration` feature is dropped, then the ROC AUC score drops. Which is what we expect, it's not a bad thing in this situation!
tree = DecisionTreeClassifier(max_depth=2) tree.fit(X_train_numeric,y_train) y_pred_proba = tree.predict_proba(X_val_numeric)[:,1] roc_auc_score(y_val, y_pred_proba) dot_data = export_graphviz(tree, out_file=None, feature_names=X_train_numeric.columns, class_names=['No', 'Yes'], filled=True,...
_____no_output_____
MIT
module2-baselines-validation/LS_DS_232_Baselines_Validation.ipynb
damerei/DS-Unit-2-Sprint-3-Classification-Validation
Logistic RegressionLogistic Regression is another great option for fast, first baselines!
from sklearn.linear_model import LogisticRegression model = LogisticRegression(solver='lbfgs', max_iter=1000) model.fit(X_train_numeric,y_train) y_pred_proba = model.predict_proba(X_val_numeric)[:,1] roc_auc_score(y_val,y_pred_proba)
_____no_output_____
MIT
module2-baselines-validation/LS_DS_232_Baselines_Validation.ipynb
damerei/DS-Unit-2-Sprint-3-Classification-Validation
With Scalerhttps://scikit-learn.org/stable/modules/preprocessing.html
import warnings from sklearn.exceptions import DataConversionWarning warnings.filterwarnings(action='ignore', category=DataConversionWarning) from sklearn.preprocessing import StandardScaler scaler = StandardScaler() X_train_scaled = scaler.fit_transform(X_train_numeric) X_val_scaled = scaler.transform(X_val_numeric...
_____no_output_____
MIT
module2-baselines-validation/LS_DS_232_Baselines_Validation.ipynb
damerei/DS-Unit-2-Sprint-3-Classification-Validation
Same, as a pipeline
from sklearn.pipeline import make_pipeline pipeline = make_pipeline( StandardScaler(), LogisticRegression(solver='lbfgs',max_iter=1000)) pipeline.fit(X_train_numeric,y_train) y_pred_proba = pipeline.predict_proba(X_val_numeric)[:,1]
_____no_output_____
MIT
module2-baselines-validation/LS_DS_232_Baselines_Validation.ipynb
damerei/DS-Unit-2-Sprint-3-Classification-Validation
Encode "low cardinality" categoricals [Cardinality](https://simple.wikipedia.org/wiki/Cardinality) means the number of unique values that a feature has:> In mathematics, the cardinality of a set means the number of its elements. For example, the set A = {2, 4, 6} contains 3 elements, and therefore A has a cardinality ...
!pip install category_encoders import category_encoders as ce pipeline = make_pipeline( ce.OneHotEncoder(use_cat_names=True), StandardScaler(), LogisticRegression(solver='lbfgs', max_iter=1000)) pipeline.fit(X_train,y_train) y_pred_proba = pipeline.predict_proba(X_val)[:,1] roc_auc_score(y_val,y_pred_proba)
Collecting category_encoders [?25l Downloading https://files.pythonhosted.org/packages/6e/a1/f7a22f144f33be78afeb06bfa78478e8284a64263a3c09b1ef54e673841e/category_encoders-2.0.0-py2.py3-none-any.whl (87kB)  |████████████████████████████████| 92kB 5.9MB/s [?25hRequirement already satisfied: numpy>=1.11.3 in /...
MIT
module2-baselines-validation/LS_DS_232_Baselines_Validation.ipynb
damerei/DS-Unit-2-Sprint-3-Classification-Validation