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 of Deep Learning, Natural Language Processing currently has a great deal of buzz surrounding it, and for good reason. The goal of this post is to do three things:1. Inspire the reader with the beauty of the problem of NLP2. Explain how machine learning techniques (i.e. something as simple as Logistic Regression) can be applied to text data.3. Prepare the reader for the next sections surrounding Deep Learning as it is applied to NLP.Before we dive in, I would like to share the poem _Jabberwocky_ by Lewis Carrol, and an accompanying excerpt from the book "_Godel, Escher, Bach_", by Douglas Hofstadter.And now, the corresponding excerpt, _**Translations of Jabberwocky**_. > Translations of JabberwockyDouglas R. HofstadterImagine native speakers of English, French, and German, all of whom have excellent command of their respective native languages, and all of whom enjoy wordplay in their own language. Would their symbol networks be similar on a local level, or on a global level? Or is it meaningful to ask such a question? The question becomes concrete when you look at the preceding translations of Lewis Carroll's famous "Jabberwocky".[The "preceding translations" were "Jabberwocky" (English, original), by Lewis Carroll, "Le Jaseroque", (French), by Frank L. Warrin, and "Der Jammerwoch" (German), by Robert Scott. --kl]I chose this example because it demonstrates, perhaps better than an example in ordinary prose, the problem of trying to find "the same node" in two different networks which are, on some level of analysis, extremely nonisomorphic. In ordinary language, the task of translation is more straightforward, since to each word or phrase in the original language, there can usually be found a corresponding word or phrase in the new language. By contrast, in a poem of this type, many "words" do not carry ordinary meaning, but act purely as exciters of nearby symbols. However, what is nearby in one language may be remote in another.Thus, in the brain of a native speaker of English, "slithy" probably activates such symbols as "slimy", "slither", "slippery", "lithe", and "sly", to varying extents. Does "lubricilleux" do the corresponding thing in the brain of a Frenchman? What indeed would be "the corresponding thing"? Would it be to activate symbols which are the ordinary translations of those words? What if there is no word, real or fabricated, which will accomplish that? Or what if a word does exist, but it is very intellectual-sounding and Latinate ("lubricilleux"), rather than earthy and Anglo-Saxon ("slithy")? Perhaps "huilasse" would be better than "lubricilleux"? Or does the Latin origin of the word "lubricilleux" not make itself felt to a speaker of French in the way that it would if it were an English word ("lubricilious", perhaps)?An interesting feature of the translation into French is the transposition into the present tense. To keep it in the past would make some unnatural turns of phrase necessary, and the present tense has a much fresher flavour in French than in the past. The translator sensed that this would be "more appropriate"--in some ill-defined yet compelling sense--and made the switch. Who can say whether remaining faithful to the English tense would have been better?In the German version, the droll phrase "er an-zu-denken-fing" occurs; it does not correspond to any English original. It is a playful reversal of words, whose flavour vaguely resembles that of the English phrase "he out-to-ponder set", if I may hazard a reverse translation. Most likely this funny turnabout of words was inspired by the similar playful reversal in the English of one line earlier: "So rested he by the Tumtum tree". It corresponds, yet doesn't correspond.Incidentally, why did the Tumtum tree get changed into an "arbre Té-té" in French? Figure it out for yourself.The word "manxome" in the original, whose "x" imbues it with many rich overtones, is weakly rendered in German by "manchsam", which back-translates into English as "maniful". The French "manscant" also lacks the manifold overtones of "manxome". There is no end to the interest of this kind of translation task.When confronted with such an example, one realizes that it is utterly impossible to make an exact translation. Yet even in this pathologically difficult case of translation, there seems to be some rough equivalence obtainable. Why is this so, if there really is no isomorphism between the brains of people who will read the different versions? The answer is that there is a kind of rough isomorphism, partly global, partly local, between the brains of all the readers of these three poems.Now, the purpose of sharing the above is because if you are reading these posts (and are anything like me), you may very well spend a large chunk of your time studying mathematics, computer science, machine learning, writing code, and so on. But, if you are new to NLP the appreciation for the beauty and deeper meaning surrounding language may not be on the forefront of your mind-that is understandable! But hopefully the passage and commentary above ignited some interest in the wonderfully complex and worthwhile problem of Natural Language Processing and Understanding. 2. Spam DetectionNow, especially at first, I don't want to dive into phonemes, morphemes, syntactical structure, and the like. We will leave those linguistic concepts for later on. The goal here is to quickly allow someone with an understanding of basic machine learning algorithms and techniques to implement them in the domain of NLP. We will see that, at least at first, a lot of NLP deals with preprocessing data, which allows us to use algorithms that we already know. The question that most definitely arises is: How do we take a bunch of documents which are basically a bunch of text, and feed them into other machine learning algorithms where the input is usually a vector of numbers? Well, before we even get to that, let's take a preprocessed data set from the [uci archive](https://archive.ics.uci.edu/ml/datasets/Spambase) and perform a simple classification on it. The data has been processed in such a way that we can consider columns 1-48 to the be the input, and column 49 to the be label (1 = spam, 0 = not spam). The input columns are considered the input, and they are a **word frequency measure**. This measure can be calculated via:$$\text{Word Frequency Measure} = \frac{\text{ of times word appears in a document}}{\text{Number of words in document}} * 100$$This will result in a **Document Term matrix**, which is a matrix where _terms_ (words that appeared in the document) go along the columns, and _documents_ (emails in this case) go along the rows:| |word 1|word 2|word 3|word 4|word 5|word 6|word 7|word 8||-------|------|------|------|------|------|------|------|------||Email 1||||||||||Email 2||||||||||Email 3||||||||||Email 4||||||||||Email 5||||||||| 2.1 Implementation in CodeWe will now use `Scikit Learn` to show that we can use _any_ model on NLP data, as long as it has been preprocessed correctly. First, let's use scikit learns `NaiveBayes` classifier:
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 = X[-100:,] Ytest = Y[-100:,] model = MultinomialNB() model.fit(Xtrain, Ytrain) print ("Classifcation Rate for NB: ", model.score(Xtest, Ytest))
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 steps that are frequently used when performing machine learning on text data (often referred to an NLP pipeline) we are going to want to work on the problem of **sentiment analysis**. Sentiment is a measure of how positive or negative something is, and we are going to build a very simple sentiment analyzer to predict the sentiment of Amazon reviews. These are reviews, so they come with 5 star ratings, and we are going to look at the electronics category in particular. These are XML files, so we will need an XML parser. 3.1 NLP Terminology Before we begin, I would just like to quickly go over some basic NLP terminology that will come up frequently throughout this post.* **Corpus**: Collection of text* **Tokens**: Words and punctuation that make up the corpus. * **Type**: a distinct token. Ex. "Run, Lola Run" has four tokens (comma counts as one) and 3 types.* **Vocabulary**: The set of all types. * The google corpus (collection of text) has 1 trillion tokens, and only 13 million types. English only has 1 million dictionary words, but the google corpus includes types such as "www.facebook.com". 3.2 Problem OverviewNow, we are just going to be looking at the electronics category. We could use the 5 star targets to do regression, but instead we will just do classification since they are already marked "positive" and "negative". As I mentioned, we are going to be working with XML data, so we will need an XML parser, for which we will use `BeautifulSoup`. We will only look at the `review_text` attribute. To create our feature vector, we will count up the number of occurences of each word, and divided it by the total number of words. However, for that to work we will need two passes through the data:1. One to collect the total number of distinct words, so that we know the size of our feature vector, in other words the vocabulary size, and possibly remove stop words like "this", "is", "I", "to", etc, to decrease the vocabulary size. The goal here is to know the index of each token2. On the second pass, we will be able to assign values to each data vector whose index corresponds to which words, and one to create data vectors Once we have that, it is simply a matter of creating a classifier like the one we did for our spam detector! Here, we will use logistic regression, so we can intepret the weights! For example, if you see a word like horrible and it has a weight of minus 1, it is associated with negative reviews. With that started, let's begin! 3.3 Sentiment Analysis in Code
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('../../data/nlp/stopwords.txt')) # grab stop words # get pos reviews # only want rev text positive_reviews = BeautifulSoup(open('../../data/nlp/electronics/positive.review').read(), "lxml") positive_reviews = positive_reviews.findAll('review_text') negative_reviews = BeautifulSoup(open('../../data/nlp/electronics/negative.review').read(), "lxml") negative_reviews = negative_reviews.findAll('review_text')
_____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 tokens = [t for t in tokens if t not in stopwords] return tokens
_____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 just the set of all types!We are essentially going to look at every individual review, tokenize them, and then add those tokens 1 by 1 to the map if they do not exist yet.
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 in positive_reviews: tokens = my_tokenizer(review.text) # converts single review into array of tokens (split function) positive_tokenized.append(tokens) for token in tokens: # loops through array of tokens for specific review if token not in word_index_map: # if the token is not in the map, add it word_index_map[token] = current_index current_index += 1 # increment current index # --------- loop through negative reviews --------- for review in negative_reviews: tokens = my_tokenizer(review.text) negative_tokenized.append(tokens) for token in tokens: if token not in word_index_map: word_index_map[token] = current_index current_index += 1
_____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 on **one** review. So the +1 is creating our label, and this function is basically designed to take our input vector from an english form to a numeric vector form.
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 xy_data[i] += 1 # increment data at that index xy_data = xy_data / xy_data.sum() # divide entire array by total, so they add to 1 xy_data[-1] = label # set last element to label return xy_data
_____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 positive_tokenized: # loop through postive tokenized reviews xy = tokens_to_vector(tokens, 1) # passing in 1 because these are pos reviews data[i,:] = xy # set data row to that of the input vector i += 1 # increment 1 for tokens in negative_tokenized: xy = tokens_to_vector(tokens, 0) data[i,:] = xy i += 1 print(data.shape)
(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_weights.sort(reverse=True, key=sort_by_magnitude) print(large_magnitude_weights)
[('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), ('little', 0.9262682823592787), ('fast', 0.905207610856845), ('speaker', 0.8965845758701319), ('ha', 0.8111001120921802), ('pretty', 0.7764302324793534), ('cable', 0.7712191036378001), ("'ve", 0.7170298751638035), ('week', -0.7194449455694366), ('returned', -0.7482471935264389), ('bad', -0.7542948554985326), ('poor', -0.7555447694156194), ('tried', -0.7892866982929136), ('buy', -0.8504195601103998), ('month', -0.8771148641617261), ('support', -0.9163137326943319), ('waste', -0.946863186564699), ('item', -0.9518247418299971), ('money', -1.1086664158434432), ('return', -1.1512973579906935), ('then', -1.2084513223482118), ('doe', -1.2197007105871698), ('wa', -1.6630639259918825), ("n't", -2.0687949024413546)]
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 correlate to a negative response. --- 4. NLTK Exploration Before we move on any further, I wanted to take a minute to go over a few of the most useful tools for the `nltk` (Natural Language Toolkit) library. This library will encapsulate many NLP tasks for us. 4.1 Parts of Speech (POS) TaggingParts of speech tagging is meant to do just what it sound like: tag each word with a given part of speech within a document. For example, in the following sentence:> "Bob is great."`Bob` is a noun, `is` is a verb, and `great` is an adjective. We can utilize `nltk`'s POS tagger on that sentence and see the same result:
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 used in reducing words to a "base" form. This is very useful because a vocabulary can get very large, while certain words tend to have the same meaning. For example _dog_ and _dogs_, and _jump_ and _jumping_ both have similar meanings. The main difference between stemming and lemmatization is that stemming is a bit more basic.
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_ word with _multiple_ meanings. These are referred to as _synonomy_ and _polysemy_ respectively. In the case of synonyms here are a few basic examples:* "Buy" and "Purchase"* "Big" and "Large"* "Quick" and "Speedy"And in the case of polysemes:* "Man" (man as in human, and man as in a male opposed to a female)* "Milk" (can be a noun or a verb)In order to solve this problem, we will need to introduce _Latent Variables_. 5.1 Latent VariablesThe easiest way to get your head around latent variables at first is via an example. Consider the words "computer", "laptop", and "PC"; these words are most likely seen together very often, meaning they are highly correlated. We can thinking a _latent_ or _hidden_ variable that is below representing them all, and we can call that $z$. We can mathematically define $z$ as:$$z = 0.7*computer \; + 0.5*PC \; + 0.6*laptop$$So, we now have an idea of what a latent variable is, but what is the job of Latent Semantic Analysis? The entire goal of LSA is:1. To find the latent/hidden variables.2. Then, transform original data into these new variables. Ideally, after the above has been performed, the dimensionality of the new data will be much smaller than that of the original data set. It is important to note that LSA definitely helps solve the synonomy problem, by combining correlated variables. However, there are conflicting view points about whether or not it helps with polysemy. 5.2 The Math Behind LSAAs we just discussed, the main goal when applying LSA is to deal with synonyms. For example, "small" and "little" would each make up their own unique variable, but in reality we know that they mean the same thing, so that is redundant. We could combine them into a single variable, reducing the dimensionality of our data set by one. So, to be clear the goal of LSA is:> **Goal of LSA**: Reduce redundancy. 5.2.1 Redundancy in NumbersNow, machine learning at its core is always dealing with numbers, so what exactly do I mean by redundancy from a numerical standpoint? Take a look at the the plot below:We can see clearly that there is a linear relationship between the dependent and independent variable. In other words, there is a linear relationship between lean body mass and muscle strength. So, we could say that one of these variables is redundant; if we know someones lean body mass, we can accurately predict their muscle strength, and vice versa. If we want a compact representation of attributes related to someones athletic performance, then we may only need to know one of these variables, since the other can be predicted from it. This advantage becomes more apparent as our dimensionality grows; if we could go from 1 million variables down to variables, that is a 200,000x's savings of space! Saving space is good, and hence reducing redundancy is good! Now the math behind LSA is rather complex and involves a good deal of linear algebra, and to be honest it would slightly bloat this notebook if I placed it here. Because of this, I have decided to move it to my mathematics section under linear algebra. With that said, LSA is essentially just the application of **Singular Value Decomposition** (SVD) to a term document matrix. I highly encourage you to go over my notebook explaining SVD and PCA before continuing, to have a better understanding of how the underlying mechanics work in the code we are about to implement. Now, we can begin by gaining a brief bit of intuition behind what LSA may look like in code. As usual, we are going to begin with an input matrix `X` of shape $NxD$, where $N$ is the number of samples and $D$ is the number of features. This will be passed into scikit learns svd model, `TruncatedSVD`, call the `fit`, `transform` function, and finally receive an output matrix `Z` of shape $Nx2$, or $Nxd$, where $d << D$. ```model = TruncatedSVD()model.fit(X)Z = model.transform(X) equivalent: Z = model.fit_transform(X)``` 5.3 LSA in Code
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 of Buddhism',...]```* we then define our tokenizer which will convert our list of strings into specific tokens, which will look like:```[['philosophy', 'sex', 'love', 'reader'], ['reading', 'judaism', 'christianity', 'islam'], ['microprocessor', 'principle'], ['bernhard', 'edouard', 'fernow', 'story', 'north', 'american', 'forestry'], ['encyclopedia', 'buddhism'],```* we then create our input matrix. This is going to be D x N, where D is the length of the total number of terms we are using (input features, 2070) and where N is the length of all tokens (2373, the total number of titles)* This is essentially the transpose of how our input matrix is generally setup. Usually we have our examples along the rows, and our input features along the columns, however, in NLP it is sometimes the opposite* we then loop through all tokens, and create a vector for each one (essentially, if a word occurs, its value in the vector is incremented by 1)* the final input matrix is fed into the SVD, where the X matrix is transformed into a Z matrix of only 2 dimensions
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({ 'introduction', 'edition', 'series', 'application', 'approach', 'card', 'access', 'package', 'plus', 'etext', 'brief', 'vol', 'fundamental', 'guide', 'essential', 'printed', 'third', 'second', 'fourth', }) # adding additional stop words 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 tokens = [t for t in tokens if t not in stopwords] # remove stop words tokens = [t for t in tokens if not any(c.isdigit() for c in t)] # get rid of any token that includes a number return tokens # Lets now figure out the index of each word, by going through the entire vocabularly # create a word-to-index map so that we can create our word-frequency vectors later # let's also save the tokenized versions so we don't have to tokenize again later word_index_map = {} current_index = 0 all_tokens = [] all_titles = [] index_word_map = [] error_count = 0 for title in titles: try: title = title.encode('ascii', 'ignore').decode('utf-8') # this will throw exception if bad characters all_titles.append(title) tokens = my_tokenizer(title) all_tokens.append(tokens) for token in tokens: if token not in word_index_map: word_index_map[token] = current_index current_index += 1 index_word_map.append(token) except Exception as e: print(e) print(title) error_count += 1 # now let's create our input matrices - just indicator variables for this example - works better than proportions def tokens_to_vector(tokens): x = np.zeros(len(word_index_map)) for t in tokens: i = word_index_map[t] x[i] = 1 return x N = len(all_tokens) # nested list, has 2373 total entries, each which has several words D = len(word_index_map) # total number of words that we are working with (2070) X = np.zeros((D, N)) # terms will go along rows, documents along columns i = 0 for tokens in all_tokens: X[:,i] = tokens_to_vector(tokens) i += 1 def main(): fig, ax = plt.subplots(figsize=(12,8)) svd = TruncatedSVD() Z = svd.fit_transform(X) plt.scatter(Z[:,0], Z[:,1]) for i in range(D): plt.annotate(s=index_word_map[i], xy=(Z[i,0], Z[i,1])) plt.show() if __name__ == '__main__': main()
_____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 broken down into a few discrete steps:* Upload your data to S3.* Define a binary classification model and a training script.* Train your model and deploy it.* Evaluate your deployed classifier and answer some questions about your approach.To complete this notebook, you'll have to complete all given exercises and answer all the questions in this notebook.> All your tasks will be clearly labeled **EXERCISE** and questions as **QUESTION**.It will be up to you to explore different classification models and decide on a model that gives you the best performance for this dataset.--- Load Data to S3In the last notebook, you should have created two files: a `training.csv` and `test.csv` file with the features and class labels for the given corpus of plagiarized/non-plagiarized text data. >The below cells load in some AWS SageMaker libraries and creates a default bucket. After creating this bucket, you can upload your locally stored data to S3.Save your train and test `.csv` feature files, locally. To do this you can run the second notebook "2_Plagiarism_Feature_Engineering" in SageMaker or you can manually upload your files to this notebook using the upload icon in Jupyter Lab. Then you can upload local files to S3 by using `sagemaker_session.upload_data` and pointing directly to where the training data is saved.
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 the required parameters. It may help to look at the [Session documentation](https://sagemaker.readthedocs.io/en/stable/session.htmlsagemaker.session.Session.upload_data) or previous SageMaker code examples.You are expected to upload your entire directory. Later, the training script will only access the `train.csv` file.
# 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 delete via the S3 console (though, additional files shouldn't affect the performance of model developed in this notebook).
""" 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/output/model.tar.gz boston-xgboost-HL/test.csv boston-xgboost-HL/train.csv boston-xgboost-HL/validation.csv boston-xgboost-LL/batch-bransform/test.csv.out boston-xgboost-LL/output/boston-xgboost-2020-10-05-08-45-40/output/model.tar.gz boston-xgboost-LL/test.csv boston-xgboost-LL/train.csv boston-xgboost-LL/validation.csv counties/kmeans-2020-10-12-15-19-49-497/output/model.tar.gz counties/kmeans-2020-10-12-16-12-40-795/output/model.tar.gz counties/pca-2020-10-12-11-38-56-130/output/model.tar.gz counties/pca-2020-10-12-12-36-11-407/output/model.tar.gz fraund_detection/linear-learner-2020-10-13-16-25-53-808/output/model.tar.gz fraund_detection/linear-learner-2020-10-13-18-26-50-429/output/model.tar.gz fraund_detection/linear-learner-2020-10-13-18-57-22-416/output/model.tar.gz fraund_detection/linear-learner-2020-10-13-19-27-34-058/output/model.tar.gz fraund_detection/linear-learner-2020-10-13-19-52-03-257/output/model.tar.gz fraund_detection/linear-learner-2020-10-13-20-12-26-687/output/model.tar.gz fraund_detection/linear-learner-2020-10-13-20-33-19-916/output/model.tar.gz fraund_detection/linear-learner-2020-10-13-20-40-04-004/output/model.tar.gz fraund_detection/linear-learner-2020-10-13-21-00-43-603/output/model.tar.gz fraund_detection/linear-learner-2020-10-14-08-57-57-060/output/model.tar.gz lambda.zip lambda_panda_layer-835b6e94-93de-4e5d-abda-4586b6b7f69d.zip moon-data/sagemaker-pytorch-2020-10-15-11-44-11-502/debug-output/training_job_end.ts moon-data/sagemaker-pytorch-2020-10-15-11-44-11-502/output/model.tar.gz moon-data/sagemaker-pytorch-2020-10-15-12-19-41-161/debug-output/training_job_end.ts moon-data/sagemaker-pytorch-2020-10-15-12-19-41-161/output/model.tar.gz moon-data/sagemaker-pytorch-2020-10-15-12-37-52-303/output/model.tar.gz moon-data/sagemaker-pytorch-2020-10-15-12-55-13-731/debug-output/training_job_end.ts moon-data/sagemaker-pytorch-2020-10-15-12-55-13-731/output/model.tar.gz python.zip python3.zip sagemaker-pytorch-2020-10-23-18-08-26-412/source/sourcedir.tar.gz sagemaker-pytorch-2020-10-23-18-14-07-463/source/sourcedir.tar.gz sagemaker-pytorch-2020-10-23-18-19-37-689/source/sourcedir.tar.gz sagemaker-record-sets/KMeans-2020-10-12-15-19-36-131/.amazon.manifest sagemaker-record-sets/KMeans-2020-10-12-15-19-36-131/matrix_0.pbr sagemaker-record-sets/LinearLearner-2020-10-13-16-12-30-860/.amazon.manifest sagemaker-record-sets/LinearLearner-2020-10-13-16-12-30-860/matrix_0.pbr sagemaker-record-sets/LinearLearner-2020-10-13-16-25-36-894/.amazon.manifest sagemaker-record-sets/LinearLearner-2020-10-13-16-25-36-894/matrix_0.pbr sagemaker-record-sets/LinearLearner-2020-10-13-18-26-27-878/.amazon.manifest sagemaker-record-sets/LinearLearner-2020-10-13-18-26-27-878/matrix_0.pbr sagemaker-record-sets/PCA-2020-10-12-11-29-48-805/.amazon.manifest sagemaker-record-sets/PCA-2020-10-12-11-29-48-805/matrix_0.pbr sagemaker-record-sets/PCA-2020-10-12-12-36-08-957/.amazon.manifest sagemaker-record-sets/PCA-2020-10-12-12-36-08-957/matrix_0.pbr sagemaker-scikit-learn-2020-10-20-13-20-22-809/debug-output/training_job_end.ts sagemaker-scikit-learn-2020-10-20-13-20-22-809/output/model.tar.gz sagemaker-scikit-learn-2020-10-20-13-20-22-809/source/sourcedir.tar.gz sagemaker-scikit-learn-2020-10-23-17-25-30-271/source/sourcedir.tar.gz sagemaker-scikit-learn-2020-10-23-17-32-58-378/source/sourcedir.tar.gz sagemaker-scikit-learn-2020-10-23-17-40-45-279/source/sourcedir.tar.gz sagemaker-scikit-learn-2020-10-23-17-52-31-242/source/sourcedir.tar.gz sagemaker-scikit-learn-2020-10-23-18-02-22-277/debug-output/training_job_end.ts sagemaker-scikit-learn-2020-10-23-18-02-22-277/output/model.tar.gz sagemaker-scikit-learn-2020-10-23-18-02-22-277/source/sourcedir.tar.gz sagemaker/energy_consumption/forecasting-deepar-2020-10-15-20-57-08-845/output/model.tar.gz sagemaker/energy_consumption/test.json sagemaker/energy_consumption/train.json sagemaker/moon-data/train.csv sagemaker/plagiarism-detection/pytorch/output/sagemaker-pytorch-2020-10-19-20-24-35-558/debug-output/training_job_end.ts sagemaker/plagiarism-detection/pytorch/output/sagemaker-pytorch-2020-10-19-20-24-35-558/output/model.tar.gz sagemaker/plagiarism-detection/pytorch/output/sagemaker-pytorch-2020-10-19-20-47-37-049/debug-output/training_job_end.ts sagemaker/plagiarism-detection/pytorch/output/sagemaker-pytorch-2020-10-19-20-47-37-049/output/model.tar.gz sagemaker/plagiarism-detection/pytorch/output/sagemaker-pytorch-2020-10-19-21-08-53-391/debug-output/training_job_end.ts sagemaker/plagiarism-detection/pytorch/output/sagemaker-pytorch-2020-10-19-21-08-53-391/output/model.tar.gz sagemaker/plagiarism-detection/pytorch/output/sagemaker-pytorch-2020-10-23-18-19-37-689/debug-output/training_job_end.ts sagemaker/plagiarism-detection/pytorch/output/sagemaker-pytorch-2020-10-23-18-19-37-689/output/model.tar.gz sagemaker/plagiarism-detection/test.csv sagemaker/plagiarism-detection/train.csv sagemaker/sentiment_rnn/train.csv sagemaker/sentiment_rnn/word_dict.pkl sample-site-packages-2016-02-20.zip sentiment-web-app/output/xgboost-2020-10-07-14-49-14-975/output/model.tar.gz sentiment-web-app/test.csv sentiment-web-app/train.csv sentiment-web-app/validation.csv sklearn-build-lambda-master.zip sklearn.zip sklearn1.zip Test passed!
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 comparison of models can be found [here](https://scikit-learn.org/stable/auto_examples/classification/plot_classifier_comparison.html).* Define a custom PyTorch neural network classifier. It will be up to you to test out a variety of models and choose the best one. Your project will be graded on the accuracy of your final model. --- EXERCISE: Complete a training script To implement a custom classifier, you'll need to complete a `train.py` script. You've been given the folders `source_sklearn` and `source_pytorch` which hold starting code for a custom Scikit-learn model and a PyTorch model, respectively. Each directory has a `train.py` training script. To complete this project **you only need to complete one of these scripts**; the script that is responsible for training your final model.A typical training script:* Loads training data from a specified directory* Parses any training & model hyperparameters (ex. nodes in a neural network, training epochs, etc.)* Instantiates a model of your design, with any specified hyperparams* Trains that model * Finally, saves the model so that it can be hosted/deployed, later Defining and training a modelMuch of the training script code is provided for you. Almost all of your work will be done in the `if __name__ == '__main__':` section. To complete a `train.py` file, you will:1. Import any extra libraries you need2. Define any additional model training hyperparameters using `parser.add_argument`2. Define a model in the `if __name__ == '__main__':` section3. Train the model in that same sectionBelow, you can use `!pygmentize` to display an existing `train.py` file. Read through the code; all of your tasks are marked with `TODO` comments. **Note: If you choose to create a custom PyTorch model, you will be responsible for defining the model in the `model.py` file,** and a `predict.py` file is provided. If you choose to use Scikit-learn, you only need a `train.py` file; you may import a classifier from the `sklearn` library.
# 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 sklearn.externals import joblib from skorch import NeuralNetRegressor from model import BinaryClassifier from sklearn.model_selection import GridSearchCV #from sklearn.svm import LinearSVC ## TODO: Import any additional libraries you need to define a model #Begin Yanfei's first try# #from sklearn.svm import LinearSVC #End Yanfei's first try# #Begin Yanfei's second try# from sklearn.linear_model import LogisticRegression #Begin Yanfei's second try# # Provided model load function def model_fn(model_dir): """Load model from the model_dir. This is the same model that is saved  in the main if statement.  """ print("Loading model.") # load using joblib model = joblib.load(os.path.join(model_dir, "model.joblib")) print("Done loading model.") return model ## TODO: Complete the main code if __name__ == '__main__': # All of the model parameters and training parameters are sent as arguments # when this script is executed, during a training job # Here we set up an argument parser to easily access the parameters parser = argparse.ArgumentParser() # SageMaker parameters, like the directories for training data and saving models; set automatically # Do not need to change parser.add_argument('--output-data-dir', type=str, default=os.environ['SM_OUTPUT_DATA_DIR']) parser.add_argument('--model-dir', type=str, default=os.environ['SM_MODEL_DIR']) parser.add_argument('--data-dir', type=str, default=os.environ['SM_CHANNEL_TRAIN']) ## TODO: Add any additional arguments that you will need to pass into your model parser.add_argument('--random_state', type=int, default=0, metavar='N', help='int, RandomState instance, default=0') parser.add_argument('--solver', type=str, default='lbfgs', metavar='S', help='Possible values: {newton-cg, lbfgs, liblinear, sag, saga}, default is lbfgs') parser.add_argument('--multi_class', type=str, default='ovr', metavar='S', help='Possible values: {auto, ovr, multinomial}, default is ovr') # args holds all passed-in arguments args = parser.parse_args() # Read in csv training file training_dir = args.data_dir train_data = pd.read_csv(os.path.join(training_dir, "train.csv"), header=None, names=None) # Labels are in the first column train_y = train_data.iloc[:,0] train_x = train_data.iloc[:,1:] ## --- Your code here --- ## ## TODO: Define a model  #Begin Yanfei's first try# #model=LinearSVC() #End Yanfei's first try# net = NeuralNetRegressor(BinaryClassifier(args.input_features,args.hidden_dim,args.output_dim) , max_epochs=100 , lr=0.001 , verbose=1) #Begin Yanfei's second try# model = LogisticRegression(random_state=args.random_state, solver=args.solver, multi_class=args.multi_class) #End Yanfei's first try# params = { 'lr': [0.001,0.005, 0.01, 0.05, 0.1, 0.2, 0.3], 'max_epochs': list(range(500,5500, 500)) } ## TODO: Train the model # model.fit(train_x,train_y) #model = GridSearchCV(net, params, refit=False, scoring='r2', verbose=1, cv=10) model.fit(train_x, train_y) ## --- End of your code --- ## # Save the trained model joblib.dump(model, os.path.join(args.model_dir, "model.joblib"))
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 read more about model saving with [joblib for sklearn](https://scikit-learn.org/stable/modules/model_persistence.html) or with [torch.save](https://pytorch.org/tutorials/beginner/saving_loading_models.html), click on the provided links. --- Create an EstimatorWhen a custom model is constructed in SageMaker, an entry point must be specified. This is the Python file which will be executed when the model is trained; the `train.py` function you specified above. To run a custom training script in SageMaker, construct an estimator, and fill in the appropriate constructor arguments:* **entry_point**: The path to the Python script SageMaker runs for training and prediction.* **source_dir**: The path to the training script directory `source_sklearn` OR `source_pytorch`.* **entry_point**: The path to the Python script SageMaker runs for training and prediction.* **source_dir**: The path to the training script directory `train_sklearn` OR `train_pytorch`.* **entry_point**: The path to the Python script SageMaker runs for training.* **source_dir**: The path to the training script directory `train_sklearn` OR `train_pytorch`.* **role**: Role ARN, which was specified, above.* **train_instance_count**: The number of training instances (should be left at 1).* **train_instance_type**: The type of SageMaker instance for training. Note: Because Scikit-learn does not natively support GPU training, Sagemaker Scikit-learn does not currently support training on GPU instance types.* **sagemaker_session**: The session used to train on Sagemaker.* **hyperparameters** (optional): A dictionary `{'name':value, ..}` passed to the train function as hyperparameters.Note: For a PyTorch model, there is another optional argument **framework_version**, which you can set to the latest version of PyTorch, `1.0`. EXERCISE: Define a Scikit-learn or PyTorch estimatorTo import your desired estimator, use one of the following lines:```from sagemaker.sklearn.estimator import SKLearn``````from sagemaker.pytorch import PyTorch```
# 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_point="train.py", source_dir="source_sklearn", role=role, train_instance_count=1, train_instance_type='ml.c4.xlarge' )
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 deploy a trained model, you'll use `.deploy`, which takes in two arguments:* **initial_instance_count**: The number of deployed instances (1).* **instance_type**: The type of SageMaker instance for deployment.Note: If you run into an instance error, it may be because you chose the wrong training or deployment instance_type. It may help to refer to your previous exercise code to see which types of instances we used.
%%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', # source_dir='source_sklearn') # deploy your model to create a predictor predictor = estimator.deploy(initial_instance_count=1, instance_type='ml.m4.xlarge')
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 use [sklearn.metrics](https://scikit-learn.org/stable/modules/classes.htmlmodule-sklearn.metrics) for this calculation.**To pass this project, your model should get at least 90% test accuracy.**
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 predictions.' print('Test passed!') # Second: calculate the test accuracy accuracy = None # calculate true positives, false positives, true negatives, false negatives tp = np.logical_and(test_y.values, test_y_preds).sum() fp = np.logical_and(1-test_y.values, test_y_preds).sum() tn = np.logical_and(1-test_y.values, 1-test_y_preds).sum() fn = np.logical_and(test_y.values, 1-test_y_preds).sum() # calculate binary classification metrics recall = tp / (tp + fn) precision = tp / (tp + fp) accuracy = (tp + tn) / (tp + fp + tn + fn) print(f'tp:{tp} fp:{fp} tn:{tn} fn:{fn}') print(accuracy) ## print out the array of predicted and true labels, if you want print('\nPredicted class labels: ') print(test_y_preds) print('\nTrue class labels: ') print(test_y.values)
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 Classfier "LogisticRegression", we have one false positive. Case 3, when use selected_features ['c_1','c_11', 'lcs_word'], and Classfier "LogisticRegression", we have one false positive. The accuary is always 0.96. Because of the testset is only 25, not big data and not large amount of features, the performance between different classfier is not observed yet. If the noise is higher, maybe the accuray will be less than 0.96. we can't Use SKLearn Classifier like "LinearSVC", "LogisticRegression" have better accuary compared to Pytorch self-defined binary classifier.
#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=1) predict_df.columns=['c_11', 'lcs_word', 'predicted class','true class'] predict_df #Case 3 Check: predict_df = pd.concat([pd.DataFrame(test_x), pd.DataFrame(test_y_preds), pd.DataFrame(test_y)], axis=1) predict_df.columns=['c_1','c_11', 'lcs_word', 'predicted class','true class'] predict_df
_____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 more complex classifiers like SVM or Neural Network for massive dataset and huge size of features.
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('sagemaker-runtime') response = runtime.invoke_endpoint(EndpointName = predictor.endpoint, # The name of the endpoint we created ContentType = 'text/csv', # The data format that is expected Body ='0.0,0.7914438502673797,0.8207547169811321\n0.0,0.0,0\n' ) #test_file.getvalue() ) a=response['Body'].read().decode('utf-8') eval(a)[0]
_____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 on cleaning up all your resources, below.
# 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('Already deleted: {}'.format(predictor.endpoint)) delete_endpoint(predictor)
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) # rick.bk(100) # rick.back(100) ## move to the left rick.left(90) rick.forward(100) ## move to the right rick.right(90) rick.forward(100) screen.exitonclick()
_____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(90) t.left(90) t.exitonclick() ## Adding motions into the screen ##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() #Change turtle shape rick.shape('turtle') ## Change pen size rick.pensize(5) rick.forward(100) ## Change pen color rick.pencolor('blue') rick.left(90) rick.forward(100) ## change turtle color rick.color('red') rick.left(90) rick.forward(100) ## Multiple Turtle rick2 = t.Turtle() # ##penup # rick2.penup() # rick2.bk(100) # ##pendown # rick2.pendown() # rick2.left(90) # rick2.fd(100) ## Resize a turtle # rick.shapesize(2,2,0) #width, length, outline # rick.forward(100) # rick.shapesize(0.5,0.5,0) # rick.forward(100) rick2.penup() rick2.setposition(-100,-100) ## hide turtle rick2.pendown() rick2.hideturtle() rick2.forward(100) ## show turtle rick2.showturtle() rick2.left(90) rick2.forward(100) screen.exitonclick()
_____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(90) border.hideturtle() #set up player player = t.Turtle() player.color('blue') player.shape('triangle') player.penup() ## set up Goal goal = t.Turtle() goal.color('red') goal.shape('circle') goal.penup() goal.setpos(-100,100) speed = 1 ## Define Function def turnleft(): player.lt(30) def turnright(): player.rt(30) def speed5(): global speed speed = 5 def speed1(): global speed speed = 1 ##keyboard Binding t.listen() t.onkey(turnleft, 'Left') t.onkey(turnright, 'Right') t.onkeypress(speed5, 'Up') t.onkeyrelease(speed1, 'Up') while True: player.forward(speed) d = np.sqrt((player.xcor()-goal.xcor())**2 +(player.ycor()-goal.ycor())**2) if d<20: goal.setpos(random.randint(-300,300) ,random.randint(-300,300))
_____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 = {'endpoint_url':"http://192.168.0.29", } client = s3fs.S3FileSystem(key="AKIAPo19vPR_TJaeVgleCiOSUw", secret="7cSWM1KCXvRpK4ICeDEAfuicEm+QQeuhqOi7cejZ", use_ssl=False, client_kwargs=kwargs) my_bucket = s3.Bucket("sample-dataset") map_labels = {"Apple___Apple_scab":0, "Apple___Black_rot":1, "Apple___Cedar_apple_rust":2, "Apple___healthy":3, "Background_without_leaves":4}
_____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 file in client.ls(directory)][1:] self.transform = transform def __len__(self): return len(self.files) def __getitem__(self, idx): img_name = self.files[idx] label = img_name.split("/")[-2] label = map_labels[label] key = img_name.split("/") key = "/".join(key[1:]) img_name = my_bucket.Object(key).get().get('Body').read() image = cv2.imdecode(np.asarray(bytearray(img_name)), cv2.COLOR_BGR2RGB) image = Image.fromarray(image) if self.transform: image = self.transform(image) label = torch.tensor(label).long() return image, label data_dir = client.glob("s3://sample-dataset/sample_data")[0] train_transforms = transforms.Compose([transforms.RandomRotation(30), transforms.RandomResizedCrop(224), transforms.RandomHorizontalFlip(), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) val_transforms = transforms.Compose([transforms.Resize(255), transforms.CenterCrop(224), transforms.ToTensor(), transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])]) train_dataset = ImageDataset(path="s3://sample-dataset/sample_data/train", transform=train_transforms) valid_dataset = ImageDataset(path="s3://sample-dataset/sample_data/val", transform=val_transforms) train_loader = DataLoader(train_dataset, batch_size=16, shuffle=True, num_workers=0) val_loader = DataLoader(valid_dataset, batch_size=16, shuffle=False, num_workers=0) dataiter = iter(train_loader) images, labels = dataiter.next() print(type(images)) print(images.shape) print(labels.shape) def imshow(image, ax=None, normalize=True): if ax is None: fig, ax = plt.subplots() image = image.numpy().transpose((1, 2, 0)) if normalize: # if the data loader has transform.normalize # undo preprocessing mean = np.array([0.485, 0.456, 0.406]) std = np.array([0.229, 0.224, 0.225]) image = std * image + mean image = np.clip(image, 0, 1) ax.imshow(image) ax.spines['top'].set_visible(False) ax.spines['right'].set_visible(False) ax.spines['left'].set_visible(False) ax.spines['bottom'].set_visible(False) ax.tick_params(axis='both', length=0) ax.set_xticklabels('') ax.set_yticklabels('') return ax imshow(images[1]); imshow(images[8]); imshow(images[12]); model = models.densenet201(pretrained=True) for param in model.parameters(): param.required_grad = False # change the classifier from collections import OrderedDict classifier = nn.Sequential(OrderedDict([ ('fc1', nn.Linear(1920, 500)), ('relu1', nn.ReLU()), ('dropout1', nn.Dropout(p=0.2)), ('fc2', nn.Linear(500, 256)), ('relu2', nn.ReLU()), ('dropout2', nn.Dropout(p=0.2)), ('fc3', nn.Linear(256, 5)), ('output', nn.LogSoftmax(dim=1)) ])) model.classifier = classifier # Train either on GPU or CPU device = torch.device("cuda" if torch.cuda.is_available() else "cpu") criterion = nn.NLLLoss() optimizer = optim.SGD(model.classifier.parameters(), lr = 0.01, momentum=0.9) model.to(device) epochs = 1 for epoch in range(epochs): running_loss = 0 for images, labels in train_loader: images, labels = images.to(device), labels.to(device) optimizer.zero_grad() outputs = model(images) loss = criterion(outputs, labels) loss.backward() optimizer.step() running_loss += loss.item() else: validation_loss = 0 accuracy = 0 with torch.no_grad(): model.eval() for images, labels in val_loader: images, labels = images.to(device), labels.to(device) outputs = model(images) loss = criterion(outputs, labels) validation_loss += loss.item() ps = torch.exp(outputs) top_p, top_class = ps.topk(1, dim=1) equals = top_class == labels.view(*top_class.shape) accuracy += torch.mean(equals.type(torch.FloatTensor)) model.train() print("Epoch: {}/{}.. ".format(epoch+1, epochs), "Training Loss: {:.3f}.. ".format(running_loss/len(train_loader)), "Valid Loss: {:.3f}.. ".format(validation_loss/len(val_loader)), "Valid Accuracy: {:.3f}".format(accuracy/len(val_loader))) #map classes to indexes model.class_to_idx = map_labels # save model s3_client = boto3.client("s3", endpoint_url = "http://192.168.0.29", aws_access_key_id="AKIAPo19vPR_TJaeVgleCiOSUw", aws_secret_access_key="7cSWM1KCXvRpK4ICeDEAfuicEm+QQeuhqOi7cejZ", ) buffer = io.BytesIO() torch.save({"state_dict":model.state_dict(), "class_to_idx":model.class_to_idx}, buffer) s3_client.put_object(Bucket="saved-models", Key='classifier.pth', Body=buffer.getvalue())
_____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.join("imgs", "bird2.png"))), [pygame.transorm.scale2x(pygame.image.load(os.path.join("imgs", "bird3.png")))] PIPE_IMG = pygame.transform.scale2x(pygame.image.load(os.path.join("imgs", "pipe.png"))) BASE_IMG = pygame.transform.scale2x(pygame.image.load(os.path.join("imgs", "base.png"))) BG_IMG = pygame.transform.scale2x(pygame.image.load(os.path.join("imgs", "bg.png"))) #Object Classes class Bird: IMGS = BIRD_IMGS MAX_ROTATION = 25 ROT_VEL = 20 ANIMATION_TIME = 5 def __init__(self, x, y): self.x = x self.y = y self.tilt = 0 self.tick_count = 0 self.vel = 0 self,height = self.y self.img_count = 0 self.img = self.IMGS[0] def jump(self): self.vel = -10.5 self.tick_count = 0 self.height = self.y def move(self): self.tick_count += 1 d = self.vel*self.tick_count + 1.5*self.tick_count**2 if d >= 16: d = 16 if d < 0: d-=2.4 self.y = self.y + de if d < 0 or self.y < self.height + 50: if self.tilt < self.MAX_ROTATION: self.tilt = MAX_ROTATION else: if self.tilt> -90: self.tilt -= self.ROT_VEL def draw(self, win): self.img_count +=1 if self.img_count < self.ANIMATION_TIME: self.img = self.IMGS[0] elif self.img_count < self.ANIMATION_TIME*2: self.img = self.IMGS[1] elif self.img_count < self.ANIMATION_TIME*3: self.img = self.IMGS[2] elif self.img_count < self.ANIMATION_TIME*4: self.img = self.IMGS[1] elif self.img_count < self.ANIMATION_TIME*4+1: self.img = self.IMGS[0] self.img_count = 0 if self.tilt <= -80: self.img = self.IMGS[1] self.img_count = self.ANIMATION_TIME*2 rotated_image = pygame.transorm.rotate(self.img, self.tilt) new_rect = rotated_image.get_rect(center=self.img.get_rect(topleft = (self.x, self.y)).center) win.blit(rotated_image, new_rect.topleft) def get_mask(self): return pygame.mask.from_surface(self.img) def draw_window(win, bird): win.blit(BG_IMG, (0,0)) bird.draw(win) pygame.display.update() def main(): bird = Bird(200,200) win = pygame.display.set_mode((WIN_WIDTH, WIN_HEIGHT)) run = True while run: for event in pygame.event.get(): if event.type == pygame.QUIT: run == False draw_window(win, bird) pygame.quit() quit() main()
_____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 = openpifpaf.decoder.factory([hn.meta for hn in net_cpu.head_nets])
_____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 right and bottom of the image that the feature map does not cover.
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 accessible from the command line: use `--debug-indices cif:5 caf:5` to select which joints and connections to visualize.
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, images_batch, device=device)[0]
_____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`是否会被程序的其他部分使用。与命令式编程不同,符号式编程通常在计算流程完全定义好后才被执行。多个深度学习框架,例如Theano和TensorFlow,都使用了符号式编程。通常,符号式编程的程序需要下面三个步骤:1. 定义计算流程;2. 把计算流程编译成可执行的程序;3. 给定输入,调用编译好的程序执行。下面我们用符号式编程重新实现本节开头给出的命令式编程代码。
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() print(prog) y = compile(prog, '', 'exec') exec(y)
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的排错工具。* 符号式编程更高效并更容易移植。一方面,在编译的时候系统容易做更多优化;另一方面,符号式编程可以将程序变成一个与Python无关的格式,从而可以使程序在非Python环境下运行,以避开Python解释器的性能问题。 混合式编程取两者之长大部分的深度学习框架在命令式编程和符号式编程之间二选一。例如Theano和受其启发的后来者TensorFlow使用了符号式编程;Chainer和它的追随者PyTorch使用了命令式编程。开发人员在设计Gluon时思考了这个问题:有没有可能既得到命令式编程的好处,又享受符号式编程的优势?开发者们认为,用户应该用纯命令式编程进行开发和调试;当需要产品级别的计算性能和部署时,用户可以将大部分程序转换成符号式来运行。Gluon通过提供混合式编程做到了这一点。在混合式编程中,我们可以通过使用HybridBlock类或者HybridSequential类构建模型。默认情况下,它们和Block或者Sequential类一样依据命令式编程的方式执行。当我们调用`hybridize`函数后,Gluon会转换成依据符号式编程的方式执行。事实上,绝大多数模型都可以享受这样的混合式编程的执行方式。本节将通过实验展示混合式编程的魅力。 使用HybridSequential类构造模型我们之前学习了如何使用Sequential类来串联多个层。为了使用混合式编程,下面我们将Sequential类替换成HybridSequential类。
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=(1, 512)) net = get_net() net(x)
_____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('hidden: ', x) return self.output(x)
_____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. 0. ]] <NDArray 1x10 @cpu(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. 0. ]] <NDArray 1x10 @cpu(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/faster way of working without using traditional for loops.----- Example: - Lets take a traditional for loop
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 # len(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: 데이터를 다양한 표 형태로 취급할 수 있는 패키지- matplotlib: 이미지와 그래프 표시
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]] print(pos) print(neg) # versicolor with blue dots and setosa with red dots plt.scatter(pos[:,0], pos[:, 1], color='blue', label="pos") plt.scatter(neg[:,0], neg[:, 1], color='red', label="neg") plt.xlabel("x1") plt.ylabel("x2") plt.legend(loc=2, scatterpoints=1, fontsize=10) def train(X, y, epochs=epochs, eta=eta): global weights global errors_log weights = np.zeros(1 + X.shape[1]) print("Initial weights", weights) errors_log = [] for i in range(epochs): errors = 0 print("EPOCHS", i+1) for xi, target in zip(X, y): update = eta * (target - predict(xi)) #print(xi, "target", target, "sum", net_input(xi), "update", update) if update != 0: weights[1:] += update * xi weights[0] += update print("Updated WEIGHTS", weights) errors += int(update != 0.0) errors_log.append(errors) return def net_input(X): global weights return np.dot(X, weights[1:]) + weights[0] def predict(X): return np.where(net_input(X) > 0.0, 1, -1) train(X, y) print(errors_log) print(weights)
[-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[:, 1], color='blue', label="pos") ax.scatter(neg[:,0], neg[:, 1], color='red', label="neg") plt.xlabel("x1") plt.ylabel("x2") plt.legend(loc=2, scatterpoints=1, fontsize=10) plt.show()
_____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/dataset/past-weather-zip-code-data-table). I downloaded the data for my town: Normal, Illinois.
%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':'2019-05'].plot(y='TMAX') plt.title('Daily high temperature in Normal, IL');
_____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 degrees, I'd be off by about 19 degrees on average.
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 is going to be whatever it was today.*** The other (climatology) predicts whatever the average historical weather has been on this day from prior years. Each model performs considerably better than random guessing, and both are so easy to compute that they make natural baselines of comparison. Any new, more complex model must beat these. Let's predict that the weather tomorrow is going to be whatever it was today. Which is another way of saying that the weather today is going to be whatever it was yesterday.We can engineer this feature with one line of code, using the pandas [`shift`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.shift.html) function.This new baseline is off by less than 6 degress on average.
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 marketing campaigns of a Portuguese banking institution. The marketing campaigns were based on phone calls. Often, more than one contact to the same client was required, in order to access if the product (bank term deposit) would be ('yes') or not ('no') subscribed. >Output variable (desired target): >y - has the client subscribed a term deposit? (binary: 'yes','no')>bank-additional-full.csv with all examples (41188) and 20 inputs, ordered by date (from May 2008 to November 2010) Get and read the data
!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 information. ...> One example is to build a "decision stump"—a decision tree with only one internal node, the root node. A tree limited to one internal node simply means that the tree induction selects the single most informative feature to make a decision. In a well-known paper in machine learning, [Robert Holte (1993)](https://link.springer.com/article/10.1023/A:1022631118932) showed that ***decision stumps often produce quite good baseline performance*** ...> A decision stump is an example of the strategy of ***choosing the single most informative piece of information*** available and basing all decisions on it. In some cases most of the leverage may be coming from a single feature, and this method assesses whether and to what extent this is the case.To fit a "decision stump" we could use a [`DecisionTreeClassifier`](http://scikit-learn.org/stable/modules/generated/sklearn.tree.DecisionTreeClassifier.html) model with parameter `max_depth=1`.In this case, we'll let our tree grow a little deeper, and use the parameter `max_depth=2`In the previous code cell, we selected only the numeric features, to avoid data wrangling and save time. For now, we'll use only the numeric features. Looking for leakage [Xavier Amatriain recommends,](https://www.quora.com/What-are-some-best-practices-for-training-machine-learning-models/answer/Xavier-Amatriain)"Make sure your training features do not contain data from the “future” (aka time traveling). While this might be easy and obvious in some cases, it can get tricky. ... If your test metric becomes really good all of the sudden, ask yourself what you might be doing wrong. Chances are you are time travelling or overfitting in some way." We can test this with the [UCI repository's Bank Marketing dataset](https://archive.ics.uci.edu/ml/datasets/Bank+Marketing). It has a feature which leaks information from the future and should be dropped:>11 - duration: last contact duration, in seconds (numeric). Important note: this attribute highly affects the output target (e.g., if duration=0 then y='no'). Yet, the duration is not known before a call is performed. Also, after the end of the call y is obviously known. Thus, this input ... should be discarded if the intention is to have a realistic predictive model. Let's train a shallow tree basline... without dropping the leaky `duration` feature.
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, 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
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) model = LogisticRegression(solver='lbfgs', max_iter=1000) model.fit(X_train_scaled, y_train) y_pred_proba = model.predict_proba(X_val_scaled)[:,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
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 of 3. One-hot encoding adds a dimension for each unique value of each categorical feature. So, it may not be a good choice for "high cardinality" categoricals that have dozens, hundreds, or thousands of unique values. In this dataset, all the categoricals seem to be "low cardinality", so we can use one-hot encoding.
!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 /usr/local/lib/python3.6/dist-packages (from category_encoders) (1.16.3) Requirement already satisfied: scikit-learn>=0.20.0 in /usr/local/lib/python3.6/dist-packages (from category_encoders) (0.20.3) Requirement already satisfied: statsmodels>=0.6.1 in /usr/local/lib/python3.6/dist-packages (from category_encoders) (0.9.0) Requirement already satisfied: patsy>=0.4.1 in /usr/local/lib/python3.6/dist-packages (from category_encoders) (0.5.1) Requirement already satisfied: scipy>=0.19.0 in /usr/local/lib/python3.6/dist-packages (from category_encoders) (1.2.1) Requirement already satisfied: pandas>=0.21.1 in /usr/local/lib/python3.6/dist-packages (from category_encoders) (0.24.2) Requirement already satisfied: six in /usr/local/lib/python3.6/dist-packages (from patsy>=0.4.1->category_encoders) (1.12.0) Requirement already satisfied: python-dateutil>=2.5.0 in /usr/local/lib/python3.6/dist-packages (from pandas>=0.21.1->category_encoders) (2.5.3) Requirement already satisfied: pytz>=2011k in /usr/local/lib/python3.6/dist-packages (from pandas>=0.21.1->category_encoders) (2018.9) Installing collected packages: category-encoders Successfully installed category-encoders-2.0.0
MIT
module2-baselines-validation/LS_DS_232_Baselines_Validation.ipynb
damerei/DS-Unit-2-Sprint-3-Classification-Validation