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
Download the data and print the sizes
train_data=torch.load('../data/fashion-mnist/train_data.pt') print(train_data.size()) train_label=torch.load('../data/fashion-mnist/train_label.pt') print(train_label.size()) test_data=torch.load('../data/fashion-mnist/test_data.pt') print(test_data.size())
torch.Size([10000, 28, 28])
MIT
codes/labs_lecture07/lab01_mlp/.ipynb_checkpoints/mlp_exercise-checkpoint.ipynb
wesleyjtann/Deep-learning-course-CE7454-2018
Make a ONE layer net class. The network output are the scores! No softmax needed! You have only one line to write in the forward function
class one_layer_net(nn.Module): def __init__(self, input_size, output_size): super(one_layer_net , self).__init__() self.linear_layer = nn.Linear(input_size, output_size, bias=False)# complete here def forward(self, x): scores = self.linear_layer(x) # complete here retu...
_____no_output_____
MIT
codes/labs_lecture07/lab01_mlp/.ipynb_checkpoints/mlp_exercise-checkpoint.ipynb
wesleyjtann/Deep-learning-course-CE7454-2018
Build the net
net= one_layer_net(784,10)# complete here print(net)
one_layer_net( (linear_layer): Linear(in_features=784, out_features=10, bias=False) )
MIT
codes/labs_lecture07/lab01_mlp/.ipynb_checkpoints/mlp_exercise-checkpoint.ipynb
wesleyjtann/Deep-learning-course-CE7454-2018
Choose the criterion and the optimizer: use the CHEAT SHEET to see the correct syntax. Remember that the optimizer need to have access to the parameters of the network (net.parameters()). Set the batchize and learning rate to be: batchize = 50 learning rate = 0.01
# make the criterion criterion = nn.CrossEntropyLoss()# complete here # make the SGD optimizer. optimizer=torch.optim.SGD(net.parameters(), lr=0.01) #complete here ) # set up the batch size bs=50
_____no_output_____
MIT
codes/labs_lecture07/lab01_mlp/.ipynb_checkpoints/mlp_exercise-checkpoint.ipynb
wesleyjtann/Deep-learning-course-CE7454-2018
Complete the training loop
for iter in range(1,5000): # Set dL/dU, dL/dV, dL/dW to be filled with zeros optimizer.zero_grad() # create a minibatch indices = torch.LongTensor(bs).random_(0,60000) minibatch_data = train_data[indices] minibatch_label = train_label[indices] # reshape the minibatch inputs = mini...
_____no_output_____
MIT
codes/labs_lecture07/lab01_mlp/.ipynb_checkpoints/mlp_exercise-checkpoint.ipynb
wesleyjtann/Deep-learning-course-CE7454-2018
Choose image at random from the test set and see how good/bad are the predictions
# choose a picture at random idx=randint(0, 10000-1) im=test_data[idx] # diplay the picture utils.show(im) # feed it to the net and display the confidence scores scores = net( im.view(1,784)) probs= F.softmax(scores, dim=1) utils.show_prob_fashion_mnist(probs)
_____no_output_____
MIT
codes/labs_lecture07/lab01_mlp/.ipynb_checkpoints/mlp_exercise-checkpoint.ipynb
wesleyjtann/Deep-learning-course-CE7454-2018
NVTabular demo on Rossmann data - TensorFlow OverviewNVTabular is a feature engineering and preprocessing library for tabular data designed to quickly and easily manipulate terabyte scale datasets used to train deep learning based recommender systems. It provides a high level abstraction to simplify code and accelera...
import os import math import json import nvtabular as nvt import glob
_____no_output_____
Apache-2.0
docs/source/examples/rossmann/tensorflow.ipynb
lgardenhire/NVTabular
Loading NVTabular workflowThis time, we only need to define our data directories. We can load the data schema from the NVTabular workflow.
DATA_DIR = os.environ.get("OUTPUT_DATA_DIR", "./data") INPUT_DATA_DIR = os.environ.get("INPUT_DATA_DIR", "./data") PREPROCESS_DIR = os.path.join(INPUT_DATA_DIR, 'ross_pre/') PREPROCESS_DIR_TRAIN = os.path.join(PREPROCESS_DIR, 'train') PREPROCESS_DIR_VALID = os.path.join(PREPROCESS_DIR, 'valid')
_____no_output_____
Apache-2.0
docs/source/examples/rossmann/tensorflow.ipynb
lgardenhire/NVTabular
What files are available to train on in our directories?
!ls $PREPROCESS_DIR !ls $PREPROCESS_DIR_TRAIN !ls $PREPROCESS_DIR_VALID
_metadata part.0.parquet
Apache-2.0
docs/source/examples/rossmann/tensorflow.ipynb
lgardenhire/NVTabular
We load the data schema and statistic information from `stats.json`. We created the file in the previous notebook `rossmann-store-sales-feature-engineering`.
stats = json.load(open(PREPROCESS_DIR + "/stats.json", "r")) CATEGORICAL_COLUMNS = stats['CATEGORICAL_COLUMNS'] CONTINUOUS_COLUMNS = stats['CONTINUOUS_COLUMNS'] LABEL_COLUMNS = stats['LABEL_COLUMNS'] COLUMNS = CATEGORICAL_COLUMNS + CONTINUOUS_COLUMNS + LABEL_COLUMNS
_____no_output_____
Apache-2.0
docs/source/examples/rossmann/tensorflow.ipynb
lgardenhire/NVTabular
The embedding table shows the cardinality of each categorical variable along with its associated embedding size. Each entry is of the form `(cardinality, embedding_size)`.
EMBEDDING_TABLE_SHAPES = stats['EMBEDDING_TABLE_SHAPES'] EMBEDDING_TABLE_SHAPES
_____no_output_____
Apache-2.0
docs/source/examples/rossmann/tensorflow.ipynb
lgardenhire/NVTabular
Training a NetworkNow that our data is preprocessed and saved out, we can leverage `dataset`s to read through the preprocessed parquet files in an online fashion to train neural networks.We'll start by setting some universal hyperparameters for our model and optimizer. These settings will be the same across all of the...
EMBEDDING_DROPOUT_RATE = 0.04 DROPOUT_RATES = [0.001, 0.01] HIDDEN_DIMS = [1000, 500] BATCH_SIZE = 65536 LEARNING_RATE = 0.001 EPOCHS = 25 # TODO: Calculate on the fly rather than recalling from previous analysis. MAX_SALES_IN_TRAINING_SET = 38722.0 MAX_LOG_SALES_PREDICTION = 1.2 * math.log(MAX_SALES_IN_TRAINING_SET +...
_____no_output_____
Apache-2.0
docs/source/examples/rossmann/tensorflow.ipynb
lgardenhire/NVTabular
TensorFlow TensorFlow: Preparing Datasets`KerasSequenceLoader` wraps a lightweight iterator around a `dataset` object to handle chunking, shuffling, and application of any workflows (which can be applied online as a preprocessing step). For column names, can use either a list of string names or a list of TensorFlow `...
import tensorflow as tf # we can control how much memory to give tensorflow with this environment variable # IMPORTANT: make sure you do this before you initialize TF's runtime, otherwise # it's too late and TF will have claimed all free GPU memory os.environ['TF_MEMORY_ALLOCATION'] = "8192" # explicit MB os.environ['...
_____no_output_____
Apache-2.0
docs/source/examples/rossmann/tensorflow.ipynb
lgardenhire/NVTabular
TensorFlow: Defining a ModelUsing Keras, we can define the layers of our model and their parameters explicitly. Here, for the sake of consistency, we'll mimic fast.ai's [TabularModel](https://docs.fast.ai/tabular.learner.html).
# DenseFeatures layer needs a dictionary of {feature_name: input} categorical_inputs = {} for column_name in CATEGORICAL_COLUMNS: categorical_inputs[column_name] = tf.keras.Input(name=column_name, shape=(1,), dtype=tf.int64) categorical_embedding_layer = tf.keras.layers.DenseFeatures(categorical_columns) categorica...
_____no_output_____
Apache-2.0
docs/source/examples/rossmann/tensorflow.ipynb
lgardenhire/NVTabular
TensorFlow: Training
def rmspe_tf(y_true, y_pred): # map back into "true" space by undoing transform y_true = tf.exp(y_true) - 1 y_pred = tf.exp(y_pred) - 1 percent_error = (y_true - y_pred) / y_true return tf.sqrt(tf.reduce_mean(percent_error**2)) %%time from time import time optimizer = tf.keras.optimizers.Adam(lear...
Epoch 1/25 13/13 [==============================] - 7s 168ms/step - loss: 6.3708 - rmspe_tf: 0.8916 Epoch 2/25 13/13 [==============================] - 2s 166ms/step - loss: 5.3491 - rmspe_tf: 0.8906 Epoch 3/25 13/13 [==============================] - 2s 168ms/step - loss: 4.7029 - rmspe_tf: 0.8801 Epoch 4/25 13/13 [==...
Apache-2.0
docs/source/examples/rossmann/tensorflow.ipynb
lgardenhire/NVTabular
Main points* Solution should be reasonably simple because the contest is only 24 hours long * Metric is based on the prediction of clicked pictures one week ahead, so clicks are the most important information* More recent information is more important* Only pictures that were shown to a user could be clicked, so pictu...
# Factors for ALS factors_count=100 # Last days of click history used trail_days=14 # number of best candidates generated by ALS output_candidates_count=2000 # Last days of history with more weight last_days=1 # Coefficient for additional weight last_days_weight=4
_____no_output_____
MIT
Recommending System for Pictures - 4th place @ Yandex ML Competition.ipynb
dremovd/pictures-recommendation-yandex-ml-2019
Popular pictures prediction model:
import lightgbm lightgbm.__version__ popularity_model = lightgbm.LGBMRegressor(seed=0) heuristic_alpha = 0.2 import datetime import tqdm import pandas as pd from scipy.sparse import coo_matrix import implicit implicit.__version__ test_users = pd.read_csv('Blitz/test_users.csv') data = pd.read_csv('Blitz/train_clicks....
_____no_output_____
MIT
Recommending System for Pictures - 4th place @ Yandex ML Competition.ipynb
dremovd/pictures-recommendation-yandex-ml-2019
Split last 7 days to calculate clicks similar to test set
train, target_week = ( data[data.day <= datetime.datetime(2019, 3, 17)].copy(), data[data.day > datetime.datetime(2019, 3, 17)], ) train.day.nunique(), target_week.day.nunique() last_date = train.day.max() train.loc[:, 'delta_days'] = 1 + (last_date - train.day).apply(lambda d: d.days) last_date = data.day.max...
_____no_output_____
MIT
Recommending System for Pictures - 4th place @ Yandex ML Competition.ipynb
dremovd/pictures-recommendation-yandex-ml-2019
Train a model predicting popular pictures next week
popularity_model.fit(X, y) X_test = picture_features(data) X_test.mean(axis=0) X_test['p'] = popularity_model.predict(X_test) X_test.loc[X_test['p'] < 0, 'p'] = 0 X_test['p'].mean()
_____no_output_____
MIT
Recommending System for Pictures - 4th place @ Yandex ML Competition.ipynb
dremovd/pictures-recommendation-yandex-ml-2019
Generate dict with predicted clicks for every picture
# This prediction would be used to correct recommender score picture = dict(X_test['p'])
_____no_output_____
MIT
Recommending System for Pictures - 4th place @ Yandex ML Competition.ipynb
dremovd/pictures-recommendation-yandex-ml-2019
Recommender part Generate prediction using ALS approach
import os os.environ['OPENBLAS_NUM_THREADS'] = "1" def als_baseline( train, test_users, factors_n, last_days, trail_days, output_candidates_count, last_days_weight ): train = train[train.delta_days <= trail_days].drop_duplicates([ 'user_id', 'picture_id' ]) users = train.user_id i...
100%|██████████| 100.0/100 [11:00<00:00, 6.78s/it]
MIT
Recommending System for Pictures - 4th place @ Yandex ML Competition.ipynb
dremovd/pictures-recommendation-yandex-ml-2019
Calculate history clicks to exclude them from results. Such clicks are excluded from test set according to task
clicked = data.groupby('user_id').agg({'picture_id': set}) def substract_clicked(p, c): filtered = [picture for picture in p if picture not in c][:100] return filtered
_____no_output_____
MIT
Recommending System for Pictures - 4th place @ Yandex ML Competition.ipynb
dremovd/pictures-recommendation-yandex-ml-2019
Heuristical approach to reweight ALS score according to picture predicted popularity Recommender returns (picture, score) pairs sorted decreasing for every user.For every user we replace picture $score_p$ with $score_p \cdot (1 + popularity_{p})^{0.2}$$popularity_{p}$ - popularity predicted for this picture for next w...
import math rows = test_users['predictions_full'] def correct_with_popularity(items, picture, alpha): return sorted([ (score * (1 + picture.get(picture_id, 0)) ** alpha, picture_id, score, picture.get(picture_id, 0)) for picture_id, score in items], reverse=True ) corrected_rows = [ [x[1...
_____no_output_____
MIT
Recommending System for Pictures - 4th place @ Yandex ML Competition.ipynb
dremovd/pictures-recommendation-yandex-ml-2019
Submission formatting
test_users['predictions'] = [ ' '.join(map(str, substract_clicked(p, {} if user_id not in clicked.index else clicked.loc[user_id][0]) )) for p, user_id in zip( corrected_rows, test_users.user_id.values ) ] test_users[['user_id', 'predictions']].to_csv('submit.csv', index=False)
_____no_output_____
MIT
Recommending System for Pictures - 4th place @ Yandex ML Competition.ipynb
dremovd/pictures-recommendation-yandex-ml-2019
Load predictor
%matplotlib inline import os import matplotlib import numpy as np import matplotlib.pyplot as plt matplotlib.use("Agg") os.getcwd() os.chdir('/home/del/research/span_ae') import span_ae from allennlp.models.archival import load_archive from allennlp.service.predictors import Predictor archive = load_archive("models/bas...
_____no_output_____
MIT
notebooks/predict.ipynb
maxdel/span_ae
Func
def predict_plot(sentence): # predict result = predictor.predict_json(sentence) attention_matrix = result['attention_matrix'] predicted_tokens = result['predicted_tokens'] survived_span_ids = result['top_spans'] input_sentence = ['BOS'] + sentence['src'].split() + ['EOS'] predicted_tokens = ...
_____no_output_____
MIT
notebooks/predict.ipynb
maxdel/span_ae
Inference
# change it sentence = "to school" # do not change it predict_plot({'src': sentence}) # change it sentence = "school" # do not change it predict_plot({'src': sentence}) # change it sentence = "it is spring already , but there are a lot of snow out there" # do not change it predict_plot({'src': sentence}) b # change ...
ORIGINAL : BOS let us discard our entire human knowledge EOS PREDICTED: let us discard our entire development knowledge EOS Attnetion matrix:
MIT
notebooks/predict.ipynb
maxdel/span_ae
This challenge implements an instantiation of OTR based on AES block cipher with modified version 1.0. OTR, which stands for Offset Two-Round, is a blockcipher mode of operation to realize an authenticated encryption with associated data (see [[1]](1)). AES-OTR algorithm is a campaign of CAESAR competition, it has succ...
M_0 = [b'Uid=16112\xffUserNa', b'me=AdministratoR', b'\xffT=111111111111\xff', b'Cmd=Give_Me_FlaG', b'\xff???????????????'] M_1 = [b'Uid=16111\xffUserNa', b'me=Administrator', b'r\xffT=11111111111\xff', b'Cmd=Give_Me_FlaG', b'\xff???????????????'] M_2 = [b'Uid=16112\xffUserNa', b'me=AdministratoR', b'\xffT=111111111111...
_____no_output_____
Apache-2.0
Crypto/imposter/imposter_writeup.ipynb
NeSE-Team/XNUCA2020Qualifier
Here `'111111111111'` can represent any value since the server won't check whether the message and its corresponding hash value match, so we just need to make sure that they are at the right length. If you look closely, you will find that none of the three plaintexts contains illegal fields, so we can use the encrypt O...
from Crypto.Util.strxor import strxor M_0 = [b'Uid=16112\xffUserNa', b'me=AdministratoR', b'\xffT=111111111111\xff', b'Cmd=Give_Me_FlaG', b'\xff???????????????'] M_1 = [b'Uid=16111\xffUserNa', b'me=Administrator', b'r\xffT=11111111111\xff', b'Cmd=Give_Me_FlaG', b'\xff???????????????'] M_2 = [b'Uid=16112\xffUserNa', b'...
_____no_output_____
Apache-2.0
Crypto/imposter/imposter_writeup.ipynb
NeSE-Team/XNUCA2020Qualifier
So according to the forgery attacks described in [[3]](3), suppose their corresponding ciphertexts are `C_0`, `C_1` and `C_2`, then we can forge a valid ciphertext and tag using:
from Toy_AE import Toy_AE def unpack(r): data = r.split(b"\xff") uid, uname, token, cmd, appendix = int(data[0][4:]), data[1][9:], data[2][2:], data[3][4:], data[4] return (uid, uname, token, cmd, appendix) ae = Toy_AE() M_0 = [b'Uid=16112\xffUserNa', b'me=AdministratoR', b'\xffT=111111111111\xff', b'Cmd...
_____no_output_____
Apache-2.0
Crypto/imposter/imposter_writeup.ipynb
NeSE-Team/XNUCA2020Qualifier
Here is my final exp:
import string from pwn import * from hashlib import sha256 from Crypto.Util.strxor import strxor from Crypto.Util.number import long_to_bytes, bytes_to_long def bypass_POW(io): chall = io.recvline() post = chall[14:30] tar = chall[38:-2] io.recvuntil(':') found = iters.bruteforce(lambda x:sha256((x...
_____no_output_____
Apache-2.0
Crypto/imposter/imposter_writeup.ipynb
NeSE-Team/XNUCA2020Qualifier
Testing different SA methods 4/5 Textblob
import csv import re import random from textblob import TextBlob # Ugly hackery, but necessary: stackoverflow.com/questions/4383571/importing-files-from-different-folder import sys sys.path.append('../../../') from src.streaming import spark_functions preprocess = spark_functions.preprocessor() tokenize = spark_...
Labeled correctly: 580/946 = 61 percent
MIT
notebooks/sentiment_analysis/textblob.ipynb
ClaasM/streamed-sentiment-topic-intent
Easy string manipulation
x = 'a string' y = "a string" if x == y: print("they are the same") fox = "tHe qUICk bROWn fOx."
_____no_output_____
MIT
Some_strings_and_regex_operation_in_Python.ipynb
LanguegeEngineering/demo-igor-skorzybot
To convert the entire string into upper-case or lower-case, you can use the ``upper()`` or ``lower()`` methods respectively:
fox.upper() fox.lower()
_____no_output_____
MIT
Some_strings_and_regex_operation_in_Python.ipynb
LanguegeEngineering/demo-igor-skorzybot
A common formatting need is to capitalize just the first letter of each word, or perhaps the first letter of each sentence.This can be done with the ``title()`` and ``capitalize()`` methods:
fox.title() fox.capitalize()
_____no_output_____
MIT
Some_strings_and_regex_operation_in_Python.ipynb
LanguegeEngineering/demo-igor-skorzybot
The cases can be swapped using the ``swapcase()`` method:
fox.swapcase() line = ' this is the content ' line.strip()
_____no_output_____
MIT
Some_strings_and_regex_operation_in_Python.ipynb
LanguegeEngineering/demo-igor-skorzybot
To remove just space to the right or left, use ``rstrip()`` or ``lstrip()`` respectively:
line.rstrip() line.lstrip()
_____no_output_____
MIT
Some_strings_and_regex_operation_in_Python.ipynb
LanguegeEngineering/demo-igor-skorzybot
To remove characters other than spaces, you can pass the desired character to the ``strip()`` method:
num = "000000000000435" num.strip('0') line = 'the quick brown fox jumped over a lazy dog' line.find('fox') line.index('fox') line[16:21]
_____no_output_____
MIT
Some_strings_and_regex_operation_in_Python.ipynb
LanguegeEngineering/demo-igor-skorzybot
The only difference between ``find()`` and ``index()`` is their behavior when the search string is not found; ``find()`` returns ``-1``, while ``index()`` raises a ``ValueError``:
line.find('bear') line.index('bear') line.partition('fox')
_____no_output_____
MIT
Some_strings_and_regex_operation_in_Python.ipynb
LanguegeEngineering/demo-igor-skorzybot
The ``rpartition()`` method is similar, but searches from the right of the string.The ``split()`` method is perhaps more useful; it finds *all* instances of the split-point and returns the substrings in between.The default is to split on any whitespace, returning a list of the individual words in a string:
line_list = line.split() print(line_list) print(line_list[1])
quick
MIT
Some_strings_and_regex_operation_in_Python.ipynb
LanguegeEngineering/demo-igor-skorzybot
A related method is ``splitlines()``, which splits on newline characters.Let's do this with a Haiku, popularly attributed to the 17th-century poet Matsuo Bashō:
haiku = """matsushima-ya aah matsushima-ya matsushima-ya""" haiku.splitlines()
_____no_output_____
MIT
Some_strings_and_regex_operation_in_Python.ipynb
LanguegeEngineering/demo-igor-skorzybot
Note that if you would like to undo a ``split()``, you can use the ``join()`` method, which returns a string built from a splitpoint and an iterable:
'--'.join(['1', '2', '3'])
_____no_output_____
MIT
Some_strings_and_regex_operation_in_Python.ipynb
LanguegeEngineering/demo-igor-skorzybot
A common pattern is to use the special character ``"\n"`` (newline) to join together lines that have been previously split, and recover the input:
print("\n".join(['matsushima-ya', 'aah matsushima-ya', 'matsushima-ya'])) pi = 3.14159 str(pi) print ("The value of pi is " + pi)
_____no_output_____
MIT
Some_strings_and_regex_operation_in_Python.ipynb
LanguegeEngineering/demo-igor-skorzybot
Pi is a float number so it must be transform to sting.
print( "The value of pi is " + str(pi))
The value of pi is 3.14159
MIT
Some_strings_and_regex_operation_in_Python.ipynb
LanguegeEngineering/demo-igor-skorzybot
A more flexible way to do this is to use *format strings*, which are strings with special markers (noted by curly braces) into which string-formatted values will be inserted.Here is a basic example:
"The value of pi is {}".format(pi)
_____no_output_____
MIT
Some_strings_and_regex_operation_in_Python.ipynb
LanguegeEngineering/demo-igor-skorzybot
Easy regex manipulation!
import re line = 'the quick brown fox jumped over a lazy dog'
_____no_output_____
MIT
Some_strings_and_regex_operation_in_Python.ipynb
LanguegeEngineering/demo-igor-skorzybot
With this, we can see that the ``regex.search()`` method operates a lot like ``str.index()`` or ``str.find()``:
line.index('fox') regex = re.compile('fox') match = regex.search(line) match.start()
_____no_output_____
MIT
Some_strings_and_regex_operation_in_Python.ipynb
LanguegeEngineering/demo-igor-skorzybot
Similarly, the ``regex.sub()`` method operates much like ``str.replace()``:
line.replace('fox', 'BEAR') regex.sub('BEAR', line)
_____no_output_____
MIT
Some_strings_and_regex_operation_in_Python.ipynb
LanguegeEngineering/demo-igor-skorzybot
The following is a table of the repetition markers available for use in regular expressions:| Character | Description | Example ||-----------|-------------|---------|| ``?`` | Match zero or one repetitions of preceding | ``"ab?"`` matches ``"a"`` or ``"ab"`` || ``*`` | Match zero or more repetitions of preceding | ``"...
bool(re.search(r'ab', "Boabab")) bool(re.search(r'.*ma.*', "Ala ma kota")) bool(re.search(r'.*(psa|kota).*', "Ala ma kota")) bool(re.search(r'.*(psa|kota).*', "Ala ma psa")) bool(re.search(r'.*(psa|kota).*', "Ala ma chomika")) zdanie = "Ala ma kota." wzor = r'.*' #pasuje do każdego zdania zamiennik = r"Ala ma psa." re....
_____no_output_____
MIT
Some_strings_and_regex_operation_in_Python.ipynb
LanguegeEngineering/demo-igor-skorzybot
Data ExplorationNow that we have extracted our data, let's clean it up and take a look at what we have to work with.
df = pd.DataFrame.from_records(rows) df = df.set_index('Id', drop=False) df['Title'] = df['Title'].fillna('').astype('str') df['Tags'] = df['Tags'].fillna('').astype('str') df['Body'] = df['Body'].fillna('').astype('str') df['Id'] = df['Id'].astype('int') df['PostTypeId'] = df['PostTypeId'].astype('int') df['ViewCo...
_____no_output_____
Apache-2.0
.ipynb_checkpoints/05.1 Generating Text in the Style of an Example Text-checkpoint.ipynb
WillKoehrsen/deep_learning_cookbook
Embedding LookupsLet's define a helper class for looking up our embedding results. We'll use itto verify our models.
questions = df[df['PostTypeId'] == 1]['Title'].reset_index(drop=True) question_tokens = pad_sequences(tokenizer.texts_to_sequences(questions)) class EmbeddingWrapper(object): def __init__(self, model): self._r = questions self._i = {i:s for (i, s) in enumerate(questions)} self._w = model.pr...
_____no_output_____
Apache-2.0
.ipynb_checkpoints/05.1 Generating Text in the Style of an Example Text-checkpoint.ipynb
WillKoehrsen/deep_learning_cookbook
Training our own networkThe results are okay but not great... instead of using the word2vec embeddings, what happens if we train our network end-to-end?
sum_model_trained, sum_embedding_trained = sum_model( embedding_size=EMBEDDING_SIZE, vocab_size=VOCAB_SIZE, embedding_weights=None, idf_weights=None ) sum_model_trained.fit_generator( data_generator(batch_size=128), epochs=10, steps_per_epoch=1000 ) lookup = EmbeddingWrapper(model=sum_embedding...
_____no_output_____
Apache-2.0
.ipynb_checkpoints/05.1 Generating Text in the Style of an Example Text-checkpoint.ipynb
WillKoehrsen/deep_learning_cookbook
CNN ModelUsing a sum-of-embeddings model works well. What happens if we try to make a simple CNN model?
def cnn_model(embedding_size, vocab_size): title = layers.Input(shape=(None,), dtype='int32', name='title') body = layers.Input(shape=(None,), dtype='int32', name='body') embedding = layers.Embedding( mask_zero=False, input_dim=vocab_size, output_dim=embedding_size, ) def ...
_____no_output_____
Apache-2.0
.ipynb_checkpoints/05.1 Generating Text in the Style of an Example Text-checkpoint.ipynb
WillKoehrsen/deep_learning_cookbook
LSTM ModelWe can also make an LSTM model. Warning, this will be very slow to train and evaluate unless you have a relatively fast GPU to run it on!
def lstm_model(embedding_size, vocab_size): title = layers.Input(shape=(None,), dtype='int32', name='title') body = layers.Input(shape=(None,), dtype='int32', name='body') embedding = layers.Embedding( mask_zero=True, input_dim=vocab_size, output_dim=embedding_size, # weight...
_____no_output_____
Apache-2.0
.ipynb_checkpoints/05.1 Generating Text in the Style of an Example Text-checkpoint.ipynb
WillKoehrsen/deep_learning_cookbook
def gen_downsample_noise(filters, size, apply_batchnorm=True): initializer = tf.random_normal_initializer(mean, std_dev) result = tf.keras.Sequential() result.add( tf.keras.layers.Conv2DTranspose(filters, size, strides=2, padding='same', kernel_initializer=initializer, ...
def gen_upsample(filters, size,apply_batchnorm = False): initializer = tf.random_normal_initializer(mean, std_dev) result = tf.keras.Sequential() result.add( tf.keras.layers.Conv2DTranspose(filters, size, strides=2, padding='same', ...
_____no_output_____
MIT
DCGAN_V2.ipynb
SAKARA96/Offspring-Face-Generator
def disc_downsample_parent_target(filters, size, apply_batchnorm=True): initializer = tf.random_normal_initializer(mean, std_dev) result = tf.keras.Sequential() result.add( tf.keras.layers.Conv2D(filters, size, strides=2, padding='same', kernel_initializer=initializer...
Clipping input data to the valid range for imshow with RGB data ([0..1] for floats or [0..255] for integers).
MIT
DCGAN_V2.ipynb
SAKARA96/Offspring-Face-Generator
AWS Marketplace Product Usage Demonstration - Algorithms Using Algorithm ARN with Amazon SageMaker APIsThis sample notebook demonstrates two new functionalities added to Amazon SageMaker:1. Using an Algorithm ARN to run training jobs and use that result for inference2. Using an AWS Marketplace product ARN - we will us...
import sagemaker as sage from sagemaker import get_execution_role role = get_execution_role() # S3 prefixes common_prefix = "DEMO-scikit-byo-iris" training_input_prefix = common_prefix + "/training-input-data" batch_inference_input_prefix = common_prefix + "/batch-inference-input-data"
_____no_output_____
Apache-2.0
aws_marketplace/using_algorithms/amazon_demo_product/Using_Algorithm_Arn_From_AWS_Marketplace.ipynb
Amirosimani/amazon-sagemaker-examples
Create the sessionThe session remembers our connection parameters to Amazon SageMaker. We'll use it to perform all of our Amazon SageMaker operations.
sagemaker_session = sage.Session()
_____no_output_____
Apache-2.0
aws_marketplace/using_algorithms/amazon_demo_product/Using_Algorithm_Arn_From_AWS_Marketplace.ipynb
Amirosimani/amazon-sagemaker-examples
Upload the data for trainingWhen training large models with huge amounts of data, you'll typically use big data tools, like Amazon Athena, AWS Glue, or Amazon EMR, to create your data in S3. For the purposes of this example, we're using some the classic [Iris dataset](https://en.wikipedia.org/wiki/Iris_flower_data_set...
TRAINING_WORKDIR = "data/training" training_input = sagemaker_session.upload_data(TRAINING_WORKDIR, key_prefix=training_input_prefix) print("Training Data Location " + training_input)
_____no_output_____
Apache-2.0
aws_marketplace/using_algorithms/amazon_demo_product/Using_Algorithm_Arn_From_AWS_Marketplace.ipynb
Amirosimani/amazon-sagemaker-examples
Creating Training Job using Algorithm ARNPlease put in the algorithm arn you want to use below. This can either be an AWS Marketplace algorithm you subscribed to (or) one of the algorithms you created in your own account.The algorithm arn listed below belongs to the [Scikit Decision Trees](https://aws.amazon.com/marke...
from src.scikit_product_arns import ScikitArnProvider algorithm_arn = ScikitArnProvider.get_algorithm_arn(sagemaker_session.boto_region_name) import json import time from sagemaker.algorithm import AlgorithmEstimator algo = AlgorithmEstimator( algorithm_arn=algorithm_arn, role=role, train_instance_count=1...
_____no_output_____
Apache-2.0
aws_marketplace/using_algorithms/amazon_demo_product/Using_Algorithm_Arn_From_AWS_Marketplace.ipynb
Amirosimani/amazon-sagemaker-examples
Run Training Job
print( "Now run the training job using algorithm arn %s in region %s" % (algorithm_arn, sagemaker_session.boto_region_name) ) algo.fit({"training": training_input})
_____no_output_____
Apache-2.0
aws_marketplace/using_algorithms/amazon_demo_product/Using_Algorithm_Arn_From_AWS_Marketplace.ipynb
Amirosimani/amazon-sagemaker-examples
Automated Model Tuning (optional)Since this algorithm supports tunable hyperparameters with a tuning objective metric, we can run a Hyperparameter Tuning Job to obtain the best training job hyperparameters and its corresponding model artifacts.
from sagemaker.tuner import HyperparameterTuner, IntegerParameter ## This demo algorithm supports max_leaf_nodes as the only tunable hyperparameter. hyperparameter_ranges = {"max_leaf_nodes": IntegerParameter(1, 100000)} tuner = HyperparameterTuner( estimator=algo, base_tuning_job_name="some-name", object...
_____no_output_____
Apache-2.0
aws_marketplace/using_algorithms/amazon_demo_product/Using_Algorithm_Arn_From_AWS_Marketplace.ipynb
Amirosimani/amazon-sagemaker-examples
Batch Transform JobNow let's use the model built to run a batch inference job and verify it works. Batch Transform Input PreparationThe snippet below is removing the "label" column (column indexed at 0) and retaining the rest to be batch transform's input. ***NOTE:*** This is the same training data, which is a no-no f...
import pandas as pd ## Remove first column that contains the label shape = pd.read_csv(TRAINING_WORKDIR + "/iris.csv", header=None).drop([0], axis=1) TRANSFORM_WORKDIR = "data/transform" shape.to_csv(TRANSFORM_WORKDIR + "/batchtransform_test.csv", index=False, header=False) transform_input = ( sagemaker_session....
_____no_output_____
Apache-2.0
aws_marketplace/using_algorithms/amazon_demo_product/Using_Algorithm_Arn_From_AWS_Marketplace.ipynb
Amirosimani/amazon-sagemaker-examples
Inspect the Batch Transform Output in S3
from urllib.parse import urlparse parsed_url = urlparse(transformer.output_path) bucket_name = parsed_url.netloc file_key = "{}/{}.out".format(parsed_url.path[1:], "batchtransform_test.csv") s3_client = sagemaker_session.boto_session.client("s3") response = s3_client.get_object(Bucket=sagemaker_session.default_bucke...
_____no_output_____
Apache-2.0
aws_marketplace/using_algorithms/amazon_demo_product/Using_Algorithm_Arn_From_AWS_Marketplace.ipynb
Amirosimani/amazon-sagemaker-examples
Live Inference EndpointFinally, we demonstrate the creation of an endpoint for live inference using this AWS Marketplace algorithm generated model
from sagemaker.predictor import csv_serializer predictor = algo.deploy(1, "ml.m4.xlarge", serializer=csv_serializer)
_____no_output_____
Apache-2.0
aws_marketplace/using_algorithms/amazon_demo_product/Using_Algorithm_Arn_From_AWS_Marketplace.ipynb
Amirosimani/amazon-sagemaker-examples
Choose some data and use it for a predictionIn order to do some predictions, we'll extract some of the data we used for training and do predictions against it. This is, of course, bad statistical practice, but a good way to see how the mechanism works.
shape = pd.read_csv(TRAINING_WORKDIR + "/iris.csv", header=None) import itertools a = [50 * i for i in range(3)] b = [40 + i for i in range(10)] indices = [i + j for i, j in itertools.product(a, b)] test_data = shape.iloc[indices[:-1]] test_X = test_data.iloc[:, 1:] test_y = test_data.iloc[:, 0]
_____no_output_____
Apache-2.0
aws_marketplace/using_algorithms/amazon_demo_product/Using_Algorithm_Arn_From_AWS_Marketplace.ipynb
Amirosimani/amazon-sagemaker-examples
Prediction is as easy as calling predict with the predictor we got back from deploy and the data we want to do predictions with. The serializers take care of doing the data conversions for us.
print(predictor.predict(test_X.values).decode("utf-8"))
_____no_output_____
Apache-2.0
aws_marketplace/using_algorithms/amazon_demo_product/Using_Algorithm_Arn_From_AWS_Marketplace.ipynb
Amirosimani/amazon-sagemaker-examples
Cleanup the endpoint
algo.delete_endpoint()
_____no_output_____
Apache-2.0
aws_marketplace/using_algorithms/amazon_demo_product/Using_Algorithm_Arn_From_AWS_Marketplace.ipynb
Amirosimani/amazon-sagemaker-examples
Detrending, Stylized Facts and the Business CycleIn an influential article, Harvey and Jaeger (1993) described the use of unobserved components models (also known as "structural time series models") to derive stylized facts of the business cycle.Their paper begins: "Establishing the 'stylized facts' associated with...
%matplotlib inline import numpy as np import pandas as pd import statsmodels.api as sm import matplotlib.pyplot as plt from IPython.display import display, Latex
_____no_output_____
BSD-3-Clause
examples/notebooks/statespace_structural_harvey_jaeger.ipynb
yarikoptic/statsmodels
Unobserved ComponentsThe unobserved components model available in Statsmodels can be written as:$$y_t = \underbrace{\mu_{t}}_{\text{trend}} + \underbrace{\gamma_{t}}_{\text{seasonal}} + \underbrace{c_{t}}_{\text{cycle}} + \sum_{j=1}^k \underbrace{\beta_j x_{jt}}_{\text{explanatory}} + \underbrace{\varepsilon_t}_{\text...
# Datasets from pandas.io.data import DataReader # Get the raw data start = '1948-01' end = '2008-01' us_gnp = DataReader('GNPC96', 'fred', start=start, end=end) us_gnp_deflator = DataReader('GNPDEF', 'fred', start=start, end=end) us_monetary_base = DataReader('AMBSL', 'fred', start=start, end=end).resample('QS') rece...
_____no_output_____
BSD-3-Clause
examples/notebooks/statespace_structural_harvey_jaeger.ipynb
yarikoptic/statsmodels
To get a sense of these three variables over the timeframe, we can plot them:
# Plot the data ax = dta.plot(figsize=(13,3)) ylim = ax.get_ylim() ax.xaxis.grid() ax.fill_between(dates, ylim[0]+1e-5, ylim[1]-1e-5, recessions, facecolor='k', alpha=0.1);
_____no_output_____
BSD-3-Clause
examples/notebooks/statespace_structural_harvey_jaeger.ipynb
yarikoptic/statsmodels
ModelSince the data is already seasonally adjusted and there are no obvious explanatory variables, the generic model considered is:$$y_t = \underbrace{\mu_{t}}_{\text{trend}} + \underbrace{c_{t}}_{\text{cycle}} + \underbrace{\varepsilon_t}_{\text{irregular}}$$The irregular will be assumed to be white noise, and the cy...
# Model specifications # Unrestricted model, using string specification unrestricted_model = { 'level': 'local linear trend', 'cycle': True, 'damped_cycle': True, 'stochastic_cycle': True } # Unrestricted model, setting components directly # This is an equivalent, but less convenient, way to specify a # local lin...
_____no_output_____
BSD-3-Clause
examples/notebooks/statespace_structural_harvey_jaeger.ipynb
yarikoptic/statsmodels
We now fit the following models:1. Output, unrestricted model2. Prices, unrestricted model3. Prices, restricted model4. Money, unrestricted model5. Money, restricted model
# Output output_mod = sm.tsa.UnobservedComponents(dta['US GNP'], **unrestricted_model) output_res = output_mod.fit(method='powell', disp=False) # Prices prices_mod = sm.tsa.UnobservedComponents(dta['US Prices'], **unrestricted_model) prices_res = prices_mod.fit(method='powell', disp=False) prices_restricted_mod = sm....
_____no_output_____
BSD-3-Clause
examples/notebooks/statespace_structural_harvey_jaeger.ipynb
yarikoptic/statsmodels
Once we have fit these models, there are a variety of ways to display the information. Looking at the model of US GNP, we can summarize the fit of the model using the `summary` method on the fit object.
print(output_res.summary())
_____no_output_____
BSD-3-Clause
examples/notebooks/statespace_structural_harvey_jaeger.ipynb
yarikoptic/statsmodels
For unobserved components models, and in particular when exploring stylized facts in line with point (2) from the introduction, it is often more instructive to plot the estimated unobserved components (e.g. the level, trend, and cycle) themselves to see if they provide a meaningful description of the data.The `plot_com...
fig = output_res.plot_components(legend_loc='lower right', figsize=(15, 9));
_____no_output_____
BSD-3-Clause
examples/notebooks/statespace_structural_harvey_jaeger.ipynb
yarikoptic/statsmodels
Finally, Harvey and Jaeger summarize the models in another way to highlight the relative importances of the trend and cyclical components; below we replicate their Table I. The values we find are broadly consistent with, but different in the particulars from, the values from their table.
# Create Table I table_i = np.zeros((5,6)) start = dta.index[0] end = dta.index[-1] time_range = '%d:%d-%d:%d' % (start.year, start.quarter, end.year, end.quarter) models = [ ('US GNP', time_range, 'None'), ('US Prices', time_range, 'None'), ('US Prices', time_range, r'$\sigma_\eta^2 = 0$'), ('US monet...
_____no_output_____
BSD-3-Clause
examples/notebooks/statespace_structural_harvey_jaeger.ipynb
yarikoptic/statsmodels
Logistic Regression with a Neural Network mindsetWelcome to your first (required) programming assignment! You will build a logistic regression classifier to recognize cats. This assignment will step you through how to do this with a Neural Network mindset, and so will also hone your intuitions about deep learning.**I...
import numpy as np import matplotlib.pyplot as plt import h5py import scipy from PIL import Image from scipy import ndimage from lr_utils import load_dataset %matplotlib inline
_____no_output_____
MIT
01.Neural-networks-Deep-learning/Week2/Logistic Regression as a Neural Network/Logistic Regression with a Neural Network mindset v3.ipynb
navicester/deeplearning.ai-Assignments
2 - Overview of the Problem set **Problem Statement**: You are given a dataset ("data.h5") containing: - a training set of m_train images labeled as cat (y=1) or non-cat (y=0) - a test set of m_test images labeled as cat or non-cat - each image is of shape (num_px, num_px, 3) where 3 is for the 3 channels (RG...
# Loading the data (cat/non-cat) train_set_x_orig, train_set_y, test_set_x_orig, test_set_y, classes = load_dataset()
_____no_output_____
MIT
01.Neural-networks-Deep-learning/Week2/Logistic Regression as a Neural Network/Logistic Regression with a Neural Network mindset v3.ipynb
navicester/deeplearning.ai-Assignments
We added "_orig" at the end of image datasets (train and test) because we are going to preprocess them. After preprocessing, we will end up with train_set_x and test_set_x (the labels train_set_y and test_set_y don't need any preprocessing).Each line of your train_set_x_orig and test_set_x_orig is an array representing...
# Example of a picture index = 25 plt.imshow(train_set_x_orig[index]) print ("y = " + str(train_set_y[:, index]) + ", it's a '" + classes[np.squeeze(train_set_y[:, index])].decode("utf-8") + "' picture.")
_____no_output_____
MIT
01.Neural-networks-Deep-learning/Week2/Logistic Regression as a Neural Network/Logistic Regression with a Neural Network mindset v3.ipynb
navicester/deeplearning.ai-Assignments
Many software bugs in deep learning come from having matrix/vector dimensions that don't fit. If you can keep your matrix/vector dimensions straight you will go a long way toward eliminating many bugs. **Exercise:** Find the values for: - m_train (number of training examples) - m_test (number of test examples) ...
### START CODE HERE ### (≈ 3 lines of code) m_train = None m_test = None num_px = None ### END CODE HERE ### print ("Number of training examples: m_train = " + str(m_train)) print ("Number of testing examples: m_test = " + str(m_test)) print ("Height/Width of each image: num_px = " + str(num_px)) print ("Each image is...
_____no_output_____
MIT
01.Neural-networks-Deep-learning/Week2/Logistic Regression as a Neural Network/Logistic Regression with a Neural Network mindset v3.ipynb
navicester/deeplearning.ai-Assignments
**Expected Output for m_train, m_test and num_px**: **m_train** 209 **m_test** 50 **num_px** 64 For convenience, you should now reshape images of shape (num_px, num_px, 3) in a numpy-array of shape (num_px $*$ num_px $*$ 3, 1). After this, our training (and test) dataset is...
# Reshape the training and test examples ### START CODE HERE ### (≈ 2 lines of code) train_set_x_flatten = None test_set_x_flatten = None ### END CODE HERE ### print ("train_set_x_flatten shape: " + str(train_set_x_flatten.shape)) print ("train_set_y shape: " + str(train_set_y.shape)) print ("test_set_x_flatten shape...
_____no_output_____
MIT
01.Neural-networks-Deep-learning/Week2/Logistic Regression as a Neural Network/Logistic Regression with a Neural Network mindset v3.ipynb
navicester/deeplearning.ai-Assignments
**Expected Output**: **train_set_x_flatten shape** (12288, 209) **train_set_y shape** (1, 209) **test_set_x_flatten shape** (12288, 50) **test_set_y shape** (1, 50) **sanity check after reshaping** [17 31 56 22 33] To represent color images, the red, green and blue c...
train_set_x = train_set_x_flatten/255. test_set_x = test_set_x_flatten/255.
_____no_output_____
MIT
01.Neural-networks-Deep-learning/Week2/Logistic Regression as a Neural Network/Logistic Regression with a Neural Network mindset v3.ipynb
navicester/deeplearning.ai-Assignments
**What you need to remember:**Common steps for pre-processing a new dataset are:- Figure out the dimensions and shapes of the problem (m_train, m_test, num_px, ...)- Reshape the datasets such that each example is now a vector of size (num_px \* num_px \* 3, 1)- "Standardize" the data 3 - General Architecture of the le...
# GRADED FUNCTION: sigmoid def sigmoid(z): """ Compute the sigmoid of z Arguments: z -- A scalar or numpy array of any size. Return: s -- sigmoid(z) """ ### START CODE HERE ### (≈ 1 line of code) s = None ### END CODE HERE ### return s print ("sigmoid([0, 2]) = " + s...
_____no_output_____
MIT
01.Neural-networks-Deep-learning/Week2/Logistic Regression as a Neural Network/Logistic Regression with a Neural Network mindset v3.ipynb
navicester/deeplearning.ai-Assignments
**Expected Output**: **sigmoid([0, 2])** [ 0.5 0.88079708] 4.2 - Initializing parameters**Exercise:** Implement parameter initialization in the cell below. You have to initialize w as a vector of zeros. If you don't know what numpy function to use, look up np.zeros() in the Numpy library's documen...
# GRADED FUNCTION: initialize_with_zeros def initialize_with_zeros(dim): """ This function creates a vector of zeros of shape (dim, 1) for w and initializes b to 0. Argument: dim -- size of the w vector we want (or number of parameters in this case) Returns: w -- initialized vector of...
_____no_output_____
MIT
01.Neural-networks-Deep-learning/Week2/Logistic Regression as a Neural Network/Logistic Regression with a Neural Network mindset v3.ipynb
navicester/deeplearning.ai-Assignments
**Expected Output**: ** w ** [[ 0.] [ 0.]] ** b ** 0 For image inputs, w will be of shape (num_px $\times$ num_px $\times$ 3, 1). 4.3 - Forward and Backward propagationNow that your parameters are initialized, you can do the "forward" and "backward" propagation s...
# GRADED FUNCTION: propagate def propagate(w, b, X, Y): """ Implement the cost function and its gradient for the propagation explained above Arguments: w -- weights, a numpy array of size (num_px * num_px * 3, 1) b -- bias, a scalar X -- data of size (num_px * num_px * 3, number of examples) ...
_____no_output_____
MIT
01.Neural-networks-Deep-learning/Week2/Logistic Regression as a Neural Network/Logistic Regression with a Neural Network mindset v3.ipynb
navicester/deeplearning.ai-Assignments
**Expected Output**: ** dw ** [[ 0.99993216] [ 1.99980262]] ** db ** 0.499935230625 ** cost ** 6.000064773192205 d) Optimization- You have initialized your parameters.- You are also able to compute a cost function and its gradient.- Now,...
# GRADED FUNCTION: optimize def optimize(w, b, X, Y, num_iterations, learning_rate, print_cost = False): """ This function optimizes w and b by running a gradient descent algorithm Arguments: w -- weights, a numpy array of size (num_px * num_px * 3, 1) b -- bias, a scalar X -- data of shap...
_____no_output_____
MIT
01.Neural-networks-Deep-learning/Week2/Logistic Regression as a Neural Network/Logistic Regression with a Neural Network mindset v3.ipynb
navicester/deeplearning.ai-Assignments
**Expected Output**: **w** [[ 0.1124579 ] [ 0.23106775]] **b** 1.55930492484 **dw** [[ 0.90158428] [ 1.76250842]] **db** 0.430462071679 **Exercise:** The previous function will output the learned w and b. We are able to ...
# GRADED FUNCTION: predict def predict(w, b, X): ''' Predict whether the label is 0 or 1 using learned logistic regression parameters (w, b) Arguments: w -- weights, a numpy array of size (num_px * num_px * 3, 1) b -- bias, a scalar X -- data of size (num_px * num_px * 3, number of example...
_____no_output_____
MIT
01.Neural-networks-Deep-learning/Week2/Logistic Regression as a Neural Network/Logistic Regression with a Neural Network mindset v3.ipynb
navicester/deeplearning.ai-Assignments
**Expected Output**: **predictions** [[ 1. 1.]] **What to remember:**You've implemented several functions that:- Initialize (w,b)- Optimize the loss iteratively to learn parameters (w,b): - computing the cost and its gradient - updating the p...
# GRADED FUNCTION: model def model(X_train, Y_train, X_test, Y_test, num_iterations = 2000, learning_rate = 0.5, print_cost = False): """ Builds the logistic regression model by calling the function you've implemented previously Arguments: X_train -- training set represented by a numpy array of sh...
_____no_output_____
MIT
01.Neural-networks-Deep-learning/Week2/Logistic Regression as a Neural Network/Logistic Regression with a Neural Network mindset v3.ipynb
navicester/deeplearning.ai-Assignments
Run the following cell to train your model.
d = model(train_set_x, train_set_y, test_set_x, test_set_y, num_iterations = 2000, learning_rate = 0.005, print_cost = True)
_____no_output_____
MIT
01.Neural-networks-Deep-learning/Week2/Logistic Regression as a Neural Network/Logistic Regression with a Neural Network mindset v3.ipynb
navicester/deeplearning.ai-Assignments
**Expected Output**: **Train Accuracy** 99.04306220095694 % **Test Accuracy** 70.0 % **Comment**: Training accuracy is close to 100%. This is a good sanity check: your model is working and has high enough capacity to fit the training data. Test error is 68%. ...
# Example of a picture that was wrongly classified. index = 1 plt.imshow(test_set_x[:,index].reshape((num_px, num_px, 3))) print ("y = " + str(test_set_y[0,index]) + ", you predicted that it is a \"" + classes[d["Y_prediction_test"][0,index]].decode("utf-8") + "\" picture.")
_____no_output_____
MIT
01.Neural-networks-Deep-learning/Week2/Logistic Regression as a Neural Network/Logistic Regression with a Neural Network mindset v3.ipynb
navicester/deeplearning.ai-Assignments
Let's also plot the cost function and the gradients.
# Plot learning curve (with costs) costs = np.squeeze(d['costs']) plt.plot(costs) plt.ylabel('cost') plt.xlabel('iterations (per hundreds)') plt.title("Learning rate =" + str(d["learning_rate"])) plt.show()
_____no_output_____
MIT
01.Neural-networks-Deep-learning/Week2/Logistic Regression as a Neural Network/Logistic Regression with a Neural Network mindset v3.ipynb
navicester/deeplearning.ai-Assignments
**Interpretation**:You can see the cost decreasing. It shows that the parameters are being learned. However, you see that you could train the model even more on the training set. Try to increase the number of iterations in the cell above and rerun the cells. You might see that the training set accuracy goes up, but the...
learning_rates = [0.01, 0.001, 0.0001] models = {} for i in learning_rates: print ("learning rate is: " + str(i)) models[str(i)] = model(train_set_x, train_set_y, test_set_x, test_set_y, num_iterations = 1500, learning_rate = i, print_cost = False) print ('\n' + "--------------------------------------------...
_____no_output_____
MIT
01.Neural-networks-Deep-learning/Week2/Logistic Regression as a Neural Network/Logistic Regression with a Neural Network mindset v3.ipynb
navicester/deeplearning.ai-Assignments
**Interpretation**: - Different learning rates give different costs and thus different predictions results.- If the learning rate is too large (0.01), the cost may oscillate up and down. It may even diverge (though in this example, using 0.01 still eventually ends up at a good value for the cost). - A lower cost doesn'...
## START CODE HERE ## (PUT YOUR IMAGE NAME) my_image = "my_image.jpg" # change this to the name of your image file ## END CODE HERE ## # We preprocess the image to fit your algorithm. fname = "images/" + my_image image = np.array(ndimage.imread(fname, flatten=False)) my_image = scipy.misc.imresize(image, size=(num...
_____no_output_____
MIT
01.Neural-networks-Deep-learning/Week2/Logistic Regression as a Neural Network/Logistic Regression with a Neural Network mindset v3.ipynb
navicester/deeplearning.ai-Assignments
SLU10 - Metrics for regression: Example NotebookIn this notebook [some regression validation metrics offered by scikit-learn](http://scikit-learn.org/stable/modules/model_evaluation.htmlcommon-cases-predefined-values) are presented.
import numpy as np import pandas as pd from sklearn.datasets import load_boston from sklearn.linear_model import LinearRegression # some scikit-learn regression validation metrics from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score np.random.seed(60)
_____no_output_____
MIT
S01 - Bootcamp and Binary Classification/SLU10 - Metrics for Regression/Example Notebook.ipynb
LDSSA/batch4-students
Load DataLoad the Boston house-prices dataset, fit a Linear Regression, and make prediction on the dataset (used to create the model).
data = load_boston() x = pd.DataFrame(data['data'], columns=data['feature_names']) y = pd.Series(data['target']) lr = LinearRegression() lr.fit(x, y) y_hat = lr.predict(x)
_____no_output_____
MIT
S01 - Bootcamp and Binary Classification/SLU10 - Metrics for Regression/Example Notebook.ipynb
LDSSA/batch4-students
Metrics with scikitlearnBelow follows a list of metrics made available by scikitlearn and its usage: Mean Squared Error$$MSE = \frac{1}{N} \sum_{n=1}^N (y_n - \hat{y}_n)^2$$
mean_squared_error(y, y_hat)
_____no_output_____
MIT
S01 - Bootcamp and Binary Classification/SLU10 - Metrics for Regression/Example Notebook.ipynb
LDSSA/batch4-students
Root Mean Squared Error$$RMSE = \sqrt{MSE}$$
np.sqrt(mean_squared_error(y, y_hat))
_____no_output_____
MIT
S01 - Bootcamp and Binary Classification/SLU10 - Metrics for Regression/Example Notebook.ipynb
LDSSA/batch4-students
Mean Absolute Error$$MAE = \frac{1}{N} \sum_{n=1}^N \left| y_n - \hat{y}_n \right|$$
mean_absolute_error(y, y_hat)
_____no_output_____
MIT
S01 - Bootcamp and Binary Classification/SLU10 - Metrics for Regression/Example Notebook.ipynb
LDSSA/batch4-students
R² score$$\bar{y} = \frac{1}{N} \sum_{n=1}^N y_n$$$$R² = 1 - \frac{MSE(y, \hat{y})}{MSE(y, \bar{y})} = 1 - \frac{\frac{1}{N} \sum_{n=1}^N (y_n - \hat{y}_n)^2}{\frac{1}{N} \sum_{n=1}^N (y_n - \bar{y})^2}= 1 - \frac{\sum_{n=1}^N (y_n - \hat{y}_n)^2}{\sum_{n=1}^N (y_n - \bar{y})^2}$$
r2_score(y, y_hat)
_____no_output_____
MIT
S01 - Bootcamp and Binary Classification/SLU10 - Metrics for Regression/Example Notebook.ipynb
LDSSA/batch4-students
Planar data classification with one hidden layerWelcome to your week 3 programming assignment! It's time to build your first neural network, which will have one hidden layer. Now, you'll notice a big difference between this model and the one you implemented previously using logistic regression.By the end of this assig...
# Package imports import numpy as np import copy import matplotlib.pyplot as plt from testCases_v2 import * from public_tests import * import sklearn import sklearn.datasets import sklearn.linear_model from planar_utils import plot_decision_boundary, sigmoid, load_planar_dataset, load_extra_datasets %matplotlib inline...
_____no_output_____
MIT
Neural Networks and Deep Learning/Week3/Planar_data_classification_with_one_hidden_layer.ipynb
sounok1234/Deeplearning_Projects