markdown stringlengths 0 37k | code stringlengths 1 33.3k | path stringlengths 8 215 | repo_name stringlengths 6 77 | license stringclasses 15
values |
|---|---|---|---|---|
The use of watermark is optional. You can install this IPython extension via "pip install watermark". For more information, please see: https://github.com/rasbt/watermark.
Overview
Dealing with missing data
Eliminating samples or features with missing values
Imputing missing values
Understanding the scikit-learn estim... | from IPython.display import Image
%matplotlib inline
# Added version check for recent scikit-learn 0.18 checks
from distutils.version import LooseVersion as Version
from sklearn import __version__ as sklearn_version
| code/ch04/ch04.ipynb | 1iyiwei/pyml | mit |
Dealing with missing data
The training data might be incomplete due to various reasons
* data collection error
* measurements not applicable
* etc.
Most machine learning algorithms/implementations cannot robustly deal with missing data
Thus we need to deal with missing data before training models
We use pandas (Python ... | import pandas as pd
from io import StringIO
csv_data = '''A,B,C,D
1.0,2.0,3.0,4.0
5.0,6.0,,8.0
10.0,11.0,12.0,'''
# If you are using Python 2.7, you need
# to convert the string to unicode:
# csv_data = unicode(csv_data)
df = pd.read_csv(StringIO(csv_data))
df | code/ch04/ch04.ipynb | 1iyiwei/pyml | mit |
The columns (A, B, C, D) are features.
The rows (0, 1, 2) are samples.
Missing values become NaN (not a number). | df.isnull()
df.isnull().sum(axis=0) | code/ch04/ch04.ipynb | 1iyiwei/pyml | mit |
Eliminating samples or features with missing values
One simple strategy is to simply eliminate samples (table rows) or features (table columns) with missing values, based on various criteria. | # the default is to drop samples/rows
df.dropna()
# but we can also elect to drop features/columns
df.dropna(axis=1)
# only drop rows where all columns are NaN
df.dropna(how='all')
# drop rows that have not at least 4 non-NaN values
df.dropna(thresh=4)
# only drop rows where NaN appear in specific columns (here: ... | code/ch04/ch04.ipynb | 1iyiwei/pyml | mit |
Dropping data might not be desirable, as the resulting data set might become too small.
Imputing missing values
Interpolating missing values from existing ones can preserve the original data better.
Impute: the process of replacing missing data with substituted values
<a href="https://en.wikipedia.org/wiki/Imputation_(... | from sklearn.preprocessing import Imputer
# options from the imputer library includes mean, median, most_frequent
imr = Imputer(missing_values='NaN', strategy='mean', axis=0)
imr = imr.fit(df)
imputed_data = imr.transform(df.values)
imputed_data | code/ch04/ch04.ipynb | 1iyiwei/pyml | mit |
For example, 7.5 is the average of 3 and 12.
6 is the average of 4 and 8. | df.values | code/ch04/ch04.ipynb | 1iyiwei/pyml | mit |
We can do better than this, by selecting only the most similar rows for interpolation, instead of all rows. This is how recommendation system could work, e.g. predict your potential rating of a movie or book you have not seen based on item ratings from you and other users.
<i>Programming Collective Intelligence: Buildi... | import pandas as pd
df = pd.DataFrame([['green', 'M', 10.1, 'class1'],
['red', 'L', 13.5, 'class2'],
['blue', 'XL', 15.3, 'class1']])
df.columns = ['color', 'size', 'price', 'classlabel']
df | code/ch04/ch04.ipynb | 1iyiwei/pyml | mit |
Data conversion
For some estimators such as decision trees that handle one feature at a time, it is OK to keep the features as they are.
However for other estimators that need to handle multiple features together, we need to convert them into compatible forms before proceeding:
1. convert categorical values into numeri... | size_mapping = {'XL': 3,
'L': 2,
'M': 1}
df['size'] = df['size'].map(size_mapping)
df
inv_size_mapping = {v: k for k, v in size_mapping.items()}
df['size'].map(inv_size_mapping) | code/ch04/ch04.ipynb | 1iyiwei/pyml | mit |
Encoding class labels
Class labels often need to be represented as integers for machine learning libraries
* not ordinal, so any integer mapping will do
* but a good idea and convention is to use consecutive small values like 0, 1, ... | import numpy as np
class_mapping = {label: idx for idx, label in enumerate(np.unique(df['classlabel']))}
class_mapping
# forward map
df['classlabel'] = df['classlabel'].map(class_mapping)
df
# inverse map
inv_class_mapping = {v: k for k, v in class_mapping.items()}
df['classlabel'] = df['classlabel'].map(inv_class_m... | code/ch04/ch04.ipynb | 1iyiwei/pyml | mit |
We can use LabelEncoder in scikit learn to convert class labels automatically. | from sklearn.preprocessing import LabelEncoder
class_le = LabelEncoder()
y = class_le.fit_transform(df['classlabel'].values)
y
class_le.inverse_transform(y) | code/ch04/ch04.ipynb | 1iyiwei/pyml | mit |
Performing one-hot encoding on nominal features
However, unlike class labels, we cannot just convert nominal features (such as colors) directly into integers.
A common mistake is to map nominal features into numerical values, e.g. for colors
* blue $\rightarrow$ 0
* green $\rightarrow$ 1
* red $\rightarrow$ 2 | X = df[['color', 'size', 'price']].values
color_le = LabelEncoder()
X[:, 0] = color_le.fit_transform(X[:, 0])
X | code/ch04/ch04.ipynb | 1iyiwei/pyml | mit |
For categorical features, it is important to keep the mapped values "equal distance"
* unless you have good reasons otherwise
For example, for colors red, green, blue, we want to convert them to values so that each color has equal distance from one another.
This cannot be done in 1D but doable in 2D (how? think about i... | from sklearn.preprocessing import OneHotEncoder
ohe = OneHotEncoder(categorical_features=[0])
ohe.fit_transform(X).toarray()
# automatic conversion via the get_dummies method in pd
pd.get_dummies(df[['price', 'color', 'size']])
df | code/ch04/ch04.ipynb | 1iyiwei/pyml | mit |
Partitioning a dataset in training and test sets
Training set to train the models
Test set to evaluate the trained models
Separate the two to avoid over-fitting
* well trained models should generalize to unseen, test data
Validation set for tuning hyper-parameters
* parameters are trained by algorithms
* hyper-paramete... | wine_data_remote = 'https://archive.ics.uci.edu/ml/machine-learning-databases/wine/wine.data'
wine_data_local = '../datasets/wine/wine.data'
df_wine = pd.read_csv(wine_data_local,
header=None)
df_wine.columns = ['Class label', 'Alcohol', 'Malic acid', 'Ash',
'Alcalinity of ash... | code/ch04/ch04.ipynb | 1iyiwei/pyml | mit |
<hr>
Note:
If the link to the Wine dataset provided above does not work for you, you can find a local copy in this repository at ./../datasets/wine/wine.data.
Or you could fetch it via | df_wine = pd.read_csv('https://raw.githubusercontent.com/1iyiwei/pyml/master/code/datasets/wine/wine.data', header=None)
df_wine.columns = ['Class label', 'Alcohol', 'Malic acid', 'Ash',
'Alcalinity of ash', 'Magnesium', 'Total phenols',
'Flavanoids', 'Nonflavanoid phenols', 'Proanthocyanins',
'Color intensity', 'H... | code/ch04/ch04.ipynb | 1iyiwei/pyml | mit |
How to allocate training and test proportions?
As much training data as possible for accurate model
As much test data as possible for evaluation
Usual rules is 60:40, 70:30, 80:20
Larger datasets can have more portions for training
* e.g. 90:10
Other partitions possible
* talk about later in model evaluation and parame... | if Version(sklearn_version) < '0.18':
from sklearn.cross_validation import train_test_split
else:
from sklearn.model_selection import train_test_split
X, y = df_wine.iloc[:, 1:].values, df_wine.iloc[:, 0].values
X_train, X_test, y_train, y_test = \
train_test_split(X, y, test_size=0.3, random_state=0)
... | code/ch04/ch04.ipynb | 1iyiwei/pyml | mit |
Bringing features onto the same scale
Most machine learning algorithms behave better when features are on similar scales.
Exceptions
* decision trees
* random forests
Example
Two features, in scale [0 1] and [0 100000]
Think about what happens when we apply
* perceptron
* KNN
Two common approaches
Normalization
min-ma... | from sklearn.preprocessing import MinMaxScaler
mms = MinMaxScaler()
X_train_norm = mms.fit_transform(X_train)
X_test_norm = mms.transform(X_test)
from sklearn.preprocessing import StandardScaler
stdsc = StandardScaler()
X_train_std = stdsc.fit_transform(X_train)
X_test_std = stdsc.transform(X_test) | code/ch04/ch04.ipynb | 1iyiwei/pyml | mit |
Toy case: standardization versus normalization | ex = pd.DataFrame([0, 1, 2, 3, 4, 5])
# standardize
ex[1] = (ex[0] - ex[0].mean()) / ex[0].std(ddof=0)
# Please note that pandas uses ddof=1 (sample standard deviation)
# by default, whereas NumPy's std method and the StandardScaler
# uses ddof=0 (population standard deviation)
# normalize
ex[2] = (ex[0] - ex[0].mi... | code/ch04/ch04.ipynb | 1iyiwei/pyml | mit |
Selecting meaningful features
Overfitting is a common problem for machine learning.
* model fits training data too closely and fails to generalize to real data
* model too complex for the given training data
<img src="./images/03_06.png" width=80%>
Ways to address overfitting
Collect more training data (to make overf... | from sklearn.linear_model import LogisticRegression
# l1 regularization
lr = LogisticRegression(penalty='l1', C=0.1)
lr.fit(X_train_std, y_train)
# compare training and test accuracy to see if there is overfitting
print('Training accuracy:', lr.score(X_train_std, y_train))
print('Test accuracy:', lr.score(X_test_std,... | code/ch04/ch04.ipynb | 1iyiwei/pyml | mit |
Plot regularization
$C$ is inverse to the regularization strength | import matplotlib.pyplot as plt
fig = plt.figure()
ax = plt.subplot(111)
colors = ['blue', 'green', 'red', 'cyan',
'magenta', 'yellow', 'black',
'pink', 'lightgreen', 'lightblue',
'gray', 'indigo', 'orange']
weights, params = [], []
for c in np.arange(-4, 6):
lr = LogisticReg... | code/ch04/ch04.ipynb | 1iyiwei/pyml | mit |
Dimensionality reduction
$L_1$ regularization implicitly selects features via zero out
Feature selection
* explicit - you specify how many features to select, the algorithm picks the most relevant (not important) ones
* forward, backward
* next topic
Note: 2 important features might be highly correlated, and thus it is... | from sklearn.base import clone
from itertools import combinations
import numpy as np
from sklearn.metrics import accuracy_score
if Version(sklearn_version) < '0.18':
from sklearn.cross_validation import train_test_split
else:
from sklearn.model_selection import train_test_split
class SBS():
def __init__(s... | code/ch04/ch04.ipynb | 1iyiwei/pyml | mit |
Below we try to apply the SBS class above.
We use the KNN classifer, which can suffer from curse of dimensionality. | import matplotlib.pyplot as plt
from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors=2)
# selecting features
sbs = SBS(knn, k_features=1)
sbs.fit(X_train_std, y_train)
# plotting performance of feature subsets
k_feat = [len(k) for k in sbs.subsets_]
plt.plot(k_feat, sbs.scores_,... | code/ch04/ch04.ipynb | 1iyiwei/pyml | mit |
Note the improved test accuracy by fitting lower dimensional training/test data.
Forward selection
This is essetially the reverse of backward selection; we will leave this as an exercise.
Assessing Feature Importances with Random Forests
Recall
* a decision tree is built by splitting nodes
* each node split is to maxim... | # feature_importances_ from random forest classifier records this info
from sklearn.ensemble import RandomForestClassifier
feat_labels = df_wine.columns[1:]
forest = RandomForestClassifier(n_estimators=10000,
random_state=0,
n_jobs=-1)
forest.fit(X_trai... | code/ch04/ch04.ipynb | 1iyiwei/pyml | mit |
Now, let's print the 3 features that met the threshold criterion for feature selection that we set earlier (note that this code snippet does not appear in the actual book but was added to this notebook later for illustrative purposes): | for f in range(X_selected.shape[1]):
print("%2d) %-*s %f" % (f + 1, 30,
feat_labels[indices[f]],
importances[indices[f]])) | code/ch04/ch04.ipynb | 1iyiwei/pyml | mit |
Testing
LRISb spectrum | test_arc_path = arclines.__path__[0]+'/data/sources/'
src_file = 'lrisb_600_4000_PYPIT.json'
with open(test_arc_path+src_file,'r') as f:
pypit_fit = json.load(f)
spec = pypit_fit['spec']
tbl = Table()
tbl['spec'] = spec
tbl.write(arclines.__path__[0]+'/tests/files/LRISb_600_spec.ascii',format='ascii') | docs/nb/Match_script.ipynb | PYPIT/arclines | bsd-3-clause |
Run
arclines_match LRISb_600_spec.ascii 4000. 1.26 CdI,HgI,ZnI
Kastr | test_arc_path = '/Users/xavier/local/Python/PYPIT-development-suite/REDUX_OUT/Kast_red/600_7500_d55/MF_kast_red/'
src_file = 'MasterWaveCalib_A_01_aa.json'
with open(test_arc_path+src_file,'r') as f:
pypit_fit = json.load(f)
spec = pypit_fit['spec']
tbl = Table()
tbl['spec'] = spec
tbl.write(arclines.__path__[0]+'... | docs/nb/Match_script.ipynb | PYPIT/arclines | bsd-3-clause |
Run
arclines_match Kastr_600_7500_spec.ascii 7500. 2.35 HgI,NeI,ArI
Check dispersion | pix = np.array(pypit_fit['xfit'])*(len(spec)-1.)
wave = np.array(pypit_fit['yfit'])
disp = (wave-np.roll(wave,1))/(pix-np.roll(pix,1))
disp | docs/nb/Match_script.ipynb | PYPIT/arclines | bsd-3-clause |
Ran without UNKNWN -- Excellent
LRISr -- 600/7500 | test_arc_path = arclines.__path__[0]+'/data/sources/'
src_file = 'lrisr_600_7500_PYPIT.json'
with open(test_arc_path+src_file,'r') as f:
pypit_fit = json.load(f)
spec = pypit_fit['spec']
tbl = Table()
tbl['spec'] = spec
tbl.write(arclines.__path__[0]+'/tests/files/LRISr_600_7500_spec.ascii',format='ascii') | docs/nb/Match_script.ipynb | PYPIT/arclines | bsd-3-clause |
Run
arclines_match LRISr_600_7500_spec.ascii 7000. 1.6 ArI,HgI,KrI,NeI,XeI
Need UNKNOWNS for better performance
arclines_match LRISr_600_7500_spec.ascii 7000. 1.6 ArI,HgI,KrI,NeI,XeI --unknowns
Am scanning now (successfully)
RCS at MMT | range(5,-1,-1) | docs/nb/Match_script.ipynb | PYPIT/arclines | bsd-3-clause |
Implement Preprocess Functions
Normalize
In the cell below, implement the normalize function to take in image data, x, and return it as a normalized Numpy array. The values should be in the range of 0 to 1, inclusive. The return object should be the same shape as x. | def normalize(x):
"""
Normalize a list of sample image data in the range of 0 to 1
: x: List of image data. The image shape is (32, 32, 3)
: return: Numpy array of normalize data
"""
# TODO: Implement Function
arrays = []
for x_ in x:
array = np.array(x_)
arrays.append(a... | image-classification/.ipynb_checkpoints/dlnd_image_classification-checkpoint.ipynb | luofan18/deep-learning | mit |
One-hot encode
Just like the previous code cell, you'll be implementing a function for preprocessing. This time, you'll implement the one_hot_encode function. The input, x, are a list of labels. Implement the function to return the list of labels as One-Hot encoded Numpy array. The possible values for labels are 0 t... | def one_hot_encode(x):
"""
One hot encode a list of sample labels. Return a one-hot encoded vector for each label.
: x: List of sample Labels
: return: Numpy array of one-hot encoded labels
"""
# TODO: Implement Function
# class_num = np.array(x).max()
class_num = 10
num = len(x)
... | image-classification/.ipynb_checkpoints/dlnd_image_classification-checkpoint.ipynb | luofan18/deep-learning | mit |
Build the network
For the neural network, you'll build each layer into a function. Most of the code you've seen has been outside of functions. To test your code more thoroughly, we require that you put each layer in a function. This allows us to give you better feedback and test for simple mistakes using our unittest... | import tensorflow as tf
def neural_net_image_input(image_shape):
"""
Return a Tensor for a batch of image input
: image_shape: Shape of the images
: return: Tensor for image input.
"""
# TODO: Implement Function
# print ('image_shape')
# print (image_shape)
shape = (None, )
shap... | image-classification/.ipynb_checkpoints/dlnd_image_classification-checkpoint.ipynb | luofan18/deep-learning | mit |
Convolution and Max Pooling Layer
Convolution layers have a lot of success with images. For this code cell, you should implement the function conv2d_maxpool to apply convolution then max pooling:
* Create the weight and bias using conv_ksize, conv_num_outputs and the shape of x_tensor.
* Apply a convolution to x_tensor... | def conv2d_maxpool(x_tensor, conv_num_outputs, conv_ksize, conv_strides, pool_ksize, pool_strides, maxpool=True):
"""
Apply convolution then max pooling to x_tensor
:param x_tensor: TensorFlow Tensor
:param conv_num_outputs: Number of outputs for the convolutional layer
:param conv_ksize: kernal siz... | image-classification/.ipynb_checkpoints/dlnd_image_classification-checkpoint.ipynb | luofan18/deep-learning | mit |
Flatten Layer
Implement the flatten function to change the dimension of x_tensor from a 4-D tensor to a 2-D tensor. The output should be the shape (Batch Size, Flattened Image Size). Shortcut option: you can use classes from the TensorFlow Layers or TensorFlow Layers (contrib) packages for this layer. For more of a ch... | def flatten(x_tensor):
"""
Flatten x_tensor to (Batch Size, Flattened Image Size)
: x_tensor: A tensor of size (Batch Size, ...), where ... are the image dimensions.
: return: A tensor of size (Batch Size, Flattened Image Size).
"""
# TODO: Implement Function
num, hight, width, channel = tup... | image-classification/.ipynb_checkpoints/dlnd_image_classification-checkpoint.ipynb | luofan18/deep-learning | mit |
Fully-Connected Layer
Implement the fully_conn function to apply a fully connected layer to x_tensor with the shape (Batch Size, num_outputs). Shortcut option: you can use classes from the TensorFlow Layers or TensorFlow Layers (contrib) packages for this layer. For more of a challenge, only use other TensorFlow packag... | def fully_conn(x_tensor, num_outputs):
"""
Apply a fully connected layer to x_tensor using weight and bias
: x_tensor: A 2-D tensor where the first dimension is batch size.
: num_outputs: The number of output that the new tensor should be.
: return: A 2-D tensor where the second dimension is num_out... | image-classification/.ipynb_checkpoints/dlnd_image_classification-checkpoint.ipynb | luofan18/deep-learning | mit |
Output Layer
Implement the output function to apply a fully connected layer to x_tensor with the shape (Batch Size, num_outputs). Shortcut option: you can use classes from the TensorFlow Layers or TensorFlow Layers (contrib) packages for this layer. For more of a challenge, only use other TensorFlow packages.
Note: Act... | def output(x_tensor, num_outputs):
"""
Apply a output layer to x_tensor using weight and bias
: x_tensor: A 2-D tensor where the first dimension is batch size.
: num_outputs: The number of output that the new tensor should be.
: return: A 2-D tensor where the second dimension is num_outputs.
"""... | image-classification/.ipynb_checkpoints/dlnd_image_classification-checkpoint.ipynb | luofan18/deep-learning | mit |
Create Convolutional Model
Implement the function conv_net to create a convolutional neural network model. The function takes in a batch of images, x, and outputs logits. Use the layers you created above to create this model:
Apply 1, 2, or 3 Convolution and Max Pool layers
Apply a Flatten Layer
Apply 1, 2, or 3 Full... | def conv_net(x, keep_prob):
"""
Create a convolutional neural network model
: x: Placeholder tensor that holds image data.
: keep_prob: Placeholder tensor that hold dropout keep probability.
: return: Tensor that represents logits
"""
# TODO: Apply 1, 2, or 3 Convolution and Max Pool layers
... | image-classification/.ipynb_checkpoints/dlnd_image_classification-checkpoint.ipynb | luofan18/deep-learning | mit |
Train the Neural Network
Single Optimization
Implement the function train_neural_network to do a single optimization. The optimization should use optimizer to optimize in session with a feed_dict of the following:
* x for image input
* y for labels
* keep_prob for keep probability for dropout
This function will be cal... | def train_neural_network(session, optimizer, keep_probability, feature_batch, label_batch):
"""
Optimize the session on a batch of images and labels
: session: Current TensorFlow session
: optimizer: TensorFlow optimizer function
: keep_probability: keep probability
: feature_batch: Batch of Num... | image-classification/.ipynb_checkpoints/dlnd_image_classification-checkpoint.ipynb | luofan18/deep-learning | mit |
Show Stats
Implement the function print_stats to print loss and validation accuracy. Use the global variables valid_features and valid_labels to calculate validation accuracy. Use a keep probability of 1.0 to calculate the loss and validation accuracy. | def print_stats(session, feature_batch, label_batch, cost, accuracy):
"""
Print information about loss and validation accuracy
: session: Current TensorFlow session
: feature_batch: Batch of Numpy image data
: label_batch: Batch of Numpy label data
: cost: TensorFlow cost function
: accuracy... | image-classification/.ipynb_checkpoints/dlnd_image_classification-checkpoint.ipynb | luofan18/deep-learning | mit |
Hyperparameters
Tune the following parameters:
* Set epochs to the number of iterations until the network stops learning or start overfitting
* Set batch_size to the highest number that your machine has memory for. Most people set them to common sizes of memory:
* 64
* 128
* 256
* ...
* Set keep_probability to the... | # TODO: Tune Parameters
epochs = 10
batch_size = 128
keep_probability = 0.8 | image-classification/.ipynb_checkpoints/dlnd_image_classification-checkpoint.ipynb | luofan18/deep-learning | mit |
Generations | def print_sample(sample, best_bleu=None):
enc_input = ' '.join([w for w in sample['encoder_input'].split(' ') if w != '<pad>'])
gold = ' '.join([w for w in sample['gold'].split(' ') if w != '<mask>'])
print('Input: '+ enc_input + '\n')
print('Gend: ' + sample['generated'] + '\n')
print('True: ' + go... | report_notebooks/encdec_noing10_200_512_04drb.ipynb | kingb12/languagemodelRNN | mit |
BLEU Analysis | def print_bleu(blue_struct):
print 'Overall Score: ', blue_struct['score'], '\n'
print '1-gram Score: ', blue_struct['components']['1']
print '2-gram Score: ', blue_struct['components']['2']
print '3-gram Score: ', blue_struct['components']['3']
print '4-gram Score: ', blue_struct['components']['4']... | report_notebooks/encdec_noing10_200_512_04drb.ipynb | kingb12/languagemodelRNN | mit |
N-pairs BLEU Analysis
This analysis randomly samples 1000 pairs of generations/ground truths and treats them as translations, giving their BLEU score. We can expect very low scores in the ground truth and high scores can expose hyper-common generations | # Training Set BLEU n-pairs Scores
print_bleu(report['n_pairs_bleu_train'])
# Validation Set n-pairs BLEU Scores
print_bleu(report['n_pairs_bleu_valid'])
# Test Set n-pairs BLEU Scores
print_bleu(report['n_pairs_bleu_test'])
# Combined n-pairs BLEU Scores
print_bleu(report['n_pairs_bleu_all'])
# Ground Truth n-pair... | report_notebooks/encdec_noing10_200_512_04drb.ipynb | kingb12/languagemodelRNN | mit |
Alignment Analysis
This analysis computs the average Smith-Waterman alignment score for generations, with the same intuition as N-pairs BLEU, in that we expect low scores in the ground truth and hyper-common generations to raise the scores | print 'Average (Train) Generated Score: ', report['average_alignment_train']
print 'Average (Valid) Generated Score: ', report['average_alignment_valid']
print 'Average (Test) Generated Score: ', report['average_alignment_test']
print 'Average (All) Generated Score: ', report['average_alignment_all']
print 'Average Gol... | report_notebooks/encdec_noing10_200_512_04drb.ipynb | kingb12/languagemodelRNN | mit |
Then, we decide on how many believers of each cultural option (religion) we want to start with. | A = 65 # initial number of believers A
B = N - A # initial number of believers A | doc/DH2016tutorial.ipynb | xrubio/simulationdh | gpl-3.0 |
Finally, we want to update these quantities at every time step depending on some variation: | t = 0
MAX_TIME = 100
while t < MAX_TIME:
A = A + variation
B = B - variation
# advance time to next iteration
t = t + 1 | doc/DH2016tutorial.ipynb | xrubio/simulationdh | gpl-3.0 |
Type the code in the code tab. Keep in mind that indents are important.
Run the code by hitting F5 (or click on a green triangle). What happens?
Well, nothing happens or, rather, we get an error.
python
NameError: name variation is not defined
Indeed, we have not defined what do we mean by 'variation'. So let's calc... | def payoff(believers, Tx,Ty):
proportionBelievers = believers/N
attraction = Tx/(Ty + Tx)
return proportionBelievers * attraction | doc/DH2016tutorial.ipynb | xrubio/simulationdh | gpl-3.0 |
Let's break it down a little. First we define the function and give it the input - the number of believers and the two values that define how attractive each cultural option is.
python
def payoff(believers, Tx, Ty):
Then we calculate two values:
percentage of population sharing this cultural option
python
proport... | while t < MAX_TIME:
variationBA = payoff(A, Ta, Tb)
variationAB = payoff(B, Tb, Ta)
A = A + variation
B = B - variation
# advance time to next iteration
t = t + 1 | doc/DH2016tutorial.ipynb | xrubio/simulationdh | gpl-3.0 |
That is, we pass the number of believers and the attractiveness of the traits. The order in which we pass the input variables into a function is important. In the B to A transmission, B becomes 'believers', while Ta becomes 'Tx' and Tb becomes 'Ty'. In the second line showing the A to B transmission, A becomes '_believ... | Ta = 1.0 # initial attractiveness of option A
Tb = 2.0 # initial attractiveness of option B
alpha = 0.1 # strength of the transmission process | doc/DH2016tutorial.ipynb | xrubio/simulationdh | gpl-3.0 |
We can now calculate the difference between the perceived payoffs during this time step. To do so, we need to first see which one did better (A or B). | difference = variationBA - variationAB | doc/DH2016tutorial.ipynb | xrubio/simulationdh | gpl-3.0 |
Now, if the difference between the two is negative then we know that during time step B is more interesting than A. On the contrary, if it is positive then A seems better than B. What is left is to see how many people moved based on this difference between payoffs. We can express it in the main while loop, like this: | # B -> A
if difference > 0:
variation = difference*B
# A -> B
else:
variation = difference*A
# update the population
A = A + variation
B = B - variation | doc/DH2016tutorial.ipynb | xrubio/simulationdh | gpl-3.0 |
We can use an additional term to have a control over how strong the transmission from A to B and back is - we will call it alpha (α). This parameter will multiply change before we modify populations A and B: | variation = alpha*variation | doc/DH2016tutorial.ipynb | xrubio/simulationdh | gpl-3.0 |
And we need to add it to the rest of the parameters of our model: | # temporal dimension
MAX_TIME = 100
t = 0 # initial time
# init populations
N = 100 # population size
A = 65 # initial population of believers A
B = N-A # initial population of believers B
# additional params
Ta = 1.0 # initial attractiveness of option A
Tb = 2.... | doc/DH2016tutorial.ipynb | xrubio/simulationdh | gpl-3.0 |
You should bear in mind that the main loop code should be located after the definition of the transmission function and the initialization of variables (because they are used here). After all the edits you have done it should look like this: | while t < MAX_TIME:
# calculate the payoff for change of believers A and B in the current time step
variationBA = payoff(A, Ta, Tb)
variationAB = payoff(B, Tb, Ta)
difference = variationBA - variationAB
# B -> A
if difference > 0:
variation = difference... | doc/DH2016tutorial.ipynb | xrubio/simulationdh | gpl-3.0 |
OK, we have all the elements ready now and if you run the code the computer will churn all the numbers somewhere in the background. However, it produces no output so we have no idea what is actually happening. Let's solve this by visualising the flow of believers from one option to another.
First, we will create two e... | # initialise the list used for plotting
believersA = []
believersB = []
# add the initial populations
believersA.append(A)
believersB.append(B) | doc/DH2016tutorial.ipynb | xrubio/simulationdh | gpl-3.0 |
The whole initialisation/definition block at the beginning of your code should look like this: | # initialisation
MAX_TIME = 100
t = 0 # initial time
N = 100 # population size
A = 65 # initial proportion of believers A
B = N-A # initial proportion of believers B
Ta = 1.0 # initial attractiveness of option A
Tb = 2.0 # initial attractiveness o... | doc/DH2016tutorial.ipynb | xrubio/simulationdh | gpl-3.0 |
We just added the initial number of believers to their respective lists. However, we also need to do this at the end of each time step. Add the following code at the end of the while loop - remember to align the indents with the previous line! | believersA.append(A)
believersB.append(B) | doc/DH2016tutorial.ipynb | xrubio/simulationdh | gpl-3.0 |
The whole while-loop block should now look like this: | while t < MAX_TIME:
# calculate the payoff for change of believers A and B in the current time step
variationBA = payoff(A, Ta, Tb)
variationAB = payoff(B, Tb, Ta)
difference = variationBA - variationAB
# B -> A
if difference > 0:
variation = difference*B
... | doc/DH2016tutorial.ipynb | xrubio/simulationdh | gpl-3.0 |
Finally, let's plot the results. First, we will import Python's plotting library, Matplotlib and use a predifined plotting style. Add these two lines at the beginning of your script: | import matplotlib.pyplot as plt # plotting library
plt.style.use('ggplot') # makes the graphs look pretty | doc/DH2016tutorial.ipynb | xrubio/simulationdh | gpl-3.0 |
Finally, let's plot! Plotting in Python is as easy as saying 'please plot this data for me'. Type these two lines at the very end of your code. We only want to plot the results once the simulation has finished so make sure this are not inside the while loop - that is, ensure this block of code is not indented. Run the ... | %matplotlib inline
# plot the results
plt.plot(believersA)
plt.plot(believersB) | doc/DH2016tutorial.ipynb | xrubio/simulationdh | gpl-3.0 |
You can see how over time one set of believers increases while the other decreases. This is not particularly surprising as the attractiveness Tb is higher than Ta. However, can you imagine a configuration where this is not enough to sway the population? Have a go at setting the variables to different initial values to ... | Ta, Tb = attractiveness(Ta, Tb) | doc/DH2016tutorial.ipynb | xrubio/simulationdh | gpl-3.0 |
Ta and Tb will then be modified based on some dynamics we want to model. Let's define the 'attractiveness' function. We have already done it once for the 'payoff' function so it should be a piece of cake. At each time step we will slightly modify the attractiveness of each trait using a kernel K that we will define. Th... | def attractiveness(Ta, Tb):
Ka = 0.1
Kb = 0
Ta = Ta + Ka
Tb = Tb + Kb
return Ta, Tb | doc/DH2016tutorial.ipynb | xrubio/simulationdh | gpl-3.0 |
First, we define the function and give it the input values.
python
def attractiveness(Ta, Tb):
Then, we establish how much the attractiveness of each trait changes (i.e., define $K_a$ and $K_b$)
python
Ka = 0.1
Kb = 0
And plug them into the equations:
python
Ta = Ta + Ka
Tb = Tb + Kb
Finally, we return the ... | while t < MAX_TIME:
# update attractiveness
Ta, Tb = attractiveness(Ta, Tb)
# calculate the payoff for change of believers A and B in the current time step
variationBA = payoff(A, Ta, Tb)
variationAB = payoff(B, Tb, Ta)
difference = variationBA - variationAB
#... | doc/DH2016tutorial.ipynb | xrubio/simulationdh | gpl-3.0 |
If you plot this you will get a different result than previously: | plt.plot(believersA)
plt.plot(believersB) | doc/DH2016tutorial.ipynb | xrubio/simulationdh | gpl-3.0 |
Have a go at changing the values of $K_a$ and $K_b$ and see what happens. Can you see any equilibrium where both traits coexist?
There are a number of functions we can use to dynamically change the 'attractiveness' of each trait. Try the following ones: | import numpy as np # stick this line at the beginning of the script alongside other 'imports'
def attractiveness2(Ta, Tb):
# temporal autocorrelation with stochasticity (normal distribution)
# we get 2 samples from a normal distribution N(0,1)
Ka, Kb = np.random.normal(0, 1, 2)
# compute the differenc... | doc/DH2016tutorial.ipynb | xrubio/simulationdh | gpl-3.0 |
Interact with SVG display
SVG is a simple way of drawing vector graphics in the browser. Here is a simple example of how SVG can be used to draw a circle in the Notebook: | s = """
<svg width="100" height="100">
<circle cx="50" cy="50" r="20" fill="aquamarine" />
</svg>
"""
SVG(s) | assignments/assignment06/InteractEx05.ipynb | LimeeZ/phys292-2015-work | mit |
Write a function named draw_circle that draws a circle using SVG. Your function should take the parameters of the circle as function arguments and have defaults as shown. You will have to write the raw SVG code as a Python string and then use the IPython.display.SVG object and IPython.display.display function. | def draw_circle(width=100, height=100, cx=25, cy=25, r=5, fill='red'):
"""Draw an SVG circle.
Parameters
----------
width : int
The width of the svg drawing area in px.
height : int
The height of the svg drawing area in px.
cx : int
The x position of the center of th... | assignments/assignment06/InteractEx05.ipynb | LimeeZ/phys292-2015-work | mit |
Use interactive to build a user interface for exploing the draw_circle function:
width: a fixed value of 300px
height: a fixed value of 300px
cx/cy: a slider in the range [0,300]
r: a slider in the range [0,50]
fill: a text area in which you can type a color's name
Save the return value of interactive to a variable n... | #?interactive
w = interactive(draw_circle, width = fixed(300), height = fixed(300), cx=[0,300], cy=[0,300], r=[0,50], fill = '')
w
c = w.children
assert c[0].min==0 and c[0].max==300
assert c[1].min==0 and c[1].max==300
assert c[2].min==0 and c[2].max==50
assert c[3].value=='red' | assignments/assignment06/InteractEx05.ipynb | LimeeZ/phys292-2015-work | mit |
Use the display function to show the widgets created by interactive: | display(w)
assert True # leave this to grade the display of the widget | assignments/assignment06/InteractEx05.ipynb | LimeeZ/phys292-2015-work | mit |
Vertex AI AutoML tables regression
Installation
Install the latest (preview) version of Vertex SDK. | ! pip3 install -U google-cloud-aiplatform --user | notebooks/community/migration/UJ4 AutoML for structured data with Vertex AI Regression.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Restart the Kernel
Once you've installed the Vertex SDK and Google cloud-storage, you need to restart the notebook kernel so it can find the packages. | import os
if not os.getenv("AUTORUN") and False:
# Automatically restart kernel after installs
import IPython
app = IPython.Application.instance()
app.kernel.do_shutdown(True) | notebooks/community/migration/UJ4 AutoML for structured data with Vertex AI Regression.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
AutoML constants
Next, setup constants unique to AutoML Table classification datasets and training:
Dataset Schemas: Tells the managed dataset service which type of dataset it is.
Data Labeling (Annotations) Schemas: Tells the managed dataset service how the data is labeled (annotated).
Dataset Training Schemas: Tells... | # Tabular Dataset type
TABLE_SCHEMA = "google-cloud-aiplatform/schema/dataset/metadata/tables_1.0.0.yaml"
# Tabular Labeling type
IMPORT_SCHEMA_TABLE_CLASSIFICATION = (
"gs://google-cloud-aiplatform/schema/dataset/ioformat/table_io_format_1.0.0.yaml"
)
# Tabular Training task
TRAINING_TABLE_CLASSIFICATION_SCHEMA = ... | notebooks/community/migration/UJ4 AutoML for structured data with Vertex AI Regression.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Clients
The Vertex SDK works as a client/server model. On your side (the Python script) you will create a client that sends requests and receives responses from the server (Vertex).
You will use several clients in this tutorial, so set them all up upfront.
Dataset Service for managed datasets.
Model Service for manage... | # client options same for all services
client_options = {"api_endpoint": API_ENDPOINT}
def create_dataset_client():
client = aip.DatasetServiceClient(client_options=client_options)
return client
def create_model_client():
client = aip.ModelServiceClient(client_options=client_options)
return client
... | notebooks/community/migration/UJ4 AutoML for structured data with Vertex AI Regression.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Example output:
Age,Job,MaritalStatus,Education,Default,Balance,Housing,Loan,Contact,Day,Month,Duration,Campaign,PDays,Previous,POutcome,Deposit
58,management,married,tertiary,no,2143,yes,no,unknown,5,may,261,1,-1,0,unknown,1
44,technician,single,secondary,no,29,yes,no,unknown,5,may,151,1,-1,0,unknown,1
33,entrepreneur... | DATA_SCHEMA = TABLE_SCHEMA
metadata = {
"input_config": {
"gcs_source": {
"uri": [IMPORT_FILE],
}
}
}
dataset = {
"display_name": "bank_" + TIMESTAMP,
"metadata_schema_uri": "gs://" + DATA_SCHEMA,
"metadata": json_format.ParseDict(metadata, Value()),
}
print(
Messa... | notebooks/community/migration/UJ4 AutoML for structured data with Vertex AI Regression.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Example output:
{
"parent": "projects/migration-ucaip-training/locations/us-central1",
"dataset": {
"displayName": "bank_20210226015209",
"metadataSchemaUri": "gs://google-cloud-aiplatform/schema/dataset/metadata/tables_1.0.0.yaml",
"metadata": {
"input_config": {
"gcs_source": {
... | request = clients["dataset"].create_dataset(parent=PARENT, dataset=dataset) | notebooks/community/migration/UJ4 AutoML for structured data with Vertex AI Regression.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Example output:
{
"name": "projects/116273516712/locations/us-central1/datasets/7748812594797871104",
"displayName": "bank_20210226015209",
"metadataSchemaUri": "gs://google-cloud-aiplatform/schema/dataset/metadata/tabular_1.0.0.yaml",
"labels": {
"aiplatform.googleapis.com/dataset_metadata_schema": "TABLE"... | # The full unique ID for the dataset
dataset_id = result.name
# The short numeric ID for the dataset
dataset_short_id = dataset_id.split("/")[-1]
print(dataset_id) | notebooks/community/migration/UJ4 AutoML for structured data with Vertex AI Regression.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Train a model
projects.locations.trainingPipelines.create
Request | TRAINING_SCHEMA = TRAINING_TABLE_CLASSIFICATION_SCHEMA
TRANSFORMATIONS = [
{"auto": {"column_name": "Age"}},
{"auto": {"column_name": "Job"}},
{"auto": {"column_name": "MaritalStatus"}},
{"auto": {"column_name": "Education"}},
{"auto": {"column_name": "Default"}},
{"auto": {"column_name": "Bala... | notebooks/community/migration/UJ4 AutoML for structured data with Vertex AI Regression.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Example output:
{
"parent": "projects/migration-ucaip-training/locations/us-central1",
"trainingPipeline": {
"displayName": "bank_20210226015209",
"inputDataConfig": {
"datasetId": "7748812594797871104",
"fractionSplit": {
"trainingFraction": 0.8,
"validationFraction": 0.1,
... | request = clients["pipeline"].create_training_pipeline(
parent=PARENT, training_pipeline=training_pipeline
) | notebooks/community/migration/UJ4 AutoML for structured data with Vertex AI Regression.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Example output:
{
"name": "projects/116273516712/locations/us-central1/trainingPipelines/3147717072369221632",
"displayName": "bank_20210226015209",
"inputDataConfig": {
"datasetId": "7748812594797871104",
"fractionSplit": {
"trainingFraction": 0.8,
"validationFraction": 0.1,
"testFracti... | # The full unique ID for the training pipeline
training_pipeline_id = request.name
# The short numeric ID for the training pipeline
training_pipeline_short_id = training_pipeline_id.split("/")[-1]
print(training_pipeline_id) | notebooks/community/migration/UJ4 AutoML for structured data with Vertex AI Regression.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
projects.locations.trainingPipelines.get
Call | request = clients["pipeline"].get_training_pipeline(name=training_pipeline_id) | notebooks/community/migration/UJ4 AutoML for structured data with Vertex AI Regression.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Example output:
{
"name": "projects/116273516712/locations/us-central1/trainingPipelines/3147717072369221632",
"displayName": "bank_20210226015209",
"inputDataConfig": {
"datasetId": "7748812594797871104",
"fractionSplit": {
"trainingFraction": 0.8,
"validationFraction": 0.1,
"testFracti... | while True:
response = clients["pipeline"].get_training_pipeline(name=training_pipeline_id)
if response.state != aip.PipelineState.PIPELINE_STATE_SUCCEEDED:
print("Training job has not completed:", response.state)
model_to_deploy_name = None
if response.state == aip.PipelineState.PIPELIN... | notebooks/community/migration/UJ4 AutoML for structured data with Vertex AI Regression.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Evaluate the model
projects.locations.models.evaluations.list
Call | request = clients["model"].list_model_evaluations(parent=model_id) | notebooks/community/migration/UJ4 AutoML for structured data with Vertex AI Regression.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Response | import json
model_evaluations = [json.loads(MessageToJson(me.__dict__["_pb"])) for me in request]
# The evaluation slice
evaluation_slice = request.model_evaluations[0].name
print(json.dumps(model_evaluations, indent=2)) | notebooks/community/migration/UJ4 AutoML for structured data with Vertex AI Regression.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Example output:
[
{
"name": "projects/116273516712/locations/us-central1/models/3936304403996213248/evaluations/6323797633322037836",
"metricsSchemaUri": "gs://google-cloud-aiplatform/schema/modelevaluation/regression_metrics_1.0.0.yaml",
"metrics": {
"rSquared": 0.39799774,
"meanAbsolutePerce... | request = clients["model"].get_model_evaluation(name=evaluation_slice) | notebooks/community/migration/UJ4 AutoML for structured data with Vertex AI Regression.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Example output:
{
"name": "projects/116273516712/locations/us-central1/models/3936304403996213248/evaluations/6323797633322037836",
"metricsSchemaUri": "gs://google-cloud-aiplatform/schema/modelevaluation/regression_metrics_1.0.0.yaml",
"metrics": {
"meanAbsolutePercentageError": 9.791032,
"rootMeanSquare... | ! gsutil cat $IMPORT_FILE | head -n 1 > tmp.csv
! gsutil cat $IMPORT_FILE | tail -n 10 >> tmp.csv
! cut -d, -f1-16 tmp.csv > batch.csv
gcs_input_uri = "gs://" + BUCKET_NAME + "/test.csv"
! gsutil cp batch.csv $gcs_input_uri
! gsutil cat $gcs_input_uri | notebooks/community/migration/UJ4 AutoML for structured data with Vertex AI Regression.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Example output:
Age,Job,MaritalStatus,Education,Default,Balance,Housing,Loan,Contact,Day,Month,Duration,Campaign,PDays,Previous,POutcome
53,management,married,tertiary,no,583,no,no,cellular,17,nov,226,1,184,4,success
34,admin.,single,secondary,no,557,no,no,cellular,17,nov,224,1,-1,0,unknown
23,student,single,tertiary,n... | batch_prediction_job = {
"display_name": "bank_" + TIMESTAMP,
"model": model_id,
"input_config": {
"instances_format": "csv",
"gcs_source": {
"uris": [gcs_input_uri],
},
},
"output_config": {
"predictions_format": "csv",
"gcs_destination": {
... | notebooks/community/migration/UJ4 AutoML for structured data with Vertex AI Regression.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Example output:
{
"parent": "projects/migration-ucaip-training/locations/us-central1",
"batchPredictionJob": {
"displayName": "bank_20210226015209",
"model": "projects/116273516712/locations/us-central1/models/3936304403996213248",
"inputConfig": {
"instancesFormat": "csv",
"gcsSource": {
... | request = clients["job"].create_batch_prediction_job(
parent=PARENT, batch_prediction_job=batch_prediction_job
) | notebooks/community/migration/UJ4 AutoML for structured data with Vertex AI Regression.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Example output:
{
"name": "projects/116273516712/locations/us-central1/batchPredictionJobs/4417450692310990848",
"displayName": "bank_20210226015209",
"model": "projects/116273516712/locations/us-central1/models/3936304403996213248",
"inputConfig": {
"instancesFormat": "csv",
"gcsSource": {
"uris"... | # The fully qualified ID for the batch job
batch_job_id = request.name
# The short numeric ID for the batch job
batch_job_short_id = batch_job_id.split("/")[-1]
print(batch_job_id) | notebooks/community/migration/UJ4 AutoML for structured data with Vertex AI Regression.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Example output:
{
"name": "projects/116273516712/locations/us-central1/batchPredictionJobs/4417450692310990848",
"displayName": "bank_20210226015209",
"model": "projects/116273516712/locations/us-central1/models/3936304403996213248",
"inputConfig": {
"instancesFormat": "csv",
"gcsSource": {
"uris"... | def get_latest_predictions(gcs_out_dir):
""" Get the latest prediction subfolder using the timestamp in the subfolder name"""
folders = !gsutil ls $gcs_out_dir
latest = ""
for folder in folders:
subfolder = folder.split("/")[-2]
if subfolder.startswith("prediction-"):
if subf... | notebooks/community/migration/UJ4 AutoML for structured data with Vertex AI Regression.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Example output:
gs://migration-ucaip-trainingaip-20210226015209/batch_output/prediction-flowers_20210226015209-2021-02-26T09:35:43.034287Z/predictions_1.csv
Age,Balance,Campaign,Contact,Day,Default,Duration,Education,Housing,Job,Loan,MaritalStatus,Month,PDays,POutcome,Previous,predicted_Deposit
72,5715,5,cellular,17,no... | endpoint = {"display_name": "bank_" + TIMESTAMP}
print(
MessageToJson(
aip.CreateEndpointRequest(
parent=PARENT,
endpoint=endpoint,
).__dict__["_pb"]
)
) | notebooks/community/migration/UJ4 AutoML for structured data with Vertex AI Regression.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Example output:
{
"parent": "projects/migration-ucaip-training/locations/us-central1",
"endpoint": {
"displayName": "bank_20210226015209"
}
}
Call | request = clients["endpoint"].create_endpoint(parent=PARENT, endpoint=endpoint) | notebooks/community/migration/UJ4 AutoML for structured data with Vertex AI Regression.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Example output:
{
"name": "projects/116273516712/locations/us-central1/endpoints/6899338707271155712"
} | # The fully qualified ID for the endpoint
endpoint_id = result.name
# The short numeric ID for the endpoint
endpoint_short_id = endpoint_id.split("/")[-1]
print(endpoint_id) | notebooks/community/migration/UJ4 AutoML for structured data with Vertex AI Regression.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
projects.locations.endpoints.deployModel
Request | deployed_model = {
"model": model_id,
"display_name": "bank_" + TIMESTAMP,
"dedicated_resources": {
"min_replica_count": 1,
"machine_spec": {"machine_type": "n1-standard-2"},
},
}
traffic_split = {"0": 100}
print(
MessageToJson(
aip.DeployModelRequest(
endpoint=... | notebooks/community/migration/UJ4 AutoML for structured data with Vertex AI Regression.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Example output:
{
"endpoint": "projects/116273516712/locations/us-central1/endpoints/6899338707271155712",
"deployedModel": {
"model": "projects/116273516712/locations/us-central1/models/3936304403996213248",
"displayName": "bank_20210226015209",
"dedicatedResources": {
"machineSpec": {
"m... | request = clients["endpoint"].deploy_model(
endpoint=endpoint_id, deployed_model=deployed_model, traffic_split=traffic_split
) | notebooks/community/migration/UJ4 AutoML for structured data with Vertex AI Regression.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Example output:
{
"deployedModel": {
"id": "7646795507926302720"
}
} | # The numeric ID for the deploy model
deploy_model_id = result.deployed_model.id
print(deploy_model_id) | notebooks/community/migration/UJ4 AutoML for structured data with Vertex AI Regression.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
projects.locations.endpoints.predict
Prepare data item for online prediction | INSTANCE = {
"Age": "58",
"Job": "managment",
"MaritalStatus": "married",
"Education": "teritary",
"Default": "no",
"Balance": "2143",
"Housing": "yes",
"Loan": "no",
"Contact": "unknown",
"Day": "5",
"Month": "may",
"Duration": "261",
"Campaign": "1",
"PDays": "-... | notebooks/community/migration/UJ4 AutoML for structured data with Vertex AI Regression.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Request | instances_list = [INSTANCE]
instances = [json_format.ParseDict(s, Value()) for s in instances_list]
request = aip.PredictRequest(
endpoint=endpoint_id,
)
request.instances.append(instances)
print(MessageToJson(request.__dict__["_pb"])) | notebooks/community/migration/UJ4 AutoML for structured data with Vertex AI Regression.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Example output:
{
"endpoint": "projects/116273516712/locations/us-central1/endpoints/6899338707271155712",
"instances": [
[
{
"Education": "teritary",
"MaritalStatus": "married",
"Balance": "2143",
"Contact": "unknown",
"Housing": "yes",
"Previous": 0.0,
... | request = clients["prediction"].predict(endpoint=endpoint_id, instances=instances) | notebooks/community/migration/UJ4 AutoML for structured data with Vertex AI Regression.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Example output:
{
"predictions": [
{
"upper_bound": 1.685426712036133,
"value": 1.007092595100403,
"lower_bound": 0.06719603389501572
}
],
"deployedModelId": "7646795507926302720"
}
projects.locations.endpoints.undeployModel
Call | request = clients["endpoint"].undeploy_model(
endpoint=endpoint_id, deployed_model_id=deploy_model_id, traffic_split={}
) | notebooks/community/migration/UJ4 AutoML for structured data with Vertex AI Regression.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Example output:
{}
Cleaning up
To clean up all GCP resources used in this project, you can delete the GCP
project you used for the tutorial.
Otherwise, you can delete the individual resources you created in this tutorial. | delete_dataset = True
delete_model = True
delete_endpoint = True
delete_pipeline = True
delete_batchjob = True
delete_bucket = True
# Delete the dataset using the Vertex AI fully qualified identifier for the dataset
try:
if delete_dataset:
clients["dataset"].delete_dataset(name=dataset_id)
except Exception... | notebooks/community/migration/UJ4 AutoML for structured data with Vertex AI Regression.ipynb | GoogleCloudPlatform/vertex-ai-samples | apache-2.0 |
Customize what happens in Model.fit
<table class="tfo-notebook-buttons" align="left">
<td>
<a target="_blank" href="https://www.tensorflow.org/guide/keras/customizing_what_happens_in_fit"><img src="https://www.tensorflow.org/images/tf_logo_32px.png" />View on TensorFlow.org</a>
</td>
<td>
<a target="_blan... | import tensorflow as tf
from tensorflow import keras | site/en-snapshot/guide/keras/customizing_what_happens_in_fit.ipynb | tensorflow/docs-l10n | apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.