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
**WOW. That's nice code!**Also: **Naming your baby Daenerys after the hero...**...is a bad break.
(baby_names .query('name in ["Khaleesi","Ramsay","Lyanna","Ellaria","Meera"] & \ year >= 2000') .groupby(['name','year'])['count'].sum() # for each name-year, combine M and F counts .reset_index() # give use the column names back as they were (makes the plot call easy) .pipe((sns.linepl...
_____no_output_____
MIT
content/03/02f_chains-Copy1.ipynb
schemesmith/ledatascifi-2021
**BUT IT COULD BE WORSE**
(baby_names .query('name in ["Krymson"] & year >= 1950') .groupby(['name','year'])['count'].sum() # for each name-year, combine M and F counts .reset_index() # give use the column names back as they were (makes the plot call easy) .pipe((sns.lineplot, 'data'),hue='name',x='year',y='count') ) ...
_____no_output_____
MIT
content/03/02f_chains-Copy1.ipynb
schemesmith/ledatascifi-2021
"Bookrating (Collaborative-Filtering)"> "Prediction of tangible books to read using collaborative filtering"- toc: false- branch: master- badges: true- comments: true- categories: [jupyter, pytorch, pytorch-lightning]- hide: false- search_exclude: true
%%capture !pip install -U fastai from google.colab import drive drive.mount('/content/drive') from fastai.collab import * import pandas as pd import torch.nn as nn pathr = '/content/drive/MyDrive/my-datasets/collaborative-filtering/BX-Book-Ratings.csv' pathb = '/content/drive/MyDrive/my-datasets/collaborative-filtering...
Harry Potter and the Goblet of Fire (Book 4) Harry Potter and the Chamber of Secrets (Book 2) The X-Planes: X-1 to X-45: 3rd Edition Sanctuary: Finding Moments of Refuge in the Presence of God Harry Potter and the Sorcerer's Stone (Book 1)
Apache-2.0
_notebooks/2021-01-26-Bookrating.ipynb
rajivreddy219/ai-projects
Text classification with attention and synthetic gradients.Imports and set-up:
%tensorflow_version 2.x import numpy as np import tensorflow as tf import pandas as pd import subprocess from sklearn.model_selection import train_test_split import gensim import re import sys import time # TODO: actually implement distribution in the training loop strategy = tf.distribute.get_strategy() use_mixed_pr...
_____no_output_____
CC0-1.0
synth_grads.ipynb
tarcey/Synthetic-Gradients-in-TF
Downloading the data
# Download the Sentiment140 dataset !mkdir -p data !wget -nc https://nyc3.digitaloceanspaces.com/ml-files-distro/v1/sentiment-analysis-is-bad/data/training.1600000.processed.noemoticon.csv.zip -P data !unzip -n -d data data/training.1600000.processed.noemoticon.csv.zip
_____no_output_____
CC0-1.0
synth_grads.ipynb
tarcey/Synthetic-Gradients-in-TF
Loading and splitting the data
sen140 = pd.read_csv( "data/training.1600000.processed.noemoticon.csv", encoding='latin-1', names=["target", "ids", "date", "flag", "user", "text"]) sen140.head() sen140 = sen140.sample(frac=1).reset_index(drop=True) sen140 = sen140[['text', 'target']] features, targets = sen140.iloc[:, 0].values, sen140.iloc[:...
_____no_output_____
CC0-1.0
synth_grads.ipynb
tarcey/Synthetic-Gradients-in-TF
Preprocessing data
def process_tweet(x): x = x.strip() x = x.lower() x = re.sub(r"[^a-zA-Z0-9üöäÜÖÄß\.,!\?\-%\$€\/ ]+'", ' ', x) x = re.sub('([\.,!\?\-%\$€\/])', r' \1 ', x) x = re.sub('\s{2,}', ' ', x) x = x.split() x.append("[&END&]") length = len(x) return x tweets_train = [] tweets_test = [] for ...
_____no_output_____
CC0-1.0
synth_grads.ipynb
tarcey/Synthetic-Gradients-in-TF
Using gensim word2vec to get a good word embedding.
# train the embedding embedding_dims = 128 embedding = gensim.models.Word2Vec(tweets_train, size=embedding_dims, min_count=0) def tokenize(_in, _vocab): _out = [] for i in range(len(_in)): tweet = _in[i] wordlist = [] for word in tweet: word...
_____no_output_____
CC0-1.0
synth_grads.ipynb
tarcey/Synthetic-Gradients-in-TF
Creating modules and defining the model.
class SequenceCollapseAttention(tf.Module): ''' Collapses a sequence of arbitrary length into num_out_entries entries from the sequence according to dot-product attention. So, a variable length sequence is reduced to a sequence of a fixed, known length. ''' def __init__(self, ...
_____no_output_____
CC0-1.0
synth_grads.ipynb
tarcey/Synthetic-Gradients-in-TF
Training the model
def train_validation_loop(model_caller, data_generator, epochs, metrics=[]): batch_time = -1 for epoch in range(epochs): start_e = time.time() start_p = time.time() num_batches = len(data_generator) predictions = [None] * num_batches for b in range(num_batches): ...
_____no_output_____
CC0-1.0
synth_grads.ipynb
tarcey/Synthetic-Gradients-in-TF
Testing it on validation data
def validator(model): @tf.function(experimental_relax_shapes=True) def validation_step(x_batch, y_batch, model=model, metrics=[]): predictions = model(x_batch, training=False) for metric in metrics: metric.update_state(y_batch, predictions) return predictions return vali...
_____no_output_____
CC0-1.0
synth_grads.ipynb
tarcey/Synthetic-Gradients-in-TF
Get some example results from the the test data.
most_evil_tweet=None most_evil_evilness=1 most_cool_tweet=None most_cool_coolness=1 most_angelic_tweet=None most_angelic_angelicness=0 y_pred = np.concatenate(predictions) for i in range(0,len(y_pred)): judgement = y_pred[i] polarity = abs(judgement-0.5)*2 if judgement>=most_angelic_angelicness: mo...
_____no_output_____
CC0-1.0
synth_grads.ipynb
tarcey/Synthetic-Gradients-in-TF
Imports
import numpy as np import xarray as xr import seaborn as sns import matplotlib as mpl import matplotlib.pyplot as plt from matplotlib.colors import LinearSegmentedColormap from matplotlib.patches import Polygon from matplotlib import colors as mat_colors import mpl_toolkits.axisartist as axisartist from mpl_toolkits.ax...
_____no_output_____
BSD-3-Clause
Fig.3.11_par_methods_overview/Par_method_comparision_overview.ipynb
pat-schmitt/supplementary_material_master_thesis
Define Functions Performance measurements
def BIAS(a1, a2): return (a1 - a2).mean().item() def RMSE(a1, a2): return np.sqrt(((a1 - a2)**2).mean()).item() def DIFF(a1, a2): return np.max(np.abs(a1 - a2)).item()
_____no_output_____
BSD-3-Clause
Fig.3.11_par_methods_overview/Par_method_comparision_overview.ipynb
pat-schmitt/supplementary_material_master_thesis
help function for heatmap axis
def setup_axes(fig, rect): ax = axisartist.Subplot(fig, rect) fig.add_subplot(ax) return ax
_____no_output_____
BSD-3-Clause
Fig.3.11_par_methods_overview/Par_method_comparision_overview.ipynb
pat-schmitt/supplementary_material_master_thesis
heatmap
def heatmap(datasets, # first_dataset, second_dataset, opti_var, annotation=None, annotation_x_position=0, annotation_y_position=1, fig=None, ax=None, cmap='vlag', cmap_levels=None, grid_color='grey', grid_linewi...
_____no_output_____
BSD-3-Clause
Fig.3.11_par_methods_overview/Par_method_comparision_overview.ipynb
pat-schmitt/supplementary_material_master_thesis
legend plot
def add_legend2(ax, title, fontsize, lw, ms, labels): ax.plot([], [], '-', lw=lw, ms=ms, c='none', label=labels[0]) # plot for first gradient scaling a...
_____no_output_____
BSD-3-Clause
Fig.3.11_par_methods_overview/Par_method_comparision_overview.ipynb
pat-schmitt/supplementary_material_master_thesis
performance plot
def performance_plot(ax, datasets, fig=None, # 'bed_h RMSE', 'bed_h Diff', 'bed_h Bias', # 'bed_shape RMSE', 'bed_shape Diff', 'bed_shape Bias', # 'w0 RMSE', 'w0 Diff', 'w0 Bias', # 'sfc_h RMSE'...
_____no_output_____
BSD-3-Clause
Fig.3.11_par_methods_overview/Par_method_comparision_overview.ipynb
pat-schmitt/supplementary_material_master_thesis
Define Colors
colors = sns.color_palette("colorblind") colors axis_color = list(colors[7]) + [1.] color_1 = list(colors[3]) + [1.] color_2 = list(colors[0]) + [1.] color_3 = list(colors[4]) + [1.] color_4 = list(colors[2]) + [1.] glacier_color = glacier_color = list(colors[9]) + [.5]
_____no_output_____
BSD-3-Clause
Fig.3.11_par_methods_overview/Par_method_comparision_overview.ipynb
pat-schmitt/supplementary_material_master_thesis
Import Data
input_folder = 'plot_data/' filename_scale_1 = 'par_clif_cons_ret_bed_h_and_bed_shape_at_once_scal1reg11.nc' filename_scale_1e4 = 'par_clif_cons_ret_bed_h_and_bed_shape_at_once_scal1e4reg11.nc' filename_separated = 'par_clif_cons_ret_bed_h_and_bed_shape_separatedreg11.nc' filename_calculated = 'par_clif_cons_ret_bed_h_...
_____no_output_____
BSD-3-Clause
Fig.3.11_par_methods_overview/Par_method_comparision_overview.ipynb
pat-schmitt/supplementary_material_master_thesis
Create figure with performance
#dataset, nr_of_iterations = None facecolor = 'white' labels_pad = -700 cmap = 'Spectral' fontsize = 25 lw=2 ms=10 annotation_x_position_spatial = -0.15 annotation_y_position_spatial = 0.9 annotation_x_position_performance = -0.14 annotation_y_position_performance = 1.05 #index_start_first_profil_row = 0 #index_end_fir...
_____no_output_____
BSD-3-Clause
Fig.3.11_par_methods_overview/Par_method_comparision_overview.ipynb
pat-schmitt/supplementary_material_master_thesis
Prune DB
conn = sqlite3.connect('prices.db') conn.executescript(SCHEMA) conn.commit() conn.close()
_____no_output_____
MIT
crypto-examples/Insert in Database.ipynb
zzhengnan/pycon-concurrency-tutorial-2020
Insert Data
BASE_PATH = Path('crypto_data/') files = list(BASE_PATH.glob('*.csv')) INSERT_STATEMENT = """ INSERT INTO price ( exchange, symbol, open, high, low, close, volume, day ) VALUES (?, ?, ?, ?, ?, ?, ?, ?); """ conn = sqlite3.connect('prices.db') for file in files: exchange, symbol = file.name[:-4].split('_') d...
_____no_output_____
MIT
crypto-examples/Insert in Database.ipynb
zzhengnan/pycon-concurrency-tutorial-2020
Final Test
conn = sqlite3.connect('prices.db') cursor = conn.cursor() cursor.execute('SELECT COUNT(*) FROM price;') cursor.fetchone() cursor.execute('SELECT * FROM price LIMIT 5;') cursor.fetchall() conn.close()
_____no_output_____
MIT
crypto-examples/Insert in Database.ipynb
zzhengnan/pycon-concurrency-tutorial-2020
Exchanges
conn = sqlite3.connect('prices.db') cursor = conn.cursor() cursor.execute('SELECT DISTINCT exchange FROM price;') cursor.fetchall() cursor.execute('SELECT DISTINCT symbol FROM price;') cursor.fetchall()
_____no_output_____
MIT
crypto-examples/Insert in Database.ipynb
zzhengnan/pycon-concurrency-tutorial-2020
Filtered query:
cursor.execute('SELECT * FROM price WHERE symbol = "btc" AND exchange = "bitfinex" AND day = "2019-07-20";') cursor.fetchall()
_____no_output_____
MIT
crypto-examples/Insert in Database.ipynb
zzhengnan/pycon-concurrency-tutorial-2020
Setup Data
#----------Training data set df_train0 = pd.read_json('../input/deepfake/metadata0.json') df_train1 = pd.read_json('../input/deepfake/metadata1.json') df_train2 = pd.read_json('../input/deepfake/metadata2.json') df_train3 = pd.read_json('../input/deepfake/metadata3.json') df_train4 = pd.read_json('../input/deepfake/met...
_____no_output_____
MIT
DFDC/Training Xception Classifier .ipynb
nizamphoenix/kaggle
Dataset
def read_img(path): return cv2.cvtColor(cv2.imread(path),cv2.COLOR_BGR2RGB) import random def shuffle(X,y): new = [] for m,n in zip(X,y): new.append([m,n]) random.shuffle(new) X,y = [],[] for path,label in new: X.append(path) y.append(label) return X,y
_____no_output_____
MIT
DFDC/Training Xception Classifier .ipynb
nizamphoenix/kaggle
FAKE-->1 REAL-->0
def get_data(train_paths, train_y, val_paths, val_y): train_X=[] for img in tqdm(train_paths): train_X.append(read_img(img)) val_X=[] for img in tqdm(val_paths): val_X.append(read_img(img)) train_X, train_y = shuffle(train_X,train_y) val_X, val_y = shuffle(val_X,val_y) return...
_____no_output_____
MIT
DFDC/Training Xception Classifier .ipynb
nizamphoenix/kaggle
Model
!pip install pytorchcv --quiet from pytorchcv.model_provider import get_model model = get_model("xception", pretrained=True) # model = get_model("resnet18", pretrained=True) model = nn.Sequential(*list(model.children())[:-1]) # Remove original output layer model[0].final_block.pool = nn.Sequential(nn.AdaptiveAvgPool2d(...
_____no_output_____
MIT
DFDC/Training Xception Classifier .ipynb
nizamphoenix/kaggle
Train Functions
def calculate_loss(preds, targets): return F.binary_cross_entropy(F.sigmoid(preds), targets) def train_model(epoch, optimizer, scheduler=None, history=None): model.train() total_loss = 0 t = tqdm(train_loader) for i, (img_batch, y_batch) in enumerate(t): img_batch = img_batch.cuda().fl...
_____no_output_____
MIT
DFDC/Training Xception Classifier .ipynb
nizamphoenix/kaggle
Dataloaders
X, val_X, y, val_y = get_data(train_img_paths, train_img_labels,val_img_paths, val_img_labels) print('There are '+str(y.count(1))+' fake train samples') print('There are '+str(y.count(0))+' real train samples') print('There are '+str(val_y.count(1))+' fake val samples') print('There are '+str(val_y.count(0))+' real va...
_____no_output_____
MIT
DFDC/Training Xception Classifier .ipynb
nizamphoenix/kaggle
Train
import gc history = pd.DataFrame() history2 = pd.DataFrame() torch.cuda.empty_cache() gc.collect() best = 1e10 n_epochs = 20 batch_size = 64#BATCH SIZE CHANGED train_loader = DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True, num_workers=4) val_loader = DataLoader(dataset=val_dataset, batch_size...
_____no_output_____
MIT
DFDC/Training Xception Classifier .ipynb
nizamphoenix/kaggle
Face RecognitionIn this assignment, you will build a face recognition system. Many of the ideas presented here are from [FaceNet](https://arxiv.org/pdf/1503.03832.pdf). In lecture, we also talked about [DeepFace](https://research.fb.com/wp-content/uploads/2016/11/deepface-closing-the-gap-to-human-level-performance-in-...
from keras.models import Sequential from keras.layers import Conv2D, ZeroPadding2D, Activation, Input, concatenate from keras.models import Model from keras.layers.normalization import BatchNormalization from keras.layers.pooling import MaxPooling2D, AveragePooling2D from keras.layers.merge import Concatenate from kera...
Using TensorFlow backend.
MIT
4. Convolutional Neural Networks/Face_Recognition_v3a.ipynb
taktak-hi/Deep-Learning-Specialization
0 - Naive Face VerificationIn Face Verification, you're given two images and you have to determine if they are of the same person. The simplest way to do this is to compare the two images pixel-by-pixel. If the distance between the raw images are less than a chosen threshold, it may be the same person! **Figure 1**...
FRmodel = faceRecoModel(input_shape=(3, 96, 96)) print("Total Params:", FRmodel.count_params())
Total Params: 3743280
MIT
4. Convolutional Neural Networks/Face_Recognition_v3a.ipynb
taktak-hi/Deep-Learning-Specialization
** Expected Output **Total Params: 3743280 By using a 128-neuron fully connected layer as its last layer, the model ensures that the output is an encoding vector of size 128. You then use the encodings to compare two face images as follows: **Figure 2**: By computing the distance between two encodings and threshol...
# GRADED FUNCTION: triplet_loss def triplet_loss(y_true, y_pred, alpha = 0.2): """ Implementation of the triplet loss as defined by formula (3) Arguments: y_true -- true labels, required when you define a loss in Keras, you don't need it in this function. y_pred -- python list containing three...
loss = 528.143
MIT
4. Convolutional Neural Networks/Face_Recognition_v3a.ipynb
taktak-hi/Deep-Learning-Specialization
**Expected Output**: **loss** 528.143 2 - Loading the pre-trained modelFaceNet is trained by minimizing the triplet loss. But since training requires a lot of data and a lot of computation, we won't train it from scratch here. Instead, we load a previously t...
FRmodel.compile(optimizer = 'adam', loss = triplet_loss, metrics = ['accuracy']) load_weights_from_FaceNet(FRmodel)
_____no_output_____
MIT
4. Convolutional Neural Networks/Face_Recognition_v3a.ipynb
taktak-hi/Deep-Learning-Specialization
Here are some examples of distances between the encodings between three individuals: **Figure 4**: Example of distance outputs between three individuals' encodingsLet's now use this model to perform face verification and face recognition! 3 - Applying the model You are building a system for an office building wh...
database = {} database["danielle"] = img_to_encoding("images/danielle.png", FRmodel) database["younes"] = img_to_encoding("images/younes.jpg", FRmodel) database["tian"] = img_to_encoding("images/tian.jpg", FRmodel) database["andrew"] = img_to_encoding("images/andrew.jpg", FRmodel) database["kian"] = img_to_encoding("im...
_____no_output_____
MIT
4. Convolutional Neural Networks/Face_Recognition_v3a.ipynb
taktak-hi/Deep-Learning-Specialization
Now, when someone shows up at your front door and swipes their ID card (thus giving you their name), you can look up their encoding in the database, and use it to check if the person standing at the front door matches the name on the ID.**Exercise**: Implement the verify() function which checks if the front-door camera...
# GRADED FUNCTION: verify def verify(image_path, identity, database, model): """ Function that verifies if the person on the "image_path" image is "identity". Arguments: image_path -- path to an image identity -- string, name of the person you'd like to verify the identity. Has to be an employ...
_____no_output_____
MIT
4. Convolutional Neural Networks/Face_Recognition_v3a.ipynb
taktak-hi/Deep-Learning-Specialization
Younes is trying to enter the office and the camera takes a picture of him ("images/camera_0.jpg"). Let's run your verification algorithm on this picture:
verify("images/camera_0.jpg", "younes", database, FRmodel)
It's younes, welcome in!
MIT
4. Convolutional Neural Networks/Face_Recognition_v3a.ipynb
taktak-hi/Deep-Learning-Specialization
**Expected Output**: **It's younes, welcome in!** (0.65939283, True) Benoit, who does not work in the office, stole Kian's ID card and tried to enter the office. The camera took a picture of Benoit ("images/camera_2.jpg). Let's run the verification algorithm ...
verify("images/camera_2.jpg", "kian", database, FRmodel)
It's not kian, please go away
MIT
4. Convolutional Neural Networks/Face_Recognition_v3a.ipynb
taktak-hi/Deep-Learning-Specialization
**Expected Output**: **It's not kian, please go away** (0.86224014, False) 3.2 - Face RecognitionYour face verification system is mostly working well. But since Kian got his ID card stolen, when he came back to the office the next day and couldn't get in! To...
# GRADED FUNCTION: who_is_it def who_is_it(image_path, database, model): """ Implements face recognition for the office by finding who is the person on the image_path image. Arguments: image_path -- path to an image database -- database containing image encodings along with the name of the per...
_____no_output_____
MIT
4. Convolutional Neural Networks/Face_Recognition_v3a.ipynb
taktak-hi/Deep-Learning-Specialization
Younes is at the front-door and the camera takes a picture of him ("images/camera_0.jpg"). Let's see if your who_it_is() algorithm identifies Younes.
who_is_it("images/camera_0.jpg", database, FRmodel)
it's younes, the distance is 0.659393
MIT
4. Convolutional Neural Networks/Face_Recognition_v3a.ipynb
taktak-hi/Deep-Learning-Specialization
Logistic Regression
model = LogisticRegressionWithSGD.train(trainingData) posTest = tf.transform('O M G GET cheap stuff by sending money to ...'.split(' ')) negTest = tf.transform('Hi Dad, I started studying Spark the other ...'.split(' ')) print('Prediction for positive test example: %g' % model.predict(posTest)) print('Prediction for ne...
Prediction for positive test example: 0 Prediction for negative test example: 0
Apache-2.0
a01_PySpark/e01_Resources/PySpark-and-MLlib/learning_spark_MLlib.ipynb
mindis/Big_Data_Analysis
Creating vectors
from numpy import array from pyspark.mllib.linalg import Vectors denseVec1 = array([1.0, 2.0, 3.0]) denseVec2 = Vectors.dense([1.0, 2.0, 3.0]) sparseVec1 = Vectors.sparse(4, {0:1.0, 2:2.0}) sparseVec2 = Vectors.sparse(4, [0, 2], [1.0, 2.0])
_____no_output_____
Apache-2.0
a01_PySpark/e01_Resources/PySpark-and-MLlib/learning_spark_MLlib.ipynb
mindis/Big_Data_Analysis
Using HashingTF
sentence = 'hello hello world' words = sentence.split() tf = HashingTF(10000) tf.transform(words) rdd = sc.wholeTextFiles("data").map(lambda (name, text): text.split()) tfVectors = tf.transform(rdd)
_____no_output_____
Apache-2.0
a01_PySpark/e01_Resources/PySpark-and-MLlib/learning_spark_MLlib.ipynb
mindis/Big_Data_Analysis
Copyright 2019 Digital Advantage - Deep Insider.
#@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under...
_____no_output_____
Apache-2.0
docs/articles/deeplearningdat.ipynb
DeepInsider/playground-data
連載『機械学習 & ディープラーニング入門(データ構造編)』のノートブック Deep Insiderで記事を読む Google Colabで実行する GitHubでソースコードを見る ※上から順に実行してください。上のコードで実行したものを再利用しているところがあるため、すべて実行しないとエラーになるコードがあります。  すべてのコードを一括実行したい場合は、メニューバーから[ランタイム]-[すべてのセルを実行]をクリックしてください。 ※このノートブックは「Python 2」でも実行できるようにしていますが、基本的に「Python 3」を利用することをお勧めします。 Pytho...
# Python バージョン2への対応 from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import sys print(sys.version_info.major) # 3 # バージョン(メジャー) print(sys.version_info.minor) # 6 # バージョン(マイナー)
_____no_output_____
Apache-2.0
docs/articles/deeplearningdat.ipynb
DeepInsider/playground-data
Python言語におけるデータの構造 Pythonにおける「1つの」データの表現 リスト1-1 「単一の」データを表現するコード
height = 177.2 print(height) # 177.2と出力される
_____no_output_____
Apache-2.0
docs/articles/deeplearningdat.ipynb
DeepInsider/playground-data
リスト1-2 変数名だけを記述してオブジェクトの評価結果を出力
height # 177.2と出力される
_____no_output_____
Apache-2.0
docs/articles/deeplearningdat.ipynb
DeepInsider/playground-data
リスト1-3 オブジェクト評価結果の出力とprint()関数の出力の違い
import numpy as np array2d = np.array([ [ 165.5, 58.4 ], [ 177.2, 67.8 ], [ 183.2, 83.7 ] ]) print(array2d) # [[165.5 58.4] # [177.2 67.8] # [183.2 83.7]] array2d # array([[165.5, 58.4], # [177.2, 67.8]...
_____no_output_____
Apache-2.0
docs/articles/deeplearningdat.ipynb
DeepInsider/playground-data
リスト2-1 「単一の」データを複数書いて表現するコード
hana_height = 165.5 taro_height = 177.2 jiro_height = 183.2 hana_height, taro_height, jiro_height # (165.5, 177.2, 183.2)
_____no_output_____
Apache-2.0
docs/articles/deeplearningdat.ipynb
DeepInsider/playground-data
リスト2-2 「複数(1次元)の」データを表現するコード
heights = [ 165.5, 177.2, 183.2 ] heights # [165.5, 177.2, 183.2]
_____no_output_____
Apache-2.0
docs/articles/deeplearningdat.ipynb
DeepInsider/playground-data
Pythonにおける「複数(2次元)の」データの表現 リスト3 「複数(2次元)の」データを表現するコード
people = [ [ 165.5, 58.4 ], [ 177.2, 67.8 ], [ 183.2, 83.7 ] ] people # [165.5, 177.2, 183.2]
_____no_output_____
Apache-2.0
docs/articles/deeplearningdat.ipynb
DeepInsider/playground-data
Pythonにおける「複数(多次元)の」データの表現 リスト4 「複数(3次元)の」データを表現するコード
list3d = [ [ [ 165.5, 58.4 ], [ 177.2, 67.8 ], [ 183.2, 83.7 ] ], [ [ 155.5, 48.4 ], [ 167.2, 57.8 ], [ 173.2, 73.7 ] ], [ [ 145.5, 38.4 ], [ 157.2, 47.8 ], [ 163.2, 63.7 ] ] ] list3d # [[[165.5, 58.4], [177.2, 67.8], [183.2, 83.7]], # [[155.5, 48.4], [167.2, 57.8], [173.2, 73.7]], # [[145.5, ...
_____no_output_____
Apache-2.0
docs/articles/deeplearningdat.ipynb
DeepInsider/playground-data
AIプログラムにおけるデータの構造(基本編) NumPyのインストール リスト5-1 `numpy`パッケージをインストールするためのシェルコマンド
!pip install numpy
_____no_output_____
Apache-2.0
docs/articles/deeplearningdat.ipynb
DeepInsider/playground-data
numpyモジュールのインポート リスト5-2 `numpy`モジュールをインポートするコード例
import numpy as np
_____no_output_____
Apache-2.0
docs/articles/deeplearningdat.ipynb
DeepInsider/playground-data
NumPyのデータ型「多次元配列」オブジェクトの作成 リスト5-3 `array`関数で多次元配列を作成するコード例(値を使用)
array2d = np.array([ [ 165.5, 58.4 ], [ 177.2, 67.8 ], [ 183.2, 83.7 ] ]) array2d # array([[165.5, 58.4], # [177.2, 67.8], # [183.2, 83.7]])
_____no_output_____
Apache-2.0
docs/articles/deeplearningdat.ipynb
DeepInsider/playground-data
リスト5-4 `array`関数で多次元配列を作成するコード例(変数を使用)
array3d = np.array(list3d) array3d # array([[[165.5, 58.4], # [177.2, 67.8], # [183.2, 83.7]], # # [[155.5, 48.4], # [167.2, 57.8], # [173.2, 73.7]], # # [[145.5, 38.4], # [1...
_____no_output_____
Apache-2.0
docs/articles/deeplearningdat.ipynb
DeepInsider/playground-data
リスト5-5 `ndarray`クラスの`tolist()`メソッドで多次元リストに変換するコード例
tolist3d = array3d.tolist() tolist3d # [[[165.5, 58.4], [177.2, 67.8], [183.2, 83.7]], # [[155.5, 48.4], [167.2, 57.8], [173.2, 73.7]], # [[145.5, 38.4], [157.2, 47.8], [163.2, 63.7]]]
_____no_output_____
Apache-2.0
docs/articles/deeplearningdat.ipynb
DeepInsider/playground-data
AIプログラムにおけるデータの構造(応用編) Pandasのインストール リスト6 ◎pandas◎パッケージをインストールするためのシェルコマンド
!pip install pandas
_____no_output_____
Apache-2.0
docs/articles/deeplearningdat.ipynb
DeepInsider/playground-data
図7-1 NumPyのデータをPandasで一覧表として表示する例
import pandas as pd df = pd.DataFrame(array2d, columns=['身長', '体重']) df
_____no_output_____
Apache-2.0
docs/articles/deeplearningdat.ipynb
DeepInsider/playground-data
AIプログラムにおけるデータの計算 AI・ディープラーニングで数学を使う理由 リスト7-1 3人の身長の平均を計算するコード例(個別の値を使用)
# hana_height, taro_height, jiro_height = 165.5, 177.2, 183.2 # Lesson 1のリスト2-1で宣言済み average_height = ( hana_height + taro_height + jiro_height ) / 3 print(average_height) # 175.29999999999998
_____no_output_____
Apache-2.0
docs/articles/deeplearningdat.ipynb
DeepInsider/playground-data
リスト7-2 3人の身長と体重の平均を計算するコード例(多次元配列を使用)
import numpy as np array1d = np.array([ 165.5, 177.2, 183.2 ]) average_height = np.average(array1d) average_height # 175.29999999999998
_____no_output_____
Apache-2.0
docs/articles/deeplearningdat.ipynb
DeepInsider/playground-data
NumPyを使った計算 リスト8-1 3行2列の行列のさまざまな特性を表示するコード例
array2d = np.array([ [ 165.5, 58.4 ], [ 177.2, 67.8 ], [ 183.2, 83.7 ] ]) print(array2d.shape) # (3, 2) print(array2d.ndim) # 2 print(array2d.size) # 6
_____no_output_____
Apache-2.0
docs/articles/deeplearningdat.ipynb
DeepInsider/playground-data
リスト8-2 NumPyを使った行列計算
diet = np.array([ [ 1.0, 0.0 ], [ 0.0, 0.9 ] ]) lose_weights = diet @ array2d.T # Python 3.5以降の場合。それ以前のPython 2系などの場合は、以下のmatmul関数を使う必要がある #lose_weights = np.matmul(diet, array2d.T) print(lose_weights.T) # [[165.5 52.56] # [177.2 61.02] # [183.2 ...
_____no_output_____
Apache-2.0
docs/articles/deeplearningdat.ipynb
DeepInsider/playground-data
リスト8-3 全要素の平均値を算出(身長/体重別ではない)
averages = np.average(array2d) averages # 122.63333333333334
_____no_output_____
Apache-2.0
docs/articles/deeplearningdat.ipynb
DeepInsider/playground-data
リスト8-4 身長/体重別の平均値を算出
averages = np.average(array2d, axis=0) averages # array([175.3 , 69.96666667])
_____no_output_____
Apache-2.0
docs/articles/deeplearningdat.ipynb
DeepInsider/playground-data
リスト8-5 3次元配列データでグループごとの身長/体重別の平均値を算出
array3d = np.array( [ [ [ 165.5, 58.4 ], [ 177.2, 67.8 ], [ 183.2, 83.7 ] ], [ [ 155.5, 48.4 ], [ 167.2, 57.8 ], [ 173.2, 73.7 ] ], [ [ 145.5, 38.4 ], [ 157.2, 47.8 ], [ 163.2, 63.7 ] ] ] ) avr3d = np.average(array3d, axis=1) print(avr3d) # [[175.3 69.96666667] # [165.3 59.96...
_____no_output_____
Apache-2.0
docs/articles/deeplearningdat.ipynb
DeepInsider/playground-data
Copyright 2019 The TensorFlow Authors.
#@title Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under...
_____no_output_____
Apache-2.0
site/en/tutorials/structured_data/time_series.ipynb
jcjveraa/docs-2
Time series forecasting View on TensorFlow.org Run in Google Colab View source on GitHub Download notebook This tutorial is an introduction to time series forecasting using TensorFlow. It builds a few different styles of models including Convolutional and Recurrent Neural Networks (CNNs an...
import os import datetime import IPython import IPython.display import matplotlib as mpl import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import tensorflow as tf mpl.rcParams['figure.figsize'] = (8, 6) mpl.rcParams['axes.grid'] = False
_____no_output_____
Apache-2.0
site/en/tutorials/structured_data/time_series.ipynb
jcjveraa/docs-2
The weather datasetThis tutorial uses a weather time series dataset recorded by the Max Planck Institute for Biogeochemistry.This dataset contains 14 different features such as air temperature, atmospheric pressure, and humidity. These were collected every 10 minutes, beginning in 2003. For efficiency, you will use on...
zip_path = tf.keras.utils.get_file( origin='https://storage.googleapis.com/tensorflow/tf-keras-datasets/jena_climate_2009_2016.csv.zip', fname='jena_climate_2009_2016.csv.zip', extract=True) csv_path, _ = os.path.splitext(zip_path)
_____no_output_____
Apache-2.0
site/en/tutorials/structured_data/time_series.ipynb
jcjveraa/docs-2
This tutorial will just deal with **hourly predictions**, so start by sub-sampling the data from 10 minute intervals to 1h:
df = pd.read_csv(csv_path) # slice [start:stop:step], starting from index 5 take every 6th record. df = df[5::6] date_time = pd.to_datetime(df.pop('Date Time'), format='%d.%m.%Y %H:%M:%S')
_____no_output_____
Apache-2.0
site/en/tutorials/structured_data/time_series.ipynb
jcjveraa/docs-2
Let's take a glance at the data. Here are the first few rows:
df.head()
_____no_output_____
Apache-2.0
site/en/tutorials/structured_data/time_series.ipynb
jcjveraa/docs-2
Here is the evolution of a few features over time.
plot_cols = ['T (degC)', 'p (mbar)', 'rho (g/m**3)'] plot_features = df[plot_cols] plot_features.index = date_time _ = plot_features.plot(subplots=True) plot_features = df[plot_cols][:480] plot_features.index = date_time[:480] _ = plot_features.plot(subplots=True)
_____no_output_____
Apache-2.0
site/en/tutorials/structured_data/time_series.ipynb
jcjveraa/docs-2
Inspect and cleanup Next look at the statistics of the dataset:
df.describe().transpose()
_____no_output_____
Apache-2.0
site/en/tutorials/structured_data/time_series.ipynb
jcjveraa/docs-2
Wind velocity One thing that should stand out is the `min` value of the wind velocity, `wv (m/s)` and `max. wv (m/s)` columns. This `-9999` is likely erroneous. There's a separate wind direction column, so the velocity should be `>=0`. Replace it with zeros:
wv = df['wv (m/s)'] bad_wv = wv == -9999.0 wv[bad_wv] = 0.0 max_wv = df['max. wv (m/s)'] bad_max_wv = max_wv == -9999.0 max_wv[bad_max_wv] = 0.0 # The above inplace edits are reflected in the DataFrame df['wv (m/s)'].min()
_____no_output_____
Apache-2.0
site/en/tutorials/structured_data/time_series.ipynb
jcjveraa/docs-2
Feature engineeringBefore diving in to build a model it's important to understand your data, and be sure that you're passing the model appropriately formatted data. WindThe last column of the data, `wd (deg)`, gives the wind direction in units of degrees. Angles do not make good model inputs, 360° and 0° should be cl...
plt.hist2d(df['wd (deg)'], df['wv (m/s)'], bins=(50, 50), vmax=400) plt.colorbar() plt.xlabel('Wind Direction [deg]') plt.ylabel('Wind Velocity [m/s]')
_____no_output_____
Apache-2.0
site/en/tutorials/structured_data/time_series.ipynb
jcjveraa/docs-2
But this will be easier for the model to interpret if you convert the wind direction and velocity columns to a wind **vector**:
wv = df.pop('wv (m/s)') max_wv = df.pop('max. wv (m/s)') # Convert to radians. wd_rad = df.pop('wd (deg)')*np.pi / 180 # Calculate the wind x and y components. df['Wx'] = wv*np.cos(wd_rad) df['Wy'] = wv*np.sin(wd_rad) # Calculate the max wind x and y components. df['max Wx'] = max_wv*np.cos(wd_rad) df['max Wy'] = ma...
_____no_output_____
Apache-2.0
site/en/tutorials/structured_data/time_series.ipynb
jcjveraa/docs-2
The distribution of wind vectors is much simpler for the model to correctly interpret.
plt.hist2d(df['Wx'], df['Wy'], bins=(50, 50), vmax=400) plt.colorbar() plt.xlabel('Wind X [m/s]') plt.ylabel('Wind Y [m/s]') ax = plt.gca() ax.axis('tight')
_____no_output_____
Apache-2.0
site/en/tutorials/structured_data/time_series.ipynb
jcjveraa/docs-2
Time Similarly the `Date Time` column is very useful, but not in this string form. Start by converting it to seconds:
timestamp_s = date_time.map(datetime.datetime.timestamp)
_____no_output_____
Apache-2.0
site/en/tutorials/structured_data/time_series.ipynb
jcjveraa/docs-2
Similar to the wind direction the time in seconds is not a useful model input. Being weather data it has clear daily and yearly periodicity. There are many ways you could deal with periodicity.A simple approach to convert it to a usable signal is to use `sin` and `cos` to convert the time to clear "Time of day" and "Ti...
day = 24*60*60 year = (365.2425)*day df['Day sin'] = np.sin(timestamp_s * (2 * np.pi / day)) df['Day cos'] = np.cos(timestamp_s * (2 * np.pi / day)) df['Year sin'] = np.sin(timestamp_s * (2 * np.pi / year)) df['Year cos'] = np.cos(timestamp_s * (2 * np.pi / year)) plt.plot(np.array(df['Day sin'])[:25]) plt.plot(np.arr...
_____no_output_____
Apache-2.0
site/en/tutorials/structured_data/time_series.ipynb
jcjveraa/docs-2
This gives the model access to the most important frequency features. In this case you knew ahead of time which frequencies were important. If you didn't know, you can determine which frequencies are important using an `fft`. To check our assumptions, here is the `tf.signal.rfft` of the temperature over time. Note the ...
fft = tf.signal.rfft(df['T (degC)']) f_per_dataset = np.arange(0, len(fft)) n_samples_h = len(df['T (degC)']) hours_per_year = 24*365.2524 years_per_dataset = n_samples_h/(hours_per_year) f_per_year = f_per_dataset/years_per_dataset plt.step(f_per_year, np.abs(fft)) plt.xscale('log') plt.ylim(0, 400000) plt.xlim([0.1...
_____no_output_____
Apache-2.0
site/en/tutorials/structured_data/time_series.ipynb
jcjveraa/docs-2
Split the data We'll use a `(70%, 20%, 10%)` split for the training, validation, and test sets. Note the data is **not** being randomly shuffled before splitting. This is for two reasons.1. It ensures that chopping the data into windows of consecutive samples is still possible.2. It ensures that the validation/test re...
column_indices = {name: i for i, name in enumerate(df.columns)} n = len(df) train_df = df[0:int(n*0.7)] val_df = df[int(n*0.7):int(n*0.9)] test_df = df[int(n*0.9):] num_features = df.shape[1]
_____no_output_____
Apache-2.0
site/en/tutorials/structured_data/time_series.ipynb
jcjveraa/docs-2
Normalize the dataIt is important to scale features before training a neural network. Normalization is a common way of doing this scaling. Subtract the mean and divide by the standard deviation of each feature. The mean and standard deviation should only be computed using the training data so that the models have no a...
train_mean = train_df.mean() train_std = train_df.std() train_df = (train_df - train_mean) / train_std val_df = (val_df - train_mean) / train_std test_df = (test_df - train_mean) / train_std
_____no_output_____
Apache-2.0
site/en/tutorials/structured_data/time_series.ipynb
jcjveraa/docs-2
Now peek at the distribution of the features. Some features do have long tails, but there are no obvious errors like the `-9999` wind velocity value.
df_std = (df - train_mean) / train_std df_std = df_std.melt(var_name='Column', value_name='Normalized') plt.figure(figsize=(12, 6)) ax = sns.violinplot(x='Column', y='Normalized', data=df_std) _ = ax.set_xticklabels(df.keys(), rotation=90)
_____no_output_____
Apache-2.0
site/en/tutorials/structured_data/time_series.ipynb
jcjveraa/docs-2
Data windowingThe models in this tutorial will make a set of predictions based on a window of consecutive samples from the data. The main features of the input windows are:* The width (number of time steps) of the input and label windows* The time offset between them.* Which features are used as inputs, labels, or bot...
class WindowGenerator(): def __init__(self, input_width, label_width, shift, train_df=train_df, val_df=val_df, test_df=test_df, label_columns=None): # Store the raw data. self.train_df = train_df self.val_df = val_df self.test_df = test_df # Work out the label column...
_____no_output_____
Apache-2.0
site/en/tutorials/structured_data/time_series.ipynb
jcjveraa/docs-2
Here is code to create the 2 windows shown in the diagrams at the start of this section:
w1 = WindowGenerator(input_width=24, label_width=1, shift=24, label_columns=['T (degC)']) w1 w2 = WindowGenerator(input_width=6, label_width=1, shift=1, label_columns=['T (degC)']) w2
_____no_output_____
Apache-2.0
site/en/tutorials/structured_data/time_series.ipynb
jcjveraa/docs-2
2. SplitGiven a list consecutive inputs, the `split_window` method will convert them to a window of inputs and a window of labels.The example `w2`, above, will be split like this:![The initial window is all consecuitive samples, this splits it into an (inputs, labels) pairs](images/split_window.png)This diagram doesn'...
def split_window(self, features): inputs = features[:, self.input_slice, :] labels = features[:, self.labels_slice, :] if self.label_columns is not None: labels = tf.stack( [labels[:, :, self.column_indices[name]] for name in self.label_columns], axis=-1) # Slicing doesn't preserve static s...
_____no_output_____
Apache-2.0
site/en/tutorials/structured_data/time_series.ipynb
jcjveraa/docs-2
Try it out:
# Stack three slices, the length of the total window: example_window = tf.stack([np.array(train_df[:w2.total_window_size]), np.array(train_df[100:100+w2.total_window_size]), np.array(train_df[200:200+w2.total_window_size])]) example_inputs, example_labels = w2.spl...
_____no_output_____
Apache-2.0
site/en/tutorials/structured_data/time_series.ipynb
jcjveraa/docs-2
Typically data in TensorFlow is packed into arrays where the outermost index is across examples (the "batch" dimension). The middle indices are the "time" or "space" (width, height) dimension(s). The innermost indices are the features.The code above took a batch of 3, 7-timestep windows, with 19 features at each time s...
w2.example = example_inputs, example_labels def plot(self, model=None, plot_col='T (degC)', max_subplots=3): inputs, labels = self.example plt.figure(figsize=(12, 8)) plot_col_index = self.column_indices[plot_col] max_n = min(max_subplots, len(inputs)) for n in range(max_n): plt.subplot(3, 1, n+1) plt...
_____no_output_____
Apache-2.0
site/en/tutorials/structured_data/time_series.ipynb
jcjveraa/docs-2
This plot aligns inputs, labels, and (later) predictions based on the time that the item refers to:
w2.plot()
_____no_output_____
Apache-2.0
site/en/tutorials/structured_data/time_series.ipynb
jcjveraa/docs-2
You can plot the other columns, but the example window `w2` configuration only has labels for the `T (degC)` column.
w2.plot(plot_col='p (mbar)')
_____no_output_____
Apache-2.0
site/en/tutorials/structured_data/time_series.ipynb
jcjveraa/docs-2
4. Create `tf.data.Dataset`s Finally this `make_dataset` method will take a time series `DataFrame` and convert it to a `tf.data.Dataset` of `(input_window, label_window)` pairs using the `preprocessing.timeseries_dataset_from_array` function.
def make_dataset(self, data): data = np.array(data, dtype=np.float32) ds = tf.keras.preprocessing.timeseries_dataset_from_array( data=data, targets=None, sequence_length=self.total_window_size, sequence_stride=1, shuffle=True, batch_size=32,) ds = ds.map(self.split_window) ...
_____no_output_____
Apache-2.0
site/en/tutorials/structured_data/time_series.ipynb
jcjveraa/docs-2
The `WindowGenerator` object holds training, validation and test data. Add properties for accessing them as `tf.data.Datasets` using the above `make_dataset` method. Also add a standard example batch for easy access and plotting:
@property def train(self): return self.make_dataset(self.train_df) @property def val(self): return self.make_dataset(self.val_df) @property def test(self): return self.make_dataset(self.test_df) @property def example(self): """Get and cache an example batch of `inputs, labels` for plotting.""" result = get...
_____no_output_____
Apache-2.0
site/en/tutorials/structured_data/time_series.ipynb
jcjveraa/docs-2
Now the `WindowGenerator` object gives you access to the `tf.data.Dataset` objects, so you can easily iterate over the data.The `Dataset.element_spec` property tells you the structure, `dtypes` and shapes of the dataset elements.
# Each element is an (inputs, label) pair w2.train.element_spec
_____no_output_____
Apache-2.0
site/en/tutorials/structured_data/time_series.ipynb
jcjveraa/docs-2
Iterating over a `Dataset` yields concrete batches:
for example_inputs, example_labels in w2.train.take(1): print(f'Inputs shape (batch, time, features): {example_inputs.shape}') print(f'Labels shape (batch, time, features): {example_labels.shape}')
_____no_output_____
Apache-2.0
site/en/tutorials/structured_data/time_series.ipynb
jcjveraa/docs-2
Single step modelsThe simplest model you can build on this sort of data is one that predicts a single feature's value, 1 timestep (1h) in the future based only on the current conditions.So start by building models to predict the `T (degC)` value 1h into the future.![Predict the next time step](images/narrow_window.png...
single_step_window = WindowGenerator( input_width=1, label_width=1, shift=1, label_columns=['T (degC)']) single_step_window
_____no_output_____
Apache-2.0
site/en/tutorials/structured_data/time_series.ipynb
jcjveraa/docs-2
The `window` object creates `tf.data.Datasets` from the training, validation, and test sets, allowing you to easily iterate over batches of data.
for example_inputs, example_labels in single_step_window.train.take(1): print(f'Inputs shape (batch, time, features): {example_inputs.shape}') print(f'Labels shape (batch, time, features): {example_labels.shape}')
_____no_output_____
Apache-2.0
site/en/tutorials/structured_data/time_series.ipynb
jcjveraa/docs-2
BaselineBefore building a trainable model it would be good to have a performance baseline as a point for comparison with the later more complicated models.This first task is to predict temperature 1h in the future given the current value of all features. The current values include the current temperature. So start wit...
class Baseline(tf.keras.Model): def __init__(self, label_index=None): super().__init__() self.label_index = label_index def call(self, inputs): if self.label_index is None: return inputs result = inputs[:, :, self.label_index] return result[:, :, tf.newaxis]
_____no_output_____
Apache-2.0
site/en/tutorials/structured_data/time_series.ipynb
jcjveraa/docs-2