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
You can also control the format of the date displayed on the screen. You can request just the day, month, year, hour, minutes and even seconds.
print('Day: ' + str(current_date.day)) print('Month: ' + str(current_date.month)) print('Year: ' + str(current_date.year))
Day: 5 Month: 6 Year: 2021
MIT
_jupyterNotebooks/python_tutorial/python_basics_1.ipynb
PranavShirole/PranavShirole.github.io
Sometimes, you can receive a date as a string, and you might need to store it as a date. You'll need to convert it to a `datetime` object.
birthday = input('When is your birthday (dd/mm/yyyy)? ') # the strptime function allows you to mention the # format in which you'll be receiving the date birthday_date = datetime.strptime(birthday, '%d/%m/%Y') print('Birthday: ' + str(birthday_date))
When is your birthday (dd/mm/yyyy)? 28/2/2000 Birthday: 2000-02-28 00:00:00
MIT
_jupyterNotebooks/python_tutorial/python_basics_1.ipynb
PranavShirole/PranavShirole.github.io
So what date was it three days before you were born?
birthday = input('When is your birthday (dd/mm/yyyy)? ') birthday_date = datetime.strptime(birthday, '%d/%m/%Y') print('Birthday: ' + str(birthday_date)) three_days = timedelta(days=3) three_before = birthday_date - three_days print('Date three days before birthday: ' + str(three_before))
When is your birthday (dd/mm/yyyy)? 28/2/2000 Birthday: 2000-02-28 00:00:00 Date three days before birthday: 2000-02-25 00:00:00
MIT
_jupyterNotebooks/python_tutorial/python_basics_1.ipynb
PranavShirole/PranavShirole.github.io
--- Error Handling *Error handling* is when you have a problem with your code that is running, and its not something that you're going to be able to predict when you push your code to production. For e.g., permissions issue, database change, server being down, etc. Basically things that happen in the wild, which you ha...
# this code won't run at all x = 35 y = 75 if x == y print('x = y')
_____no_output_____
MIT
_jupyterNotebooks/python_tutorial/python_basics_1.ipynb
PranavShirole/PranavShirole.github.io
We're missing a colon after `y`, which is why we're getting the error above. Runtime errorsWith runtime errors, your code will run, but it will fail when it encounters the error.
# this code will fail when run x = 5 y = 0 print(x / y)
_____no_output_____
MIT
_jupyterNotebooks/python_tutorial/python_basics_1.ipynb
PranavShirole/PranavShirole.github.io
We're trying to divide by zero, which is not possible. Python tells you why you're getting the error and points towards the line which needs to be fixed. It's good practice to start from the line mentioned and work your way up to the error. Runtime errors can also be caused due to an error in the framework you're using...
x = 5 y = 0 try: print(x / y) except ZeroDivisionError as e: print('Sorry, something went wrong') except: print('Something really went wrong') finally: print('This line always runs, on success or failure')
Sorry, something went wrong This line always runs, on success or failure
MIT
_jupyterNotebooks/python_tutorial/python_basics_1.ipynb
PranavShirole/PranavShirole.github.io
Logic errorsLogic errors occur when the code compiles properly, doesn't give any syntax or runtime errors, but it doesn't give you the response you're looking for.
# this code won't run at all x = 10 y = 20 if x > y: print(str(x) + ' is less than ' + str(y))
_____no_output_____
MIT
_jupyterNotebooks/python_tutorial/python_basics_1.ipynb
PranavShirole/PranavShirole.github.io
In the code above, `x` is less than `y`; but the `if` statement includes `x > y`, instead of `x < y`.When you're figuring out what went wrong with your code, just make sure that you reread your code. You can check the documentation and also search the internet on sites like StackOverflow and Medium. --- Handling Condit...
price = 250.0 if price >= 100.00: tax = 0.3 print(tax)
0.3
MIT
_jupyterNotebooks/python_tutorial/python_basics_1.ipynb
PranavShirole/PranavShirole.github.io
if - else statementYou can add a default action using `else`. An `else` statement contains the block of code that executes if the conditional expression in the `if` statement resolves to `0` or a `False` value.
price = 50 if price >= 100.00: tax = 0.3 else: tax = 0 print(tax)
0
MIT
_jupyterNotebooks/python_tutorial/python_basics_1.ipynb
PranavShirole/PranavShirole.github.io
Be careful when comparing strings. String comparisons are case sensitive.
country = 'INDIA' if country == 'india': print('Namaste') else: print('Hello') country = 'INDIA' if country.lower() == 'india': print('Namaste') else: print('Hello')
Namaste
MIT
_jupyterNotebooks/python_tutorial/python_basics_1.ipynb
PranavShirole/PranavShirole.github.io
if - elif - else statementYou may need to check multiple conditions to determine the correct action. The `elif` statement allows you to check multiple expressions for `True` and execute a block of cide as soon as one of the conditions evaluates to `True`.
# income tax percentage by state state = input('Which state do you live in? ') if state == 'Georgia': tax = 5.75 elif state == 'California': tax = 13.3 elif state == 'Texas' or state == 'Florida': tax = 0.0 else: tax = 4.0 print(tax)
Which state do you live in? Georgia 5.75
MIT
_jupyterNotebooks/python_tutorial/python_basics_1.ipynb
PranavShirole/PranavShirole.github.io
OR statements| first condition | second condition | evaluation | |-----------------|------------------|------------| |True |True |True | |True |False |True ||False |True |True | |False |False |False ...
# income tax rates by state state = input('Which state do you live in? ') if state in ('Texas', 'Florida', 'Alaska', 'Wyoming', 'South Dakota'): tax = 0.0 elif state == 'California': tax = 13.3 elif state == 'Georgia': tax = 5.75 else: tax = 4.0 print(tax)
Which state do you live in? Alaska 0.0
MIT
_jupyterNotebooks/python_tutorial/python_basics_1.ipynb
PranavShirole/PranavShirole.github.io
Nested if statementThere may be a situation when you want to check for another condition after a condition resolves to `True`. If an action depends on a combination of conditions, you can nest `if` statements.
country = input("What country do you live in? ") if country.lower() == 'canada': province = input("What province/state do you live in? ") if province in('Alberta', 'Nunavut','Yukon'): tax = 0.05 elif province == 'Ontario': tax = 0.13 else: tax = 0.15 else: tax = 0.0 print(ta...
What country do you live in? Canada What province/state do you live in? Ontario 0.13
MIT
_jupyterNotebooks/python_tutorial/python_basics_1.ipynb
PranavShirole/PranavShirole.github.io
Sometimes you can combine conditions with `and` instead of nested `if` statements. Let's assume that you're trying to calculate which students in a college have made the honor roll. The requirements for making the honor roll are a minimum 85% GPA and maintaining all your grades at at least 70%.
# convert strings into float gpa = float(input('What\'s your GPA? ')) lowest_grade = float(input('What was your lowest grade? ')) if gpa >= 0.85 and lowest_grade >= 0.7: print('You made the honor roll') else: print('You\'re really stupid')
What's your GPA? 0.8 What was your lowest grade? 0.75 You're really stupid
MIT
_jupyterNotebooks/python_tutorial/python_basics_1.ipynb
PranavShirole/PranavShirole.github.io
If you have a very complicated `if` statement, rather than copying and pasting it in different parts of you code to do different things, we can remember what happened the last time we looked at the `if` statement with a Boolean variable.
gpa = float(input('What\'s your GPA? ')) lowest_grade = float(input('What was your lowest grade? ')) if gpa >= 0.85 and lowest_grade >= 0.7: honor_roll = True else: honor_roll = False ''' Somewhere later in your code if you need to check if a student is on honor roll, all you need to do is check the boole...
What's your GPA? 0.9 What was your lowest grade? 0.87 You made the honor roll
MIT
_jupyterNotebooks/python_tutorial/python_basics_1.ipynb
PranavShirole/PranavShirole.github.io
--- Collections ListsLists are a collection of items.
# prepopulate a list names = ['John', 'Will', 'Max'] # start with an empty list scores = [] # add new item to the end scores.append(90) scores.append(91) print(names) print(scores) # lists are zero-indexed print(scores[1])
['John', 'Will', 'Max'] [90, 91] 91
MIT
_jupyterNotebooks/python_tutorial/python_basics_1.ipynb
PranavShirole/PranavShirole.github.io
You can get the number of items in a list using `len`.
names = ['John', 'Will', 'Max'] # get the number of items using len print(len(names))
3
MIT
_jupyterNotebooks/python_tutorial/python_basics_1.ipynb
PranavShirole/PranavShirole.github.io
You can insert an item in a list using `insert`. This will insert the item at the specific index that you mention.
# Bill will be inserted at index 0, i.e. the first item names.insert(0, 'Bill') print(names)
['Bill', 'John', 'Will', 'Max']
MIT
_jupyterNotebooks/python_tutorial/python_basics_1.ipynb
PranavShirole/PranavShirole.github.io
You can use `sort` to sort strings in alphabetical order. In case of numbers, it sorts them in the ascending order. Remember that using `sort` will modify the list!
names.sort() print(names)
['Bill', 'John', 'Max', 'Will']
MIT
_jupyterNotebooks/python_tutorial/python_basics_1.ipynb
PranavShirole/PranavShirole.github.io
You can retrieve a range within the list by indicating the start and end index; the end index being exclusive, i.e. it will not be included in the list.
names = ['Amy', 'Susan', 'Jackie', 'Kylie', 'Ellen'] # start and end index presenters = names[1:3] # all names up to but not including index 3 hosts = names[:3] # all names from 3 onwards, including index 3 judges = names[3:] print(names) print(presenters) print(hosts) print(judges)
['Amy', 'Susan', 'Jackie', 'Kylie', 'Ellen'] ['Susan', 'Jackie'] ['Amy', 'Susan', 'Jackie'] ['Kylie', 'Ellen']
MIT
_jupyterNotebooks/python_tutorial/python_basics_1.ipynb
PranavShirole/PranavShirole.github.io
ArraysArrays are a collection of numbered data types. Unlike a list, in order for you to use an array, you have to create an array object by importing it from the `array` library.
from array import array # indicate the numerical type you'll use scores = array('d') # d indicates a double scores.append(80) scores.append(81) print(scores) print(scores[0])
array('d', [80.0, 81.0]) 80.0
MIT
_jupyterNotebooks/python_tutorial/python_basics_1.ipynb
PranavShirole/PranavShirole.github.io
So what's the difference between an array and a list? Arrays are only numerical data types and everything inside the array must be of the same data type. They can help add extra structure to your code. Lists can store anything you want, can store any data type, and can have mixed data types. They give more flexibilit...
person = {'first': 'John'} person['last'] = 'Wick' print(person) print(person['first']) identity = { 'Batman': 'Bruce Wayne', 'Superman': 'Clark Kent', 'Spiderman': 'Peter Parker', 'Iron Man': 'Tony Stark' } print(identity)
{'Batman': 'Bruce Wayne', 'Superman': 'Clark Kent', 'Spiderman': 'Peter Parker', 'Iron Man': 'Tony Stark'}
MIT
_jupyterNotebooks/python_tutorial/python_basics_1.ipynb
PranavShirole/PranavShirole.github.io
When to use a dictionary vs a list?It depends on whether you want to name things and whether you want items to be in a guaranteed order. A dictionary will let you name key-value pairs but it does not guarantee you a specific order. A list does guarantee you a specific order since it has a zero-based index. --- Random...
import random # generate a random whole number between 1 and 50 # inclusive of 1 and 50 random_integer = random.randint(1, 50) print(random_integer) # generate a random floating point number between 0.0 and 1.0 # exclusive of 1.0 random_float = random.random() print(random_float) # generate a random floating point n...
0.6343084141143187 3.1715420705715935
MIT
_jupyterNotebooks/python_tutorial/python_basics_1.ipynb
PranavShirole/PranavShirole.github.io
There are so many more methods to the `random` module and you can check out the Python documentation to find out about all the things you can do with this module. --- LoopsLoops are a concept that is used when you need to have things happening over and over again. for loops`for` loops are used to loop through a collect...
# go through the list of names for name in ['John', 'Will', 'Max']: print(name) wildcats = ['lion', 'tiger', 'puma', 'jaguar', 'cheetah', 'leopard'] for wildcat in wildcats: print(wildcat + ' is a wildcat.')
lion is a wildcat. tiger is a wildcat. puma is a wildcat. jaguar is a wildcat. cheetah is a wildcat. leopard is a wildcat.
MIT
_jupyterNotebooks/python_tutorial/python_basics_1.ipynb
PranavShirole/PranavShirole.github.io
You can loop a particular number of times using `range`. `range` automatically creates a list of numbers for you. Remember that for the `range` function, the end index is exclusive.> `for number in range(a, b): do something print(number)`
# end index is exclusive for index in range(0, 5): print(index)
0 1 2 3 4
MIT
_jupyterNotebooks/python_tutorial/python_basics_1.ipynb
PranavShirole/PranavShirole.github.io
If you want the range to increase by any other number, you can add a step to the function after the starting and ending indices.
for index in range(0, 15, 3): print(index)
0 3 6 9 12
MIT
_jupyterNotebooks/python_tutorial/python_basics_1.ipynb
PranavShirole/PranavShirole.github.io
while loop`while` loops are used to loop with a condition. As long as something is `True`, the code will stay inside of the `while` loop i.e. the loop will continue going while the condition is true. You need to make sure that at some point you change the condition and it must result to `False`; otherwise the program ...
names = ['John', 'Will', 'Max'] index = 0 while index < len(names): print(names[index]) # change the condition index += 1 print(index) x = True while x: print('This is an example of a while loop.') # change the condition x = False while not x: print('This is another example of a whi...
This is an example of a while loop. This is another example of a while loop.
MIT
_jupyterNotebooks/python_tutorial/python_basics_1.ipynb
PranavShirole/PranavShirole.github.io
`for` loops are great when you want to iterate over something and you need to do something with each thing that you're iterating over. In cases like above, when you have a list, you almost always want use a `for` loop. `while` loops are useful when you don't care about the number in the sequence or about the item you'...
def my_function(): result = 5 * 4 return result my_function()
_____no_output_____
MIT
_jupyterNotebooks/python_tutorial/python_basics_1.ipynb
PranavShirole/PranavShirole.github.io
When you call a function that has an output, the returned output is what replaces the function call, and the output can be stored as a variable.
def my_function(): return 5 * 8 output = my_function() print(output)
40
MIT
_jupyterNotebooks/python_tutorial/python_basics_1.ipynb
PranavShirole/PranavShirole.github.io
Imagine that you're trying to figure out why your program is taking a long time to run. So you write some print statements inside your code to tell you what time it is when the code is running, so you can see what time it is at different stages when your code is running.
import datetime # print timestamps to see how long # sections take to run first_name = 'John' print('task completed') print(datetime.datetime.now()) print() for x in range(0, 10): print(x) print('task completed') print(datetime.datetime.now()) print()
task completed 2021-06-07 13:58:13.113387 0 1 2 3 4 5 6 7 8 9 task completed 2021-06-07 13:58:13.115614
MIT
_jupyterNotebooks/python_tutorial/python_basics_1.ipynb
PranavShirole/PranavShirole.github.io
The above code can be rewritten using a function. You can define the function using `def` keyword, followed by the name of the function, and then a colon (`:`). Remember to use indentation which determines what code belongs to that function.
# import datetime class from datetime library from datetime import datetime # print the current time def print_time(): print('task completed') # no need for the extra datetime prefix # since the class is imported above print(datetime.now()) print() first_name = 'John' print_time() for x in r...
task completed 2021-06-07 14:11:40.583077 0 1 2 3 4 5 6 7 8 9 task completed 2021-06-07 14:11:40.589036
MIT
_jupyterNotebooks/python_tutorial/python_basics_1.ipynb
PranavShirole/PranavShirole.github.io
Sometimes when you copy/paste your code, we want to change some part of it. In the above example, what if you want to display a different message each time you run it. Say you want to display a specific message depending on the command you were running. This is where function parameters come in. *Parameters* or *argume...
from datetime import datetime # print the current time and task name def print_time(task_name): print(task_name) print(datetime.now()) print() first_name = 'John' # pass in the task_name as a parameter print_time('first name assigned') for x in range(0, 10): print(x) # pass in the task_name as a ...
first name assigned 2021-06-07 16:07:57.077250 0 1 2 3 4 5 6 7 8 9 loop completed 2021-06-07 16:07:57.079687
MIT
_jupyterNotebooks/python_tutorial/python_basics_1.ipynb
PranavShirole/PranavShirole.github.io
Let's take another example where the code looks different but we're using the same logic. Suppose you're interested in getting initials for a user ID after the user enters their name.
first_name = input('Enter your first name: ') # get only the first letter of input first_name_initial = first_name[0:1] last_name = input('Enter your last name: ') last_name_initial = last_name[0:1] print('Your initials are: ' + first_name_initial + last_name_initial)
Enter your first name: John Enter your last name: Wick Your initials are: JW
MIT
_jupyterNotebooks/python_tutorial/python_basics_1.ipynb
PranavShirole/PranavShirole.github.io
The above code can be written using a function.
def get_initial(name): initial = name[0:1] # the return function returns a value return initial first_name = input('Enter your first name: ') first_name_initial = get_initial(first_name) last_name = input('Enter your last name: ') last_name_initial = get_initial(last_name) # nested function in another ca...
Enter your first name: john Enter your last name: wick Your initials are: jw
MIT
_jupyterNotebooks/python_tutorial/python_basics_1.ipynb
PranavShirole/PranavShirole.github.io
Functions can accept multiple parameters. In the above example, suppose you want to the user initials to only be uppercase for a user ID but lowercase for an email ID.
def get_initial(name, force_uppercase=True): # default to True if force_uppercase: initial = name[0:1].upper() else: initial = name[0:1] return initial first_name = input('Enter your first name: ') first_name_initial = get_initial(first_name) last_name = input('Enter your last name: ') las...
Enter your first name: john Enter your last name: wick Your initials are: Jw
MIT
_jupyterNotebooks/python_tutorial/python_basics_1.ipynb
PranavShirole/PranavShirole.github.io
Sentiment Classification AU Reviews Data (BOW, non-Deep Learning)This notebook covers two good approaches to perform sentiment classification - Naive Bayes and Logistic Regression. We will train AU reviews data on both.As a rule of thumb, reviews that are 3 stars and above are **positive**, and vice versa.
%pip install spacy %pip install gensim %pip install spacy_langdetect !python3 -m spacy download en_core_web_sm import gzip import json import matplotlib.pyplot as plt import numpy as np import re import random import pandas as pd import seaborn as sns import gensim import spacy from collections import Counter, defaultd...
_____no_output_____
MIT
playground/mel/sentiment_classification_au_bow_non_DL.ipynb
mads-app-reviews-nlp/app-reviews-nlp
1. Data Processing Check the dataset size:
print(len(reviews))
626377
MIT
playground/mel/sentiment_classification_au_bow_non_DL.ipynb
mads-app-reviews-nlp/app-reviews-nlp
And the type of apps:
app_list = list(reviews['app'].unique()) app_list
_____no_output_____
MIT
playground/mel/sentiment_classification_au_bow_non_DL.ipynb
mads-app-reviews-nlp/app-reviews-nlp
Let's also get a sense of our dataset's balance
reviews['label'].value_counts(normalize=True) # By app for app in app_list: print(reviews[reviews['app'] == app]['label'].value_counts(normalize=True))
0 0.760423 1 0.239577 Name: label, dtype: float64 0 0.648032 1 0.351968 Name: label, dtype: float64 0 0.651189 1 0.348811 Name: label, dtype: float64 0 0.682461 1 0.317539 Name: label, dtype: float64 0 0.56053 1 0.43947 Name: label, dtype: float64
MIT
playground/mel/sentiment_classification_au_bow_non_DL.ipynb
mads-app-reviews-nlp/app-reviews-nlp
Across the board the distribution of positive and negative reviews are quite consistent between the apps. Overall, there's an imbalance in our dataset, with positive reviews making for 75% of the dataset. Let's also check for null values.
reviews.isnull().sum() reviews = reviews.dropna() df_proc = reviews.copy() df_proc.drop(columns=['date', 'rating', 'app'], inplace=True) df_proc.head()
_____no_output_____
MIT
playground/mel/sentiment_classification_au_bow_non_DL.ipynb
mads-app-reviews-nlp/app-reviews-nlp
For AU dataset we won't be filtering out non-English reviews. It's likely that this makes up for a very small proportion of the dataset.
df_proc.to_csv('reviews_au_filtered.csv') X = df_proc['review'] y = df_proc['label']
_____no_output_____
MIT
playground/mel/sentiment_classification_au_bow_non_DL.ipynb
mads-app-reviews-nlp/app-reviews-nlp
We will split the dataset into `train`, `test`, and `dev`, with 80%, 10%, 10% ratio, respectively.
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=RANDOM_SEED) X_test, X_dev, y_test, y_dev = train_test_split(X_test, y_test, test_size=0.5, random_state=RANDOM_SEED) len(X_train) len(X_dev) len(X_test) X_train.iloc[0] X_test.iloc[0]
_____no_output_____
MIT
playground/mel/sentiment_classification_au_bow_non_DL.ipynb
mads-app-reviews-nlp/app-reviews-nlp
2.1 Bag-of-Words Approach on Naive Bayes & Logistic RegressionThis section explores the use of bag of words as feature extraction. But first, let's have a look at the token frequencies.
# Fill this with any token (with anything in it!) for tokens separated by whitespace ws_tokens = Counter() # Fill this one with tokens separated by whitespace but constisting only of tokens # that are totally made of alphanumeric characters (you can use the \w character # class in making the regex) alpha_ws_tokens = ...
_____no_output_____
MIT
playground/mel/sentiment_classification_au_bow_non_DL.ipynb
mads-app-reviews-nlp/app-reviews-nlp
Lots of stopwords, as expected.
x = list(range(100)) y = [word_tup[1] for word_tup in top_100] ax = plt.plot(x, y, '.') #plt.yscale('log') #plt.xscale('log')
_____no_output_____
MIT
playground/mel/sentiment_classification_au_bow_non_DL.ipynb
mads-app-reviews-nlp/app-reviews-nlp
And unexpectedly, the word frequency distribution also follows Zipf's law as well. What that means is that we can essentially remove uncommon words, without worrying that they will affect performance. We will also need to remove stopwords, and add unigrams and bigrams as features.
vectorizer = TfidfVectorizer(stop_words='english', min_df=500, ngram_range=(1,2)) X_train_bow = vectorizer.fit_transform(X_train) print(X_train_bow.shape) X_dev_bow = vectorizer.transform(X_dev) def train_model(clf): print("_" * 80) print("Training: ") clf.fit(X_train_bow, y_train) y_dev_pred = clf.pred...
_____no_output_____
MIT
playground/mel/sentiment_classification_au_bow_non_DL.ipynb
mads-app-reviews-nlp/app-reviews-nlp
It's training time! We'll start with a few dummy classifiers, followed by Naive Bayes and Logistic Regression.
for clf, name in ( (DummyClassifier(strategy='uniform', random_state=RANDOM_SEED), "Uniform Classifier"), (DummyClassifier(strategy='most_frequent', random_state=RANDOM_SEED), "Most Frequent Classifier"), ): print("=" * 80) print("Training Results - Dummy Classifiers") print(name) mod = train_mo...
================================================================================ Training Results - Naive Bayes & LogReg MultinomialNB ________________________________________________________________________________ Training: accuracy: 0.899 classification report: precision recall f1-score suppor...
MIT
playground/mel/sentiment_classification_au_bow_non_DL.ipynb
mads-app-reviews-nlp/app-reviews-nlp
The baseline results are quite promising, with both MultinomialNB and Logistic Regression achieving 0.85 on macro F1-score. This means that the bag-of-word approach is a rather solid approach for sentiment classification. It's also interesting to see that while MultinomialNB has a rather balanced number of false pos an...
# Create a dataframe for mis-classifications def create_mis_classification_df(name): mis_class = pd.DataFrame(X_dev) mis_class['Actual'] = y_dev mis_class['Predicted'] = preds[name] mis_class = mis_class[mis_class['Actual'] != mis_class['Predicted']] return mis_class mis_class_multi = create_mis_cla...
_____no_output_____
MIT
playground/mel/sentiment_classification_au_bow_non_DL.ipynb
mads-app-reviews-nlp/app-reviews-nlp
Really interesting. Looking at the results, there are a few cases of mis-classifications:- Reviews that contain negation expressions, eg "not okay" is classified as a positive review when in reality it should be negative. BoW approach makes it hard for ML model to recognize this kind of expressions.- Reviews that are m...
vectorizer = TfidfVectorizer(stop_words='english', min_df=100, ngram_range=(1,2)) X_train_bow = vectorizer.fit_transform(X_train) X_dev_bow = vectorizer.transform(X_dev) preds = {} # A dict to store our dev set predictions for clf, name in ( (MultinomialNB(alpha=0.01), "MultinomialNB"), (BernoulliNB(alpha=0.01...
================================================================================ Training Results - Naive Bayes & LogReg MultinomialNB ________________________________________________________________________________ Training: accuracy: 0.907 classification report: precision recall f1-score suppor...
MIT
playground/mel/sentiment_classification_au_bow_non_DL.ipynb
mads-app-reviews-nlp/app-reviews-nlp
Slight bump in performance, but at the expense of longer training time. 2.2 Not use stopwords removal
vectorizer = TfidfVectorizer(min_df=100, ngram_range=(1,2)) X_train_bow = vectorizer.fit_transform(X_train) X_dev_bow = vectorizer.transform(X_dev) preds = {} # A dict to store our dev set predictions for clf, name in ( (MultinomialNB(alpha=0.01), "MultinomialNB"), (BernoulliNB(alpha=0.01), "BernoulliNB"), ...
================================================================================ Training Results - Naive Bayes & LogReg MultinomialNB ________________________________________________________________________________ Training: accuracy: 0.912 classification report: precision recall f1-score suppor...
MIT
playground/mel/sentiment_classification_au_bow_non_DL.ipynb
mads-app-reviews-nlp/app-reviews-nlp
Performance improved, surprisingly. 2.3 Set max_df
vectorizer = TfidfVectorizer(min_df=100, max_df=5000, ngram_range=(1,2)) X_train_bow = vectorizer.fit_transform(X_train) X_dev_bow = vectorizer.transform(X_dev) preds = {} # A dict to store our dev set predictions for clf, name in ( (MultinomialNB(alpha=0.01), "MultinomialNB"), (BernoulliNB(alpha=0.01), "Berno...
================================================================================ Training Results - Naive Bayes & LogReg MultinomialNB ________________________________________________________________________________ Training: accuracy: 0.911 classification report: precision recall f1-score suppor...
MIT
playground/mel/sentiment_classification_au_bow_non_DL.ipynb
mads-app-reviews-nlp/app-reviews-nlp
Not much changes from stopwords removal. 2.4 Clip frequency at 1Earlier, we see that there isn't any performance with BernoulliNB as compared to other methods. But what if we clip the frequency at the feature processing level? Luckily, sklearn tfidf has a `binary` parameters that allows us to do that.
vectorizer = TfidfVectorizer(binary=True, ngram_range=(1,1)) X_train_bow = vectorizer.fit_transform(X_train) X_dev_bow = vectorizer.transform(X_dev) preds = {} # A dict to store our dev set predictions for clf, name in ( (MultinomialNB(alpha=0.01), "MultinomialNB"), (BernoulliNB(alpha=0.01), "BernoulliNB"), ...
================================================================================ Training Results - Naive Bayes & LogReg MultinomialNB ________________________________________________________________________________ Training: accuracy: 0.901 classification report: precision recall f1-score suppor...
MIT
playground/mel/sentiment_classification_au_bow_non_DL.ipynb
mads-app-reviews-nlp/app-reviews-nlp
2.5 Tune Logistic Regression ParamsSo far, LogReg performs the best in terms of macro F1 score. In this section, we'll try tuning the performance of Logistic Regression, using the best Tfidf tuning result above.
vectorizer = TfidfVectorizer(min_df=100, ngram_range=(1,2)) X_train_bow = vectorizer.fit_transform(X_train) X_dev_bow = vectorizer.transform(X_dev) clf = LogisticRegression(solver='lbfgs', class_weight='balanced', max_iter=3000, random_state=RANDOM_SEED) param_grid = {'C' : np.logspace(-4, 4, 20)} print("=" * 80) pri...
================================================================================ LogReg Grid Search Fitting 5 folds for each of 20 candidates, totalling 100 fits {'C': 1.623776739188721} accuracy: 0.926 classification report: precision recall f1-score support 0 0.97 0.92 ...
MIT
playground/mel/sentiment_classification_au_bow_non_DL.ipynb
mads-app-reviews-nlp/app-reviews-nlp
Homework 9: Bootstrap, Resampling, CLT **Reading**: * [Estimation](https://www.inferentialthinking.com/chapters/13/estimation.html)* [Why the mean matters](https://www.inferentialthinking.com/chapters/14/why-the-mean-matters.html)Please complete this notebook by filling in the cells provided. Directly sharing answers...
# Run this cell to set up the notebook, but please don't change it. # These lines import the Numpy and Datascience modules. import numpy as np from datascience import * # These lines do some fancy plotting magic. import matplotlib %matplotlib inline import matplotlib.pyplot as plt plt.style.use('fivethirtyeight') imp...
_____no_output_____
BSD-3-Clause
hw/hw09/.ipynb_checkpoints/hw09-checkpoint.ipynb
ds-modules/Colab-demo
1. PreliminariesThe British Royal Air Force wanted to know how many warplanes the Germans had (some number `N`, which is a *parameter*), and they needed to estimate that quantity knowing only a random sample of the planes' serial numbers (from 1 to `N`). We know that the German's warplanes are labeled consecutively fr...
N = ... N_estimate = ... grader.check("q1_1")
_____no_output_____
BSD-3-Clause
hw/hw09/.ipynb_checkpoints/hw09-checkpoint.ipynb
ds-modules/Colab-demo
To make the situation realistic, we're going to hide the true number of warplanes from you. You'll have access only to this random sample:
observations = Table.read_table("serial_numbers.csv") num_observations = observations.num_rows observations
_____no_output_____
BSD-3-Clause
hw/hw09/.ipynb_checkpoints/hw09-checkpoint.ipynb
ds-modules/Colab-demo
Question 1.2The average of the sample is about half of `N`. So one way to estimate `N` is to take twice the mean of the serial numbers we see. Write a function that computes that statistic. It should take as its argument an array of serial numbers and return twice their mean. Call the function `mean_based_estimator`...
def mean_based_estimator(nums): ... mean_based_estimate = ... mean_based_estimate grader.check("q1_2")
_____no_output_____
BSD-3-Clause
hw/hw09/.ipynb_checkpoints/hw09-checkpoint.ipynb
ds-modules/Colab-demo
Question 1.3We can also estimate `N` by using the biggest serial number in the sample. Compute this value and give it the name `max_estimate`.<!--BEGIN QUESTIONname: q1_3-->
max_estimate = ... max_estimate grader.check("q1_3")
_____no_output_____
BSD-3-Clause
hw/hw09/.ipynb_checkpoints/hw09-checkpoint.ipynb
ds-modules/Colab-demo
Question 1.4Let's take a look at the values of `max_estimate` and `mean_based_estimate` that we got for our dataset. Which of these values is closer to the true population maximum `N`? Based off of our estimators, can we give a lower bound for what `N` must be? In other words, is there a value that `N` must be greater...
def simulate_resample(tbl): ... simulate_resample(observations) # Don't delete this line grader.check("q2_1")
_____no_output_____
BSD-3-Clause
hw/hw09/.ipynb_checkpoints/hw09-checkpoint.ipynb
ds-modules/Colab-demo
We'll use many resamples at once to see what estimates typically look like. However, we don't often pay attention to single resamples, so it's easy to misunderstand them. Let's first answer some questions about our resample. Question 2.2Which of the following statements are true?1. The original sample can contain se...
true_statements = ... grader.check("q2_2")
_____no_output_____
BSD-3-Clause
hw/hw09/.ipynb_checkpoints/hw09-checkpoint.ipynb
ds-modules/Colab-demo
Now let's write a function to do many resamples at once. Question 2.3Write a function called `sample_estimates`. It should take 3 arguments:1. `serial_num_tbl`: A table from which the data should be sampled. The table will look like `observations`. 2. `statistic`: A *function* that takes in an array of serial numbers...
def sample_estimates(serial_num_tbl, statistic, num_replications): ... # DON'T CHANGE THE CODE BELOW THIS COMMENT! (If you do, you will fail the hidden test) # This is just an example to test your function. # This should generate an empirical histogram of twice-mean-based estimates # of N from samples of size 50 i...
_____no_output_____
BSD-3-Clause
hw/hw09/.ipynb_checkpoints/hw09-checkpoint.ipynb
ds-modules/Colab-demo
Now we can go back to the sample we actually observed (the table `observations`) and estimate how much our mean-based estimate of `N` would have varied from sample to sample. Question 2.4Using the bootstrap and the sample `observations`, simulate the approximate distribution of *mean-based estimates* of `N`. Use 7,50...
bootstrap_mean_based_estimates = ... # Don't change the code below! This plots bootstrap_mean_based_estimates. Table().with_column("mean-based estimate", bootstrap_mean_based_estimates).hist(bins=np.arange(0, 200, 4)) grader.check("q2_4")
_____no_output_____
BSD-3-Clause
hw/hw09/.ipynb_checkpoints/hw09-checkpoint.ipynb
ds-modules/Colab-demo
Question 2.5Using the bootstrap and the sample `observations`, simulate the approximate distribution of *max estimates* of `N`. Use 7,500 replications and save the estimates in an array called `bootstrap_max_estimates`.We have provided code that plots a histogram, allowing you to visualize the simulated estimates.<!-...
bootstrap_max_estimates = ... # Don't change the code below! This plots bootstrap_max_estimates. Table().with_column("max estimate", bootstrap_max_estimates).hist(bins=np.arange(0, 200, 4)) grader.check("q2_5")
_____no_output_____
BSD-3-Clause
hw/hw09/.ipynb_checkpoints/hw09-checkpoint.ipynb
ds-modules/Colab-demo
Question 2.6`N` was actually 150! Compare the histograms of estimates you generated in 2.4 and 2.5 and answer the following questions:1. How does the distribution of values for the mean-based estimates differ from the max estimates? Do both distributions contain the true max value?2. Which estimator is more dependent ...
left_end_1 = ... right_end_1 = ... print("Middle 95% of bootstrap estimates: [{:f}, {:f}]".format(left_end_1, right_end_1)) # Don't change the code below! It draws your interval and N on the histogram of mean-based estimates. Table().with_column("mean-based estimate", bootstrap_mean_based_estimates).hist(bins=np.arang...
_____no_output_____
BSD-3-Clause
hw/hw09/.ipynb_checkpoints/hw09-checkpoint.ipynb
ds-modules/Colab-demo
Question 3.2Write code that simulates the sampling and bootstrapping process again, as follows:1. Generate a new set of random observations the RAF might have seen by sampling from the `population` table we have created for you below. Use the sample size `num_observations`.2. Compute an estimate of `N` from these new ...
population = Table().with_column("serial number", np.arange(1, 150+1)) new_observations = ... new_mean_based_estimate = ... new_bootstrap_estimates = ... Table().with_column("mean-based estimate", new_bootstrap_estimates).hist(bins=np.arange(0, 252, 4)) new_left_end = ... new_right_end = ... # Don't change code below...
_____no_output_____
BSD-3-Clause
hw/hw09/.ipynb_checkpoints/hw09-checkpoint.ipynb
ds-modules/Colab-demo
Question 3.3Does the interval covering the middle 95% of the new bootstrap estimates include `N`? If you ran that cell 100 times and generated 100 intervals, how many of those intervals would you expect to include `N`?<!--BEGIN QUESTIONname: q3_3manual: true--> _Type your answer here, replacing this text._ Let's look...
reviews = Table.read_table("reviews.csv") reviews
_____no_output_____
BSD-3-Clause
hw/hw09/.ipynb_checkpoints/hw09-checkpoint.ipynb
ds-modules/Colab-demo
**Question 4.1**. Calculate the average percentage of positive reviews from your sample and assign it to `initial_sample_mean`.<!--BEGIN QUESTIONname: q4_1manual: false-->
initial_sample_mean = ... initial_sample_mean grader.check("q4_1")
_____no_output_____
BSD-3-Clause
hw/hw09/.ipynb_checkpoints/hw09-checkpoint.ipynb
ds-modules/Colab-demo
You've calculated the average percentage of positive reviews from your sample, so now you want to do some inference using this information. **Question 4.2**. First, simulate 5000 bootstrap resamples of the positive review percentages. For each bootstrap resample, calculate the resample mean and store the resampled mean...
resample_positive_percentages = make_array() for i in np.arange(5000): resample = ... resample_avg_positive = ... resample_positive_percentages = ... # Do NOT change these lines. (Table().with_column("Average % of Positive Reviews in Resamples", resample_positive_percentages).his...
_____no_output_____
BSD-3-Clause
hw/hw09/.ipynb_checkpoints/hw09-checkpoint.ipynb
ds-modules/Colab-demo
**Question 4.3**. What is the the shape of the empirical distribution of the average percentage of positive reviews based on our original sample? What value is the distribution centered at? Assign your answer to the variable `initial_sample_mean_distribution`--your answer should be either `1`, `2`, `3`, or `4` correspo...
initial_sample_mean_distribution = ... grader.check("q4_3")
_____no_output_____
BSD-3-Clause
hw/hw09/.ipynb_checkpoints/hw09-checkpoint.ipynb
ds-modules/Colab-demo
According to the Central Limit Theorem, the probability distribution of the sum or average of a *large random sample* drawn with replacement will be roughly normal, regardless of the distribution of the population from which the sample is drawn. **Question 4.4**. Note the statement about the sample being large and rand...
resampled_means_variability = ... resampled_means_variability grader.check("q4_5")
_____no_output_____
BSD-3-Clause
hw/hw09/.ipynb_checkpoints/hw09-checkpoint.ipynb
ds-modules/Colab-demo
This estimate is pretty variable! To make the estimate less variable, let's say you found a way to randomly sample reputable marketplaces from across the web which sell this book. Let's say that there are up to 150 of these marketplaces. The percentages of positive reviews are loaded into the table `more_reviews`.
# Just run this cell more_reviews = Table.read_table("more_reviews.csv") more_reviews
_____no_output_____
BSD-3-Clause
hw/hw09/.ipynb_checkpoints/hw09-checkpoint.ipynb
ds-modules/Colab-demo
In the next few questions, we'll test an important result of the Central Limit Theorem. According to the CLT, the standard deviation of all possible sample means can be calculated using the following formula:$$\text{SD of all possible sample means} = \dfrac{\text{Population SD}}{\sqrt{\text{sample size}}}$$This formula...
# Just run this cell. It's not necessary for you to read this code, but you can do 99% of this on your own! # Note: this cell might take a bit to run. def empirical_sample_mean_sd(n): sample_means = make_array() for i in np.arange(500): sample = more_reviews.sample(n).column('Positive Review Percentage...
_____no_output_____
BSD-3-Clause
hw/hw09/.ipynb_checkpoints/hw09-checkpoint.ipynb
ds-modules/Colab-demo
**Question 4.6**. Assign the numbers corresponding to all true statements to an array called `sample_mean_sd_statements`. 1. The law of large numbers tells us that the distribution of a large random sample should resemble the distribution from which it is drawn.2. The SD of the sample means is proportional to the squar...
sample_mean_sd_statements = ... grader.check("q4_6")
_____no_output_____
BSD-3-Clause
hw/hw09/.ipynb_checkpoints/hw09-checkpoint.ipynb
ds-modules/Colab-demo
Often times, when conducting statistical inference, you'll want your estimate of a population parameter to have a certain accuracy. It is common to measure accuracy of an estimate using the SD of the estimate--as the SD goes down, your estimate becomes less variable. As a result, the width of the confidence interval fo...
sample_size_calculation = ... grader.check("q4_7")
_____no_output_____
BSD-3-Clause
hw/hw09/.ipynb_checkpoints/hw09-checkpoint.ipynb
ds-modules/Colab-demo
Congratulations, you're done with Homework 9! ---To double-check your work, the cell below will rerun all of the autograder tests.
grader.check_all()
_____no_output_____
BSD-3-Clause
hw/hw09/.ipynb_checkpoints/hw09-checkpoint.ipynb
ds-modules/Colab-demo
SubmissionMake sure you have run all cells in your notebook in order before running the cell below, so that all images/graphs appear in the output. The cell below will generate a zip file for you to submit. **Please save before exporting!**
# Save your notebook first, then run this cell to export your submission. grader.export()
_____no_output_____
BSD-3-Clause
hw/hw09/.ipynb_checkpoints/hw09-checkpoint.ipynb
ds-modules/Colab-demo
SciPy Tutorial
#!git clone https://github.com/gertingold/euroscipy-scipy-tutorial
Cloning into 'euroscipy-scipy-tutorial'... remote: Enumerating objects: 108, done. remote: Counting objects: 100% (108/108), done. remote: Compressing objects: 100% (84/84), done. remote: Total 108 (delta 40), reused 85 (delta 20), pack-reused 0 Receiving objects: 100% (108/108), 21.53 MiB | 6.42 MiB/s, don...
MIT
EuroSciPy-2019/3 - Tuesday/SciPy Tutorial.ipynb
mpenagar/Irakaskuntza-Docencia-2019-2020
Basic example 1. Import Seamless in IPython or Jupyter
from seamless.highlevel import Context ctx = Context()
_____no_output_____
MIT
examples/basic-example.ipynb
sjdv1982/seamless
2. Set up a simple Seamless context
def add(a, b): return a + b ctx.a = 10 # ctx.a => Seamless cell ctx.b = 20 # ctx.b => Seamless cell ctx.add = add # ctx.add => Seamless transformer ctx.add.a = ctx.a ctx.add.b = ctx.b ctx.c = ctx.add # ctx.c => Seamless cell await ctx.computation() ctx.c.value ctx.a += 5 await ctx.comp...
_____no_output_____
MIT
examples/basic-example.ipynb
sjdv1982/seamless
3. Define schemas and validation rules
ctx.add.example.a = 0.0 # declares that add.a must be a number ctx.add.example.b = 0.0 def validate(self): assert self.a < self.b ctx.add.add_validator(validate, name="validate") await ctx.computation() print(ctx.add.exception) # Validation passes => exception is None
None
MIT
examples/basic-example.ipynb
sjdv1982/seamless
4. Create an API for a Seamless cell
def report(self): value = self.unsilk if value is None: print("Sorry, there is no result") else: print("The result is: {}".format(value)) ctx.c.example.report = report await ctx.computation() ctx.c.value.report()
The result is: 35
MIT
examples/basic-example.ipynb
sjdv1982/seamless
5. Mount cells to the file system
ctx.a.celltype = "plain" ctx.a.mount("/tmp/a.txt") ctx.b.celltype = "plain" ctx.b.mount("/tmp/b.txt") ctx.c.celltype = "plain" ctx.c.mount("/tmp/c.txt", mode="w") ctx.add.code.mount("/tmp/code.py") await ctx.translation()
d31923282290a41f9e2fcda93feb36aafdc11827f9bb4b63e11b2c099cf17325 Warning: File path '/tmp/a.txt' has a different value, overwriting cell 8e843baef228089dc379d4c3b6e28c1bb5d44eee257f1206b5dfee44ef6b05ad Warning: File path '/tmp/b.txt' has a different value, overwriting cell
MIT
examples/basic-example.ipynb
sjdv1982/seamless
6. Share a cell over HTTP
ctx.c.mimetype = "text" ctx.c.share() await ctx.translation()
_____no_output_____
MIT
examples/basic-example.ipynb
sjdv1982/seamless
http://localhost:5813/ctx/c 7. Control cells from Jupyter
from ipywidgets import IntSlider, IntText a = IntSlider(min=-10,max=30) b = IntSlider(min=-10,max=30) c = ctx.c.output() ctx.a.traitlet().link(a) ctx.b.traitlet().link(b) display(a) display(b) display(c)
Opened the seamless share update server at port 5138
MIT
examples/basic-example.ipynb
sjdv1982/seamless
8. Save the entire state of the context
# Graph and checksums, as JSON ctx.save_graph("basic-example.seamless") # Checksum-to-buffer cache, as ZIP file ctx.save_zip("basic-example.zip")
Opened the seamless REST server at port 5813
MIT
examples/basic-example.ipynb
sjdv1982/seamless
>This notebook is part of our [Introduction to Machine Learning](http://www.codeheroku.com/course?course_id=1) course at [Code Heroku](http://www.codeheroku.com/).Hey folks, today we are going to discuss about the application of gradient descent algorithm for solving machine learning problems. Let’s take a brief overvi...
import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv("student_scores.csv") #Read csv file using Pandas library
_____no_output_____
MIT
gradient descent/Gradient_Descent.ipynb
AkshatNGupta/Introduction-to-Machine-Learning
Next, we need to read the values of X and Y from the dataframe and create a scatter plot of that data.
X = df["Hours"] #Read values of X from dataframe Y = df["Scores"] #Read values of Y from dataframe plt.plot(X,Y,'o') # 'o' for creating scatter plot plt.title("Implementing Gradient Descent") plt.xlabel("Hours Studied") plt.ylabel("Student Score")
_____no_output_____
MIT
gradient descent/Gradient_Descent.ipynb
AkshatNGupta/Introduction-to-Machine-Learning
After that, we will initially choose m = 0 and b = 0
m = 0 b = 0
_____no_output_____
MIT
gradient descent/Gradient_Descent.ipynb
AkshatNGupta/Introduction-to-Machine-Learning
Now, we need to create a function(gradient descent function) which will take the current value of m and b and then give us better values of m and b.
def grad_desc(X,Y,m,b): for point in zip(X,Y): x = point[0] #value of x of a point y_actual = point[1] #Actual value of y for that point y_prediction = m*x + b #Predicted value of y for given x error = y_prediction - y_actual #Error in the estimation #Using alpha = 0.0...
_____no_output_____
MIT
gradient descent/Gradient_Descent.ipynb
AkshatNGupta/Introduction-to-Machine-Learning
Notice, in the above code, we are using learning rate(alpha) = 0.0005 . You can try to modify this value and try this example with different learning rates.Now we will make a function which will help us to plot the regression line on the graph.
def plot_regression_line(X,m,b): regression_x = X.values #list of values of x regression_y = [] #list of values of y for x in regression_x: y = m*x + b #calculating the y_prediction regression_y.append(y) #adding the predicted value in list of y plt.plot(regression_x,regression_y) #plot...
_____no_output_____
MIT
gradient descent/Gradient_Descent.ipynb
AkshatNGupta/Introduction-to-Machine-Learning
Now, when we will run the grad_desc() function, each time we will get a better result for regression line. Let us create a loop and run the grad_desc() function for 10 times and visualize the results.
for i in range(0,10): m,b = grad_desc(X,Y,m,b) #call grad_desc() to get better m & b plot_regression_line(X,m,b) #plot regression line with m & b
_____no_output_____
MIT
gradient descent/Gradient_Descent.ipynb
AkshatNGupta/Introduction-to-Machine-Learning
Finally, we need to show the plot by adding the following statement:
plt.show()
_____no_output_____
MIT
gradient descent/Gradient_Descent.ipynb
AkshatNGupta/Introduction-to-Machine-Learning
So, the full code for our program is:
import pandas as pd import matplotlib.pyplot as plt # function for plotting regression line def plot_regression_line(X,m,b): regression_x = X.values regression_y = [] for x in regression_x: y = m*x + b regression_y.append(y) plt.plot(regression_x,regression_y) plt.pause(1) df =...
_____no_output_____
MIT
gradient descent/Gradient_Descent.ipynb
AkshatNGupta/Introduction-to-Machine-Learning
Make model
X_train = np.asarray([[word_to_index[w] for w in sent[:-1]] for sent in tokenized_sentences]) y_train = np.asarray([[word_to_index[w] for w in sent[1:]] for sent in tokenized_sentences]) X_train[0] class RNNNumpy: def __init__(self, word_dim, hidden_dim=100, bptt_truncate=4): self.word_dim = word_dim ...
점 감동 현실 왜 재밌다 재미없다 말 끝 어떻다 받다
MIT
2017/coursera/code/0120/zero_based_generate_word.ipynb
janguck/lab_study_group
**Chapter 10 – Introduction to Artificial Neural Networks with Keras**_This notebook contains all the sample code and solutions to the exercises in chapter 10._ Setup First, let's import a few common modules, ensure MatplotLib plots figures inline and prepare a function to save the figures. We also check that Python 3...
# Python ≥3.5 is required import sys assert sys.version_info >= (3, 5) # Scikit-Learn ≥0.20 is required import sklearn assert sklearn.__version__ >= "0.20" # TensorFlow ≥2.0-preview is required import tensorflow as tf assert tf.__version__ >= "2.0" # Common imports import numpy as np import os # to make this notebo...
_____no_output_____
Apache-2.0
10_neural_nets_with_keras.ipynb
agniji/handson-ml2
Perceptrons **Note**: we set `max_iter` and `tol` explicitly to avoid warnings about the fact that their default value will change in future versions of Scikit-Learn.
import numpy as np from sklearn.datasets import load_iris from sklearn.linear_model import Perceptron iris = load_iris() X = iris.data[:, (2, 3)] # petal length, petal width y = (iris.target == 0).astype(np.int) per_clf = Perceptron(max_iter=1000, tol=1e-3, random_state=42) per_clf.fit(X, y) y_pred = per_clf.predic...
Saving figure perceptron_iris_plot
Apache-2.0
10_neural_nets_with_keras.ipynb
agniji/handson-ml2
Activation functions
def sigmoid(z): return 1 / (1 + np.exp(-z)) def relu(z): return np.maximum(0, z) def derivative(f, z, eps=0.000001): return (f(z + eps) - f(z - eps))/(2 * eps) z = np.linspace(-5, 5, 200) plt.figure(figsize=(11,4)) plt.subplot(121) plt.plot(z, np.sign(z), "r-", linewidth=1, label="Step") plt.plot(z, sig...
_____no_output_____
Apache-2.0
10_neural_nets_with_keras.ipynb
agniji/handson-ml2
Building an Image Classifier First let's import TensorFlow and Keras.
import tensorflow as tf from tensorflow import keras tf.__version__ keras.__version__
_____no_output_____
Apache-2.0
10_neural_nets_with_keras.ipynb
agniji/handson-ml2
Let's start by loading the fashion MNIST dataset. Keras has a number of functions to load popular datasets in `keras.datasets`. The dataset is already split for you between a training set and a test set, but it can be useful to split the training set further to have a validation set:
fashion_mnist = keras.datasets.fashion_mnist (X_train_full, y_train_full), (X_test, y_test) = fashion_mnist.load_data()
_____no_output_____
Apache-2.0
10_neural_nets_with_keras.ipynb
agniji/handson-ml2
The training set contains 60,000 grayscale images, each 28x28 pixels:
X_train_full.shape
_____no_output_____
Apache-2.0
10_neural_nets_with_keras.ipynb
agniji/handson-ml2
Each pixel intensity is represented as a byte (0 to 255):
X_train_full.dtype
_____no_output_____
Apache-2.0
10_neural_nets_with_keras.ipynb
agniji/handson-ml2