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
Write a Pandas program to add a prefix or suffix to all columns of a given DataFrame.
df = pd.DataFrame({'W':[68,75,86,80,66],'X':[78,85,96,80,86], 'Y':[84,94,89,83,86],'Z':[86,97,96,72,83]}); print("Original DataFrame") df print("\nAdd prefix:") df.add_prefix("A_") print("\nAdd suffix:") df.add_suffix("_1")
Add suffix:
MIT
Pandas_Exercise_Dataframe.ipynb
yaozeliang/pandas_share
Write a Pandas program to select columns by data type of a given DataFrame
df = pd.DataFrame({ 'name': ['Alberto Franco','Gino Mcneill','Ryan Parkes', 'Eesha Hinton', 'Syed Wharton'], 'date_of_birth': ['17/05/2002','16/02/1999','25/09/1998','11/05/2002','15/09/1997'], 'age': [18.5, 21.2, 22.5, 22, 23] }) df print("\nSelect numerical columns") df.select_dtypes(include = "number") ...
Select string columns
MIT
Pandas_Exercise_Dataframe.ipynb
yaozeliang/pandas_share
Write a Pandas program to rename all columns with the same pattern of a given DataFrame.
df = pd.DataFrame({ 'Name': ['Alberto Franco','Gino Mcneill','Ryan Parkes', 'Eesha Hinton', 'Syed Wharton'], 'Date_Of_Birth ': ['17/05/2002','16/02/1999','25/09/1998','11/05/2002','15/09/1997'], 'Age': [18.5, 21.2, 22.5, 22, 23] }) print("Original DataFrame") df df.columns = df.columns.str.lower().str.rstr...
Remove trailing (at the end) whitesapce and convert to lowercase of the columns name
MIT
Pandas_Exercise_Dataframe.ipynb
yaozeliang/pandas_share
Write a Pandas program to merge datasets and check uniqueness.
df = pd.DataFrame({ 'Name': ['Alberto Franco','Gino Mcneill','Ryan Parkes', 'Eesha Hinton', 'Syed Wharton'], 'Date_Of_Birth ': ['17/05/2002','16/02/1999','25/09/1998','11/05/2002','15/09/1997'], 'Age': [18.5, 21.2, 22.5, 22, 23] }) print("Original DataFrame:") print(df) df1 = df.copy(deep = True) df = df.dr...
“many_to_one” or “m:1”: check if merge keys are unique in right dataset:
MIT
Pandas_Exercise_Dataframe.ipynb
yaozeliang/pandas_share
Write a Pandas program to convert continuous values of a column in a given DataFrame to categorical.
df = pd.DataFrame({ 'name': ['Alberto Franco','Gino Mcneill','Ryan Parkes', 'Eesha Hinton', 'Syed Wharton', 'Kierra Gentry'], 'age': [18, 22, 85, 50, 80, 5] }) df df["age_groups"] = pd.cut(df["age"], bins = [0, 18, 65, 99], labels = ["kids", "adult", "elderly"]) df
_____no_output_____
MIT
Pandas_Exercise_Dataframe.ipynb
yaozeliang/pandas_share
Write a Pandas program to combine many given series to create a DataFrame.
sr1 = pd.Series(['php', 'python', 'java', 'c#', 'c++']) sr2 = pd.Series([1, 2, 3, 4, 5]) sr1 sr2 print("\nUsing pandas concat:") ser_df = pd.concat([sr1, sr2], axis = 1) ser_df ser_df = pd.DataFrame({"col1":sr1, "col2":sr2}) ser_df
_____no_output_____
MIT
Pandas_Exercise_Dataframe.ipynb
yaozeliang/pandas_share
Lab 12. Data Analysis in Python load data into pandas.dataframe
import pandas df = pandas.read_excel('s3://ksmithia241-2021spring/house_price.xls') df[:10]
_____no_output_____
MIT
lab12.ipynb
kendallsmith327/IA-241
2.1 unit price
df['unit_price']=df['price']/df['area'] df[:10]
_____no_output_____
MIT
lab12.ipynb
kendallsmith327/IA-241
2.2 house type
df['house_type'].value_counts()
_____no_output_____
MIT
lab12.ipynb
kendallsmith327/IA-241
2.3 average price more than two bathrooms
prc_more_2_bath=df.loc[ df ['bathroom']>2 ]['price'] print('avg price of houses more than 2 bathrooms is ${}'.format(prc_more_2_bath.mean()))
avg price of houses more than 2 bathrooms is $383645.45454545453
MIT
lab12.ipynb
kendallsmith327/IA-241
2.4 mean/median unit price
print('mean unit price is ${}'.format(df['unit_price'].mean())) print('median unit price is ${}'.format(df['unit_price'].median()))
median unit price is $130.13392857142858
MIT
lab12.ipynb
kendallsmith327/IA-241
2.5 avg price per house type
df.groupby('house_type').mean()['price']
_____no_output_____
MIT
lab12.ipynb
kendallsmith327/IA-241
2.6 predict price by house area
from scipy import stats result = stats.linregress(df['area'],df['price']) print('slope is {}'.format(result.slope)) print('intercept is {}'.format(result.intercept)) print('r square is {}'.format(result.rvalue*result.rvalue)) print('p value is {}'.format(result.pvalue))
slope is 79.95495729411489 intercept is 156254.76245096227 r square is 0.2343900121890692 p value is 0.001340065037461188
MIT
lab12.ipynb
kendallsmith327/IA-241
2.7 predict price of house 2,000 sqft
print('price of a house with {} sqft is ${}'.format(2000,2000*result.slope+result.intercept))
price of a house with 2000 sqft is $316164.67703919206
MIT
lab12.ipynb
kendallsmith327/IA-241
**Objective** **Learn computer vision fundamentals with the famous MNIST data** **importing libraries** 1. data load2. data preparation* Normalization* reshape* label encoding* spliting training and validation 3. introduction to convents4. saving submission file
import numpy as np import pandas as pd import tensorflow as tf import seaborn as sns np.random.seed(2) from sklearn.model_selection import train_test_split from sklearn.metrics import confusion_matrix import itertools from keras.utils.np_utils import to_categorical # convert to one-hot-encoding from keras.models impo...
Using TensorFlow backend.
MIT
digit_recognizer.ipynb
attaullahshafiq10/digit-recognizer
**load_Data**
# loading data train_data = pd.read_csv("train.csv") test_data = pd.read_csv("test.csv") # display first five rows of train_data train_data.head() test_data.head() # checking shape of train_data train_data.shape # # checking shape of test_data test_data.shape
_____no_output_____
MIT
digit_recognizer.ipynb
attaullahshafiq10/digit-recognizer
**Check for null and missing values**
# check the data train_data.describe() # check missing and null values test_data.isnull().sum() train_data.isnull().sum() Y_train = train_data["label"] # Drop 'label' column X_train = train_data.drop(labels = ["label"],axis = 1) # free some space del train_data g = sns.countplot(Y_train) Y_train.value_counts()
_____no_output_____
MIT
digit_recognizer.ipynb
attaullahshafiq10/digit-recognizer
There is no missing values in the train and test dataset. So we can safely go ahead. **Normalization** We perform a grayscale normalization to reduce the effect of illumination's differences.Moreover the CNN converg faster on [0..1] data than on [0..255].
# Normalize the data X_train= X_train / 255.0 test_data= test_data / 255.0
_____no_output_____
MIT
digit_recognizer.ipynb
attaullahshafiq10/digit-recognizer
**Reshape**
# Reshape image in 3 dimensions (height = 28px, width = 28px , channel = 1) X_train = X_train.values.reshape((-1,28,28,1)) test_data = test_data.values.reshape((-1,28,28,1)) test_data.shape
_____no_output_____
MIT
digit_recognizer.ipynb
attaullahshafiq10/digit-recognizer
**label_encoding**
# Encode labels to one hot vectors (ex : 2 -> [0,0,1,0,0,0,0,0,0,0]) Y_train = to_categorical(Y_train, num_classes = 10)
_____no_output_____
MIT
digit_recognizer.ipynb
attaullahshafiq10/digit-recognizer
**Split training and valdiation set**
# Set the random seed random_seed = 2 # Split the train and the validation set for the fitting X_train, X_val, Y_train, Y_val = train_test_split(X_train, Y_train, test_size = 0.1, random_state=random_seed)
_____no_output_____
MIT
digit_recognizer.ipynb
attaullahshafiq10/digit-recognizer
i choosed to split the train set in two parts : a small fraction (10%) became the validation set which the model is evaluated and the rest (90%) is used to train the model.
# Some examples import matplotlib.pyplot as plt h = plt.imshow(X_train[0][:,:,0]) k = plt.imshow(X_train[10][:,:,0])
_____no_output_____
MIT
digit_recognizer.ipynb
attaullahshafiq10/digit-recognizer
**Introduction to convnets**
from tensorflow.keras import layers from tensorflow.keras import models model = models.Sequential() model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1))) model.add(layers.MaxPooling2D((2, 2))) model.add(layers.Conv2D(64, (3, 3), activation='relu')) model.add(layers.MaxPooling2D((2, 2))) mode...
_____no_output_____
MIT
digit_recognizer.ipynb
attaullahshafiq10/digit-recognizer
Let’s display the architecture of the convnet so far.
model.summary()
Model: "sequential" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= conv2d (Conv2D) (None, 26, 26, 32) 320 ____________________________________...
MIT
digit_recognizer.ipynb
attaullahshafiq10/digit-recognizer
**Adding a classifier on top of the convnet**
model.add(layers.Flatten()) model.add(layers.Dense(64, activation='relu')) model.add(layers.Dense(10, activation='softmax'))
_____no_output_____
MIT
digit_recognizer.ipynb
attaullahshafiq10/digit-recognizer
We’ll do 10-way classification, using a final layer with 10 outputs and a softmax activation.Here’s what the network looks like now
model.summary() # Define the optimizer #optimizer = rmsprop(lr=0.001, rho=0.9, epsilon=1e-08, decay=0.0) learning_rate_reduction = ReduceLROnPlateau(monitor='val_acc', patience=3, verbose=1, ...
Train on 37800 samples Epoch 1/30 37800/37800 [==============================] - 35s 925us/sample - loss: 0.1917 - accuracy: 0.9388 Epoch 2/30 37800/37800 [==============================] - 34s 911us/sample - loss: 0.0513 - accuracy: 0.9834 Epoch 3/30 37800/37800 [==============================] - 34s 910us/sample - lo...
MIT
digit_recognizer.ipynb
attaullahshafiq10/digit-recognizer
Let’s evaluate the model on the test data.
test_loss, test_acc = model.evaluate(X_val, Y_val) test_acc results = model.predict(test_data) # select the indix with the maximum probability results = np.argmax(results,axis = 1) results = pd.Series(results,name="Label")
_____no_output_____
MIT
digit_recognizer.ipynb
attaullahshafiq10/digit-recognizer
**submission file**
submission = pd.concat([pd.Series(range(1,28001),name = "ImageId"),results],axis = 1) submission.to_csv("cnn_mnist_submission5.csv",index=False)
_____no_output_____
MIT
digit_recognizer.ipynb
attaullahshafiq10/digit-recognizer
Data Science TemplateBy Tobias Reaper --- Contents --- Description --- Introduction Business Question How does this help the business? Solution Overview- Assumptions:- Supervised model- Type of classification / regression / etc. Process- Data processing and exploration - Target engineering - Explore the data: types,...
# Basic imports import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns # ML / sklearn imports from sklearn.model_selection import train_test_split, RandomizedSearchCV from sklearn.ensemble import RandomForestClassifier # Configuration pd.options.display.max_columns = None # Suppre...
_____no_output_____
MIT
ds/practice/frameworks/ds_ml_template.ipynb
tobias-fyi/vela
Data import and overview- Preview of columns- Drop unneeded columns- Deal with null values- What are the data types and do any need to be fixed?
# Import ____ df = pd.read_csv() df.head() # Basic shape of data df.shape # Take a look at data types df.dtypes
_____no_output_____
MIT
ds/practice/frameworks/ds_ml_template.ipynb
tobias-fyi/vela
--- Data Exploration and Preprocessing Data types
# Convert dates to datetimes
_____no_output_____
MIT
ds/practice/frameworks/ds_ml_template.ipynb
tobias-fyi/vela
Init dataset
# Possible choices: 'GrabCut', 'Berkeley', 'DAVIS', 'COCO_MVal', 'SBD' DATASET = 'GrabCut' dataset = utils.get_dataset(DATASET, cfg)
_____no_output_____
MIT
notebooks/test_any_model.ipynb
aagaard/ritm_interactive_segmentation
Init model
from isegm.inference.predictors import get_predictor EVAL_MAX_CLICKS = 20 MODEL_THRESH = 0.49 checkpoint_path = utils.find_checkpoint(cfg.INTERACTIVE_MODELS_PATH, 'coco_lvis_h18s_itermask') model = utils.load_is_model(checkpoint_path, device) # Possible choices: 'NoBRS', 'f-BRS-A', 'f-BRS-B', 'f-BRS-C', 'RGB-BRS', '...
_____no_output_____
MIT
notebooks/test_any_model.ipynb
aagaard/ritm_interactive_segmentation
Dataset evaluation
TARGET_IOU = 0.9 all_ious, elapsed_time = evaluate_dataset(dataset, predictor, pred_thr=MODEL_THRESH, max_iou_thr=TARGET_IOU, max_clicks=EVAL_MAX_CLICKS) mean_spc, mean_spi = utils.get_time_metrics(all_ious, elapsed_time) noc_list, over_max_list = utils.compute_noc_metric(all...
_____no_output_____
MIT
notebooks/test_any_model.ipynb
aagaard/ritm_interactive_segmentation
Single sample eval
sample_id = 12 TARGET_IOU = 0.95 sample = dataset.get_sample(sample_id) gt_mask = sample.gt_mask clicks_list, ious_arr, pred = evaluate_sample(sample.image, gt_mask, predictor, pred_thr=MODEL_THRESH, max_iou_thr=TARGET_IOU, ...
_____no_output_____
MIT
notebooks/test_any_model.ipynb
aagaard/ritm_interactive_segmentation
Exploring the data So let's learn how we set up the data.
#default_exp validate #hide import os, sys, warnings #hide root = "D:/data_sets/24_garden" #os.chdir(root) #hide warnings.filterwarnings("ignore", category=RuntimeWarning) warnings.filterwarnings("ignore", category=UserWarning) #export from fastai2.vision.all import * #from garden2.utils import * from garden2.train i...
_____no_output_____
Apache-2.0
05_validate.ipynb
sso0090/garden2
StarGANGAN can not only generate fake realistic images, it can also generate fake images according to desired properties. StarGAN is able to ranslate an input image to any desired target domain. Given a source image and a few attributes we want(so called target domain) for the resulting image, StarGAN can generate des...
%matplotlib inline import os import numpy as np from solver import Solver from data_loader import get_loader from torch.backends import cudnn import torch import matplotlib.pyplot as plt from torchvision import transforms as T from torchvision.utils import save_image from PIL import Image from default_config import con...
_____no_output_____
MIT
StarGAN.ipynb
AZdet/summer_camp_GAN
Load model
# set config config.mode = 'test' config.dataset = 'CelebA' config.image_size = 256 config.c_dim = 5 config.selected_attrs = ['Black_Hair', 'Blond_Hair', 'Brown_Hair', 'Male', 'Young'] config.model_save_dir = 'stargan_celeba_256/models' config.result_dir = 'stargan_celeba_256/results' # solver solver = Solver(None, No...
/home/nbuser/anaconda3_420/lib/python3.5/site-packages/tensorflow/python/framework/dtypes.py:455: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'. _np_qint8 = np.dtype([("qint8", np.int8, 1)]) /home/nbuser...
MIT
StarGAN.ipynb
AZdet/summer_camp_GAN
Load image and transfer
face = detect_face('./images/02.jpg') plt.imshow(face) plt.show() generate_face(face)
Choose your desired hair color: 0 for Black_Hair, 1 for Blond_Hair, 2 for Brown_Hair 1 Choose the gender you desired: 0 for Female, 1 for Male1 Choose whether to generate aged, 0 for No, 1 for Yes: 0
MIT
StarGAN.ipynb
AZdet/summer_camp_GAN
Code to train and test Write the captions from json file:
import json import os, os.path import pickle train_val = json.load(open('videodatainfo_2017.json', 'r')) # combine all images and annotations together sentences = train_val['sentences'] # for efficiency lets group annotations by video itoa = {} for s in sentences: videoid_buf = s['video_id'] videoid = int(v...
_____no_output_____
MIT
Model-Train-Test-2D-Attention.ipynb
Curious-Geek/Video-Captioning
Auxilary functions to handle captions
import numpy as np """Functions to do the following: * Create vocabulary * Create dictionary mapping from word to word_id * Map words in captions to word_ids""" def build_vocab(word_count_thresh): """Function to create vocabulary based on word count threshold. Input: ...
_____no_output_____
MIT
Model-Train-Test-2D-Attention.ipynb
Curious-Geek/Video-Captioning
Train Test Validation Split
## Get the list of the files we have extracted features import os from sklearn.model_selection import train_test_split video_list = os.listdir('./DATA/features') videos = [] for item in video_list: videos.append(item.split('-')[0]) video_train, video_test = train_test_split(videos, test_size=0.1, random_state=42)...
Training Videos - 5890 Testing Videos - 728 Validation Videos - 655
MIT
Model-Train-Test-2D-Attention.ipynb
Curious-Geek/Video-Captioning
Auxillary functions to handle model build
import numpy as np import tensorflow as tf import glob import cv2 import imageio import pickle np.random.seed(0) #Global initializations n_lstm_steps = 30 DATA_DIR = './DATA/' VIDEO_DIR = DATA_DIR + 'features/' YOUTUBE_CLIPS_DIR = DATA_DIR + 'videos/' TEXT_DIR = DATA_DIR+'word_features/' pkl_file = open('./DATA/word_fe...
<EOS> 1
MIT
Model-Train-Test-2D-Attention.ipynb
Curious-Geek/Video-Captioning
Build the model to train
import numpy as np import tensorflow as tf import sys #GLOBAL VARIABLE INITIALIZATIONS TO BUILD MODEL n_steps = 30 hidden_dim = 500 frame_dim = 2048 batch_size = 1 vocab_size = len(word2id) bias_init_vector = get_bias_vector() n_steps_vocab = 30 def build_model(): """This function creates weight matrices that tran...
_____no_output_____
MIT
Model-Train-Test-2D-Attention.ipynb
Curious-Geek/Video-Captioning
Training Begins !!!
train()
Network config: N_Steps: 30 Hidden_dim:500 Frame_dim:2048 Batch_size:30 Vocab_size:29325 Created weights Video_input: (30, 59, 500) Video_output: (30, 59, 500) Caption_input: (30, 59, 1000) Caption_output: (30, 59, 500) INFO:tensorflow:Restoring parameters from ./ckpt_v4/model_58000.ckpt Restored model Iteration 0 ...
MIT
Model-Train-Test-2D-Attention.ipynb
Curious-Geek/Video-Captioning
Testing
def test(): with tf.Graph().as_default(): learning_rate = 0.00001 video,caption,caption_mask,output_logits,loss,dropout_prob = build_model() optim = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(loss) ckpt_file = './ckpt_v5/model_58000.ckpt.meta' saver = tf.t...
Network config: N_Steps: 30 Hidden_dim:500 Frame_dim:2048 Batch_size:1 Vocab_size:29325 Created weights Video_input: (1, 59, 500) Video_output: (1, 59, 500) Caption_input: (1, 59, 1000) Caption_output: (1, 59, 500) INFO:tensorflow:Restoring parameters from ./ckpt_v5/model_58000.ckpt Restored model 1 <BOS> a ............
MIT
Model-Train-Test-2D-Attention.ipynb
Curious-Geek/Video-Captioning
Attention
coding: utf-8 # In[1]: import tensorflow as tf import numpy as np import json import os from keras.layers.embeddings import Embedding from keras.models import Sequential from keras.layers import Dense, Activation, Input, GRU, Dropout from keras.optimizers import RMSprop from keras.layers.wrappers import TimeDistrib...
[?1h=top - 06:22:12 up 1:41, 4 users, load average: 1.11, 0.35, 0.12 Tasks: 193 total, 1 running, 192 sleeping, 0 stopped, 0 zombie %Cpu(s): 0.4 us, 0.3 sy...
MIT
Model-Train-Test-2D-Attention.ipynb
Curious-Geek/Video-Captioning
Updates to Assignment If you were working on the older version:* Please click on the "Coursera" icon in the top right to open up the folder directory. * Navigate to the folder: Week 3/ Planar data classification with one hidden layer. You can see your prior work in version 6b: "Planar data classification with one hi...
# Package imports import numpy as np import matplotlib.pyplot as plt from testCases_v2 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 np.random.seed(1) # set a seed so tha...
_____no_output_____
MIT
Neural-Networks-and-Deep-Learning/Week 3/Planar_data_classification_with_onehidden_layer.ipynb
vishwapardeshi/Deep-Learning
2 - Dataset First, let's get the dataset you will work on. The following code will load a "flower" 2-class dataset into variables `X` and `Y`.
X, Y = load_planar_dataset()
_____no_output_____
MIT
Neural-Networks-and-Deep-Learning/Week 3/Planar_data_classification_with_onehidden_layer.ipynb
vishwapardeshi/Deep-Learning
Visualize the dataset using matplotlib. The data looks like a "flower" with some red (label y=0) and some blue (y=1) points. Your goal is to build a model to fit this data. In other words, we want the classifier to define regions as either red or blue.
# Visualize the data: plt.scatter(X[0, :], X[1, :], c=Y, s=40, cmap=plt.cm.Spectral);
_____no_output_____
MIT
Neural-Networks-and-Deep-Learning/Week 3/Planar_data_classification_with_onehidden_layer.ipynb
vishwapardeshi/Deep-Learning
You have: - a numpy-array (matrix) X that contains your features (x1, x2) - a numpy-array (vector) Y that contains your labels (red:0, blue:1).Lets first get a better sense of what our data is like. **Exercise**: How many training examples do you have? In addition, what is the `shape` of the variables `X` and `Y`...
### START CODE HERE ### (≈ 3 lines of code) shape_X = X.shape shape_Y = Y.shape m = X.shape[1] # training set size ### END CODE HERE ### print ('The shape of X is: ' + str(shape_X)) print ('The shape of Y is: ' + str(shape_Y)) print ('I have m = %d training examples!' % (m))
The shape of X is: (2, 400) The shape of Y is: (1, 400) I have m = 400 training examples!
MIT
Neural-Networks-and-Deep-Learning/Week 3/Planar_data_classification_with_onehidden_layer.ipynb
vishwapardeshi/Deep-Learning
**Expected Output**: **shape of X** (2, 400) **shape of Y** (1, 400) **m** 400 3 - Simple Logistic RegressionBefore building a full neural network, lets first see how logistic regression performs on this problem. You can use sklearn's built-in functions to do that...
# Train the logistic regression classifier clf = sklearn.linear_model.LogisticRegressionCV(); clf.fit(X.T, Y.T);
_____no_output_____
MIT
Neural-Networks-and-Deep-Learning/Week 3/Planar_data_classification_with_onehidden_layer.ipynb
vishwapardeshi/Deep-Learning
You can now plot the decision boundary of these models. Run the code below.
# Plot the decision boundary for logistic regression plot_decision_boundary(lambda x: clf.predict(x), X, Y) plt.title("Logistic Regression") # Print accuracy LR_predictions = clf.predict(X.T) print ('Accuracy of logistic regression: %d ' % float((np.dot(Y,LR_predictions) + np.dot(1-Y,1-LR_predictions))/float(Y.size)*1...
Accuracy of logistic regression: 47 % (percentage of correctly labelled datapoints)
MIT
Neural-Networks-and-Deep-Learning/Week 3/Planar_data_classification_with_onehidden_layer.ipynb
vishwapardeshi/Deep-Learning
**Expected Output**: **Accuracy** 47% **Interpretation**: The dataset is not linearly separable, so logistic regression doesn't perform well. Hopefully a neural network will do better. Let's try this now! 4 - Neural Network modelLogistic regression did not work well on the "flower dataset". You are goi...
# GRADED FUNCTION: layer_sizes def layer_sizes(X, Y): """ Arguments: X -- input dataset of shape (input size, number of examples) Y -- labels of shape (output size, number of examples) Returns: n_x -- the size of the input layer n_h -- the size of the hidden layer n_y -- the size o...
The size of the input layer is: n_x = 5 The size of the hidden layer is: n_h = 4 The size of the output layer is: n_y = 2
MIT
Neural-Networks-and-Deep-Learning/Week 3/Planar_data_classification_with_onehidden_layer.ipynb
vishwapardeshi/Deep-Learning
**Expected Output** (these are not the sizes you will use for your network, they are just used to assess the function you've just coded). **n_x** 5 **n_h** 4 **n_y** 2 4.2 - Initialize the model's parameters **Exercise**: Implement the function `initialize_parameters()`...
# GRADED FUNCTION: initialize_parameters def initialize_parameters(n_x, n_h, n_y): """ Argument: n_x -- size of the input layer n_h -- size of the hidden layer n_y -- size of the output layer Returns: params -- python dictionary containing your parameters: W1 -- wei...
W1 = [[-0.00416758 -0.00056267] [-0.02136196 0.01640271] [-0.01793436 -0.00841747] [ 0.00502881 -0.01245288]] b1 = [[ 0.] [ 0.] [ 0.] [ 0.]] W2 = [[-0.01057952 -0.00909008 0.00551454 0.02292208]] b2 = [[ 0.]]
MIT
Neural-Networks-and-Deep-Learning/Week 3/Planar_data_classification_with_onehidden_layer.ipynb
vishwapardeshi/Deep-Learning
**Expected Output**: **W1** [[-0.00416758 -0.00056267] [-0.02136196 0.01640271] [-0.01793436 -0.00841747] [ 0.00502881 -0.01245288]] **b1** [[ 0.] [ 0.] [ 0.] [ 0.]] **W2** [[-0.01057952 -0.00909008 0.00551454 0.02292208]] **b2** [[ 0.]] 4.3 - The Loop **Qu...
# GRADED FUNCTION: forward_propagation def forward_propagation(X, parameters): """ Argument: X -- input data of size (n_x, m) parameters -- python dictionary containing your parameters (output of initialization function) Returns: A2 -- The sigmoid output of the second activation cache ...
0.262818640198 0.091999045227 -1.30766601287 0.212877681719
MIT
Neural-Networks-and-Deep-Learning/Week 3/Planar_data_classification_with_onehidden_layer.ipynb
vishwapardeshi/Deep-Learning
**Expected Output**: 0.262818640198 0.091999045227 -1.30766601287 0.212877681719 Now that you have computed $A^{[2]}$ (in the Python variable "`A2`"), which contains $a^{[2](i)}$ for every example, you can compute the cost function as follows:$$J = - \frac{1}{m} \sum\limits_{i = 1}^{m} \large{(} \small y^{(i)...
# GRADED FUNCTION: compute_cost def compute_cost(A2, Y, parameters): """ Computes the cross-entropy cost given in equation (13) Arguments: A2 -- The sigmoid output of the second activation, of shape (1, number of examples) Y -- "true" labels vector of shape (1, number of examples) paramete...
cost = 0.6930587610394646
MIT
Neural-Networks-and-Deep-Learning/Week 3/Planar_data_classification_with_onehidden_layer.ipynb
vishwapardeshi/Deep-Learning
**Expected Output**: **cost** 0.693058761... Using the cache computed during forward propagation, you can now implement backward propagation.**Question**: Implement the function `backward_propagation()`.**Instructions**:Backpropagation is usually the hardest (most mathematical) part in deep learning. To ...
# GRADED FUNCTION: backward_propagation def backward_propagation(parameters, cache, X, Y): """ Implement the backward propagation using the instructions above. Arguments: parameters -- python dictionary containing our parameters cache -- a dictionary containing "Z1", "A1", "Z2" and "A2". ...
dW1 = [[ 0.00301023 -0.00747267] [ 0.00257968 -0.00641288] [-0.00156892 0.003893 ] [-0.00652037 0.01618243]] db1 = [[ 0.00176201] [ 0.00150995] [-0.00091736] [-0.00381422]] dW2 = [[ 0.00078841 0.01765429 -0.00084166 -0.01022527]] db2 = [[-0.16655712]]
MIT
Neural-Networks-and-Deep-Learning/Week 3/Planar_data_classification_with_onehidden_layer.ipynb
vishwapardeshi/Deep-Learning
**Expected output**: **dW1** [[ 0.00301023 -0.00747267] [ 0.00257968 -0.00641288] [-0.00156892 0.003893 ] [-0.00652037 0.01618243]] **db1** [[ 0.00176201] [ 0.00150995] [-0.00091736] [-0.00381422]] **dW2** [[ 0.00078841 0.01765429 -0.00084166 -0.01022527]] **db2** ...
# GRADED FUNCTION: update_parameters def update_parameters(parameters, grads, learning_rate = 1.2): """ Updates parameters using the gradient descent update rule given above Arguments: parameters -- python dictionary containing your parameters grads -- python dictionary containing your gradie...
W1 = [[-0.00643025 0.01936718] [-0.02410458 0.03978052] [-0.01653973 -0.02096177] [ 0.01046864 -0.05990141]] b1 = [[ -1.02420756e-06] [ 1.27373948e-05] [ 8.32996807e-07] [ -3.20136836e-06]] W2 = [[-0.01041081 -0.04463285 0.01758031 0.04747113]] b2 = [[ 0.00010457]]
MIT
Neural-Networks-and-Deep-Learning/Week 3/Planar_data_classification_with_onehidden_layer.ipynb
vishwapardeshi/Deep-Learning
**Expected Output**: **W1** [[-0.00643025 0.01936718] [-0.02410458 0.03978052] [-0.01653973 -0.02096177] [ 0.01046864 -0.05990141]] **b1** [[ -1.02420756e-06] [ 1.27373948e-05] [ 8.32996807e-07] [ -3.20136836e-06]] **W2** [[-0.01041081 -0.04463285 0.01758031 0.04747113]] ...
# GRADED FUNCTION: nn_model def nn_model(X, Y, n_h, num_iterations = 10000, print_cost=False): """ Arguments: X -- dataset of shape (2, number of examples) Y -- labels of shape (1, number of examples) n_h -- size of the hidden layer num_iterations -- Number of iterations in gradient descent loo...
Cost after iteration 0: 0.692739 Cost after iteration 1000: 0.000218 Cost after iteration 2000: 0.000107 Cost after iteration 3000: 0.000071 Cost after iteration 4000: 0.000053 Cost after iteration 5000: 0.000042 Cost after iteration 6000: 0.000035 Cost after iteration 7000: 0.000030 Cost after iteration 8000: 0.000026...
MIT
Neural-Networks-and-Deep-Learning/Week 3/Planar_data_classification_with_onehidden_layer.ipynb
vishwapardeshi/Deep-Learning
**Expected Output**: **cost after iteration 0** 0.692739 $\vdots$ $\vdots$ **W1** [[-0.65848169 1.21866811] [-0.76204273 1.39377573] [ 0.5792005 -1.10397703] [ 0.76773391 -1.41477129]] **b1** [[ 0.287592 ] [ 0.3511264 ] [-0...
# GRADED FUNCTION: predict def predict(parameters, X): """ Using the learned parameters, predicts a class for each example in X Arguments: parameters -- python dictionary containing your parameters X -- input data of size (n_x, m) Returns predictions -- vector of predictions of o...
predictions mean = 0.666666666667
MIT
Neural-Networks-and-Deep-Learning/Week 3/Planar_data_classification_with_onehidden_layer.ipynb
vishwapardeshi/Deep-Learning
**Expected Output**: **predictions mean** 0.666666666667 It is time to run the model and see how it performs on a planar dataset. Run the following code to test your model with a single hidden layer of $n_h$ hidden units.
# Build a model with a n_h-dimensional hidden layer parameters = nn_model(X, Y, n_h = 4, num_iterations = 10000, print_cost=True) # Plot the decision boundary plot_decision_boundary(lambda x: predict(parameters, x.T), X, Y) plt.title("Decision Boundary for hidden layer size " + str(4))
Cost after iteration 0: 0.693048 Cost after iteration 1000: 0.288083 Cost after iteration 2000: 0.254385 Cost after iteration 3000: 0.233864 Cost after iteration 4000: 0.226792 Cost after iteration 5000: 0.222644 Cost after iteration 6000: 0.219731 Cost after iteration 7000: 0.217504 Cost after iteration 8000: 0.219471...
MIT
Neural-Networks-and-Deep-Learning/Week 3/Planar_data_classification_with_onehidden_layer.ipynb
vishwapardeshi/Deep-Learning
**Expected Output**: **Cost after iteration 9000** 0.218607
# Print accuracy predictions = predict(parameters, X) print ('Accuracy: %d' % float((np.dot(Y,predictions.T) + np.dot(1-Y,1-predictions.T))/float(Y.size)*100) + '%')
Accuracy: 90%
MIT
Neural-Networks-and-Deep-Learning/Week 3/Planar_data_classification_with_onehidden_layer.ipynb
vishwapardeshi/Deep-Learning
**Expected Output**: **Accuracy** 90% Accuracy is really high compared to Logistic Regression. The model has learnt the leaf patterns of the flower! Neural networks are able to learn even highly non-linear decision boundaries, unlike logistic regression. Now, let's try out several hidden layer sizes. 4.6...
# This may take about 2 minutes to run plt.figure(figsize=(16, 32)) hidden_layer_sizes = [1, 2, 3, 4, 5, 20, 50] for i, n_h in enumerate(hidden_layer_sizes): plt.subplot(5, 2, i+1) plt.title('Hidden Layer of size %d' % n_h) parameters = nn_model(X, Y, n_h, num_iterations = 5000) plot_decision_boundary(...
Accuracy for 1 hidden units: 67.5 % Accuracy for 2 hidden units: 67.25 % Accuracy for 3 hidden units: 90.75 % Accuracy for 4 hidden units: 90.5 % Accuracy for 5 hidden units: 91.25 % Accuracy for 20 hidden units: 90.0 % Accuracy for 50 hidden units: 90.25 %
MIT
Neural-Networks-and-Deep-Learning/Week 3/Planar_data_classification_with_onehidden_layer.ipynb
vishwapardeshi/Deep-Learning
**Interpretation**:- The larger models (with more hidden units) are able to fit the training set better, until eventually the largest models overfit the data. - The best hidden layer size seems to be around n_h = 5. Indeed, a value around here seems to fits the data well without also incurring noticeable overfitting.-...
# Datasets noisy_circles, noisy_moons, blobs, gaussian_quantiles, no_structure = load_extra_datasets() datasets = {"noisy_circles": noisy_circles, "noisy_moons": noisy_moons, "blobs": blobs, "gaussian_quantiles": gaussian_quantiles} ### START CODE HERE ### (choose your dataset) dat...
_____no_output_____
MIT
Neural-Networks-and-Deep-Learning/Week 3/Planar_data_classification_with_onehidden_layer.ipynb
vishwapardeshi/Deep-Learning
Lambda School Data Science - A First Look at Data Lecture - let's explore Python DS libraries and examples!The Python Data Science ecosystem is huge. You've seen some of the big pieces - pandas, scikit-learn, matplotlib. What parts do you want to see more of?
# TODO - we'll be doing this live, taking requests # and reproducing what it is to look up and learn things drinks = ['coke', 'sprite', 'juice', 'water']
_____no_output_____
MIT
module1-afirstlookatdata/LS_DS_111_A_First_Look_at_Data.ipynb
BaiganKing/DS-Unit-1-Sprint-1-Dealing-With-Data
Assignment - now it's your turnPick at least one Python DS library, and using documentation/examples reproduce in this notebook something cool. It's OK if you don't fully understand it or get it 100% working, but do put in effort and look things up.
# TODO - your code here # Use what we did live in lecture as an example import pandas as pd import numpy as np import matplotlib.pyplot as plt import statsmodels.api as sm import statsmodels.discrete.discrete_model as smdis import statsmodels.stats.outliers_influence as outliers from google.colab import files uploaded ...
_____no_output_____
MIT
module1-afirstlookatdata/LS_DS_111_A_First_Look_at_Data.ipynb
BaiganKing/DS-Unit-1-Sprint-1-Dealing-With-Data
Mode fittingHere we will make a simple hierarchical model that encodes some knowledge of quasi-equally spaced modes of oscillation into the prior. Using data from papers:
import numpy as np import matplotlib.pyplot as plt from scipy import signal import seaborn as sns import pystan
_____no_output_____
MIT
JoshFiles/Stan Practice/Mode_Fitting.ipynb
daw538/y4project
Spectral analysis of a signal generated by a sum of 14 cosine waves whose frequencies follow: $f_{n, {\rm true}} = (n + 0.5) \Delta \nu + \mathcal{N}(0, 0.02)$.Then spectral analysis identifies the component frequencies and from this the frequency spacing can be found.
def gaussian(f, f0, h, w): return h * np.exp(-0.5 * (f - f0)**2 / w**2) fs = 10e3 N = 1e5 dnu = 2.0 numax = 14.0 time = np.arange(N) / fs f0s = (np.arange(0, 14, 1) + 0.5) * dnu #f0s += np.random.randn(len(f0s)) * 0.02 x = 0 for n in f0s: #print(gaussian(n, numax, 25.0, 5.0)) x += gaussian(n, numax, 25.0...
_____no_output_____
MIT
JoshFiles/Stan Practice/Mode_Fitting.ipynb
daw538/y4project
Can find $\Delta\nu$ by calculating the distance between 2 adjacent peaks:
peaks = signal.find_peaks(Pxx_den, 3) for i in range(len(peaks[0])-1): print(f[peaks[0][i+1]]-f[peaks[0][i]]) bin_width = f[1] - f[0] w = int(dnu / bin_width) s = 0 h = int(np.floor(len(Pxx_den[s:]) / w)) print(len(Pxx_den[s:])) print(h,w) ladder_p = np.reshape(Pxx_den[s:h*w+s], [h, w]) ladder_f = np.reshape(f[s:h*...
_____no_output_____
MIT
JoshFiles/Stan Practice/Mode_Fitting.ipynb
daw538/y4project
Guy's CodeLet's set up the data first. We will define a bunch of Lorentzian modes that are nearly equally spaced in frequency. The mode heights will be controlled by a Gaussian function. So the mode frequencies will be defined as:$f_{n, {\rm true}} = (n + 0.5) \Delta \nu + \mathcal{N}(0, 0.02)$.and the envelope (hei...
def lor(f, f0, w, h): return h / (1.0 + 4.0 * ((f - f0)/w)**2) def gaussian(f, f0, h, w): return h * np.exp(-0.5 * (f - f0)**2 / w**2) np.random.seed(53) f = np.linspace(0, 28, 1000) dnu = 2.0 numax = 14.0 f0s = (np.arange(0, 14, 1) + 0.5) * dnu f0s += np.random.randn(len(f0s)) * 0.02 #f_n,true true = np.on...
_____no_output_____
MIT
JoshFiles/Stan Practice/Mode_Fitting.ipynb
daw538/y4project
We now transform the data into a ladder, or echelle, with one mode in each segment.
bin_width = f[1] - f[0] print(bin_width) w = int(dnu / bin_width) print(len(data[s:]), w) s = 0 h = int(np.floor(len(data[s:]) / w)) ladder_p = np.reshape(data[s:h*w+s], [h, w]) ladder_f = np.reshape(f[s:h*w+s], [h, w])
0.1 1000 20
MIT
JoshFiles/Stan Practice/Mode_Fitting.ipynb
daw538/y4project
We can collapse the echelle and combine with some smoothing techniques to show you the data:
from astropy.convolution import Gaussian1DKernel, convolve fig, ax = plt.subplots() ax.plot(ladder_f[0,:] / dnu, np.mean(ladder_p, axis=0)) # Create kernel g = Gaussian1DKernel(stddev=5) # Convolve data z = convolve(np.mean(ladder_p, axis=0), g) ax.plot(ladder_f[0,:] / dnu, z, 'k-', lw=2) # Create kernel g = Gaussian1D...
_____no_output_____
MIT
JoshFiles/Stan Practice/Mode_Fitting.ipynb
daw538/y4project
Now we can plot the uncollapsed echelle:
fig, ax = plt.subplots(nn) for i in range(int(nn)): ax[i].plot(d_f, ladder_p[i,:], label=f'Index: {i}') ax[i].set_yticks([]) plt.subplots_adjust(hspace=0.0, wspace=0.0) #print(len(ladder_f[0,:])) #print(len(ladder_p[:,0])) #print(ladder_f) #print(ladder_p)
71 14 [[ 0. 0.02802803 0.05605606 0.08408408 0.11211211 0.14014014 0.16816817 0.1961962 0.22422422 0.25225225 0.28028028 0.30830831 0.33633634 0.36436436 0.39239239 0.42042042 0.44844845 0.47647648 0.5045045 0.53253253 0.56056056 0.58858859 0.61661662 0.64464464 0.67267267 0.7...
MIT
JoshFiles/Stan Practice/Mode_Fitting.ipynb
daw538/y4project
And now we build the example Pystan model:
code = ''' functions { real lor(real freq, real f0, real w, real h){ return h / (1 + 4 * ((freq - f0)/w)^2); } real gaussian(real f, real numax, real width, real height){ return height * exp(-0.5 * (f - numax)^2 / width^2); } } data { int N; // Data points per order int M; // Num...
INFO:pystan:COMPILING THE C++ CODE FOR MODEL anon_model_ae1e6452f5130395d3f50a4387192288 NOW.
MIT
JoshFiles/Stan Practice/Mode_Fitting.ipynb
daw538/y4project
The code takes a while to converge. We run for 20000 iterations and check the results.
stan_data = {'N': len(ladder_f[0,:]), 'M': len(ladder_p[:,0]), 'freq': ladder_f, 'snr': ladder_p, 'dnu_est': dnu, 'numax_est': numax} nchains = 4 start = {'dnu': dnu, 'numax': numax} fitsm = sm.sampling(data=stan_data, iter=20000, chains=nchains, init=[start for n in range(nchains)]) fitsm.plo...
Inference for Stan model: anon_model_ae1e6452f5130395d3f50a4387192288. 4 chains, each with iter=20000; warmup=10000; thin=1; post-warmup draws per chain=10000, total post-warmup draws=40000. mean se_mean sd 2.5% 25% 50% 75% 97.5% n_eff Rhat dnu 2.0 9.9e-6 9.1e-4 ...
MIT
JoshFiles/Stan Practice/Mode_Fitting.ipynb
daw538/y4project
The convergence is good! (The nan Rhat is because the dnu value is so well constrained). We can check the inferred frequencies with respect to the true frequencies:
fig, ax = plt.subplots() ax.scatter(f0s, fitsm['mode_freqs'].mean(axis=0) - f0s) ax.errorbar(f0s, fitsm['mode_freqs'].mean(axis=0) - f0s, yerr=fitsm['mode_freqs'].std(axis=0)) print(fitsm['mode_freqs'].shape) print(f0s.shape)
(40000, 14) (14,)
MIT
JoshFiles/Stan Practice/Mode_Fitting.ipynb
daw538/y4project
Here is a corner plot of the results:
import corner post = np.vstack([fitsm['dnu'], fitsm['numax'], fitsm['envheight'], fitsm['envwidth'], fitsm['modewidth']]).T corner.corner(post) plt.show()
_____no_output_____
MIT
JoshFiles/Stan Practice/Mode_Fitting.ipynb
daw538/y4project
We can now compare the true model with the estimated model:
best = np.ones(len(f)) best += np.sum([lor(f, n, fitsm['modewidth'].mean(), gaussian(n, fitsm['numax'].mean(), fitsm['envheight'].mean(), fitsm['envwidth'].mean()) ) for n in fitsm['mode_freqs'].mean(axis=0)], axis=0) plt.plot(f, best, 'k-.', label='best', zorder=99) plt.p...
_____no_output_____
MIT
JoshFiles/Stan Practice/Mode_Fitting.ipynb
daw538/y4project
Copyright 2018 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/guide/distribute_strategy.ipynb
MoniqueGautier/docs
Distributed Training in TensorFlow View on TensorFlow.org Run in Google Colab View source on GitHub Overview`tf.distribute.Strategy` is a TensorFlow API to distribute trainingacross multiple GPUs, multiple machines or TPUs. Using this API, users can distribute their existing models and training ...
# Import TensorFlow from __future__ import absolute_import, division, print_function, unicode_literals !pip install tf-nightly-gpu import tensorflow as tf
_____no_output_____
Apache-2.0
site/en/guide/distribute_strategy.ipynb
MoniqueGautier/docs
Types of strategies`tf.distribute.Strategy` intends to cover a number of use cases along different axes. Some of these combinations are currently supported and others will be added in the future. Some of these axes are:* Syncronous vs asynchronous training: These are two common ways of distributing training with data ...
mirrored_strategy = tf.distribute.MirroredStrategy()
_____no_output_____
Apache-2.0
site/en/guide/distribute_strategy.ipynb
MoniqueGautier/docs
This will create a `MirroredStrategy` instance which will use all the GPUs that are visible to TensorFlow, and use NCCL as the cross device communication.If you wish to use only some of the GPUs on your machine, you can do so like this:
mirrored_strategy = tf.distribute.MirroredStrategy(devices=["/gpu:0", "/gpu:1"])
_____no_output_____
Apache-2.0
site/en/guide/distribute_strategy.ipynb
MoniqueGautier/docs
If you wish to override the cross device communication, you can do so using the `cross_device_ops` argument by supplying an instance of `tf.distribute.CrossDeviceOps`. Currently we provide `tf.distribute.HierarchicalCopyAllReduce` and `tf.distribute.ReductionToOneDevice` as 2 other options other than `tf.distribute.Ncc...
mirrored_strategy = tf.distribute.MirroredStrategy( cross_device_ops=tf.distribute.HierarchicalCopyAllReduce())
_____no_output_____
Apache-2.0
site/en/guide/distribute_strategy.ipynb
MoniqueGautier/docs
CentralStorageStrategy`tf.distribute.experimental.CentralStorageStrategy` does synchronous training as well. Variables are not mirrored, instead they are placed on the CPU and operations are replicated across all local GPUs. If there is only one GPU, all variables and operations will be placed on that GPU.Create a `Ce...
central_storage_strategy = tf.distribute.experimental.CentralStorageStrategy()
_____no_output_____
Apache-2.0
site/en/guide/distribute_strategy.ipynb
MoniqueGautier/docs
This will create a `CentralStorageStrategy` instance which will use all visible GPUs and CPU. Update to variables on replicas will be aggragated before being applied to variables. Note: This strategy is [`experimental`](https://www.tensorflow.org/guide/version_compatwhat_is_not_covered) as we are currently improving it...
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy()
_____no_output_____
Apache-2.0
site/en/guide/distribute_strategy.ipynb
MoniqueGautier/docs
`MultiWorkerMirroredStrategy` currently allows you to choose between two different implementations of collective ops. `CollectiveCommunication.RING` implements ring-based collectives using gRPC as the communication layer. `CollectiveCommunication.NCCL` uses [Nvidia's NCCL](https://developer.nvidia.com/nccl) to implem...
multiworker_strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy( tf.distribute.experimental.CollectiveCommunication.NCCL)
_____no_output_____
Apache-2.0
site/en/guide/distribute_strategy.ipynb
MoniqueGautier/docs
One of the key differences to get multi worker training going, as compared to multi-GPU training, is the multi-worker setup. "TF_CONFIG" environment variable is the standard way in TensorFlow to specify the cluster configuration to each worker that is part of the cluster. See section on ["TF_CONFIG" below](TF_CONFIG) f...
mirrored_strategy = tf.distribute.MirroredStrategy() with mirrored_strategy.scope(): model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))]) model.compile(loss='mse', optimizer='sgd')
_____no_output_____
Apache-2.0
site/en/guide/distribute_strategy.ipynb
MoniqueGautier/docs
In this example we used `MirroredStrategy` so we can run this on a machine with multiple GPUs. `strategy.scope()` indicated which parts of the code to run distributed. Creating a model inside this scope allows us to create mirrored variables instead of regular variables. Compiling under the scope allows us to know that...
dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100).batch(10) model.fit(dataset, epochs=2) model.evaluate(dataset)
_____no_output_____
Apache-2.0
site/en/guide/distribute_strategy.ipynb
MoniqueGautier/docs
Here we used a `tf.data.Dataset` to provide the training and eval input. You can also use numpy arrays:
import numpy as np inputs, targets = np.ones((100, 1)), np.ones((100, 1)) model.fit(inputs, targets, epochs=2, batch_size=10)
_____no_output_____
Apache-2.0
site/en/guide/distribute_strategy.ipynb
MoniqueGautier/docs
In both cases (dataset or numpy), each batch of the given input is divided equally among the multiple replicas. For instance, if using `MirroredStrategy` with 2 GPUs, each batch of size 10 will get divided among the 2 GPUs, with each receiving 5 input examples in each step. Each epoch will then train faster as you add ...
# Compute global batch size using number of replicas. BATCH_SIZE_PER_REPLICA = 5 global_batch_size = (BATCH_SIZE_PER_REPLICA * mirrored_strategy.num_replicas_in_sync) dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(100) dataset = dataset.batch(global_batch_size) LEARNING_RATES_BY_BATCH...
_____no_output_____
Apache-2.0
site/en/guide/distribute_strategy.ipynb
MoniqueGautier/docs
What's supported now?In [TF nightly release](https://pypi.org/project/tf-nightly-gpu/), we now support training with Keras using all strategies.Note: When using `MultiWorkerMirorredStrategy` for multiple workers or `TPUStrategy` with more than one host with Keras, currently the user will have to explicitly shard or sh...
mirrored_strategy = tf.distribute.MirroredStrategy() config = tf.estimator.RunConfig( train_distribute=mirrored_strategy, eval_distribute=mirrored_strategy) regressor = tf.estimator.LinearRegressor( feature_columns=[tf.feature_column.numeric_column('feats')], optimizer='SGD', config=config)
_____no_output_____
Apache-2.0
site/en/guide/distribute_strategy.ipynb
MoniqueGautier/docs
We use a premade Estimator here, but the same code works with a custom Estimator as well. `train_distribute` determines how training will be distributed, and `eval_distribute` determines how evaluation will be distributed. This is another difference from Keras where we use the same strategy for both training and eval.N...
def input_fn(): dataset = tf.data.Dataset.from_tensors(({"feats":[1.]}, [1.])) return dataset.repeat(1000).batch(10) regressor.train(input_fn=input_fn, steps=10) regressor.evaluate(input_fn=input_fn, steps=10)
_____no_output_____
Apache-2.0
site/en/guide/distribute_strategy.ipynb
MoniqueGautier/docs
Another difference to highlight here between Estimator and Keras is the input handling. In Keras, we mentioned that each batch of the dataset is split across the multiple replicas. In Estimator, however, the user provides an `input_fn` and have full control over how they want their data to be distributed across workers...
with mirrored_strategy.scope(): model = tf.keras.Sequential([tf.keras.layers.Dense(1, input_shape=(1,))]) optimizer = tf.train.GradientDescentOptimizer(0.1)
_____no_output_____
Apache-2.0
site/en/guide/distribute_strategy.ipynb
MoniqueGautier/docs
Next, we create the input dataset and call `make_dataset_iterator` to distribute the dataset based on the strategy. This API is expected to change in the near future.
with mirrored_strategy.scope(): dataset = tf.data.Dataset.from_tensors(([1.], [1.])).repeat(1000).batch( global_batch_size) input_iterator = mirrored_strategy.make_dataset_iterator(dataset)
_____no_output_____
Apache-2.0
site/en/guide/distribute_strategy.ipynb
MoniqueGautier/docs
Then, we define one step of the training. We will use `tf.GradientTape` to compute gradients and optimizer to apply those gradients to update our model's variables. To distribute this training step, we put it in a function `step_fn` and pass it to `strategy.experimental_run` along with the iterator created before:
def train_step(): def step_fn(inputs): features, labels = inputs logits = model(features) cross_entropy = tf.nn.softmax_cross_entropy_with_logits( logits=logits, labels=labels) loss = tf.reduce_sum(cross_entropy) * (1.0 / global_batch_size) train_op = optimizer.minimize(loss) with tf.c...
_____no_output_____
Apache-2.0
site/en/guide/distribute_strategy.ipynb
MoniqueGautier/docs
A few other things to note in the code above:1. We used `tf.nn.softmax_cross_entropy_with_logits` to compute the loss. And then we scaled the total loss by the global batch size. This is important because all the replicas are training in sync and number of examples in each step of training is the global batch. So the l...
with mirrored_strategy.scope(): iterator_init = input_iterator.initialize() var_init = tf.global_variables_initializer() loss = train_step() with tf.Session() as sess: sess.run([iterator_init, var_init]) for _ in range(10): print(sess.run(loss))
_____no_output_____
Apache-2.0
site/en/guide/distribute_strategy.ipynb
MoniqueGautier/docs
Sentiment analysisDataset used: IMDb movies dataset(http://ai.stanford.edu/~amaas/data/sentiment/aclImdb_v1.tar.gz)
import pyprind import pandas as pd import os import io """ Organise the given dataset into operatable datastructure We shall use Pandas DataFrames """ pbar = pyprind.ProgBar(50000) labels = {'pos':1, 'neg':0} df = pd.DataFrame() for s in ('test', 'train'): for l in ('pos', 'neg'): path = './aclImdb/%s/%s'...
_____no_output_____
MIT
.ipynb_checkpoints/sentiment_analysis-checkpoint.ipynb
prakharchoudhary/SentimentalAnalysis
Training a logistic regression model for document classification
# Added version check for recent scikit-learn 0.18 checks from distutils.version import LooseVersion as Version from sklearn import __version__ as sklearn_version #we will use simple bag-of-words model X_train = df.loc[:25000, 'review'].values y_train = df.loc[:25000, 'sentiment'].values X_test = df.loc[25000:, 'review...
Test Accuracy: 0.901
MIT
.ipynb_checkpoints/sentiment_analysis-checkpoint.ipynb
prakharchoudhary/SentimentalAnalysis
Start Comment:
""" Please note that gs_lr_tfidf.best_score_ is the average k-fold cross-validation score. I.e., if we have a GridSearchCV object with 5-fold cross-validation (like the one above), the best_score_ attribute returns the average score over the 5-folds of the best model. """ from sklearn.linear_model import LogisticReg...
_____no_output_____
MIT
.ipynb_checkpoints/sentiment_analysis-checkpoint.ipynb
prakharchoudhary/SentimentalAnalysis