markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
Install TFX
!pip install -U tfx
site/en-snapshot/tfx/tutorials/tfx/penguin_simple.ipynb
tensorflow/docs-l10n
apache-2.0
Did you restart the runtime? If you are using Google Colab, the first time that you run the cell above, you must restart the runtime by clicking above "RESTART RUNTIME" button or using "Runtime > Restart runtime ..." menu. This is because of the way that Colab loads packages. Check the TensorFlow and TFX versions.
import tensorflow as tf print('TensorFlow version: {}'.format(tf.__version__)) from tfx import v1 as tfx print('TFX version: {}'.format(tfx.__version__))
site/en-snapshot/tfx/tutorials/tfx/penguin_simple.ipynb
tensorflow/docs-l10n
apache-2.0
Set up variables There are some variables used to define a pipeline. You can customize these variables as you want. By default all output from the pipeline will be generated under the current directory.
import os PIPELINE_NAME = "penguin-simple" # Output directory to store artifacts generated from the pipeline. PIPELINE_ROOT = os.path.join('pipelines', PIPELINE_NAME) # Path to a SQLite DB file to use as an MLMD storage. METADATA_PATH = os.path.join('metadata', PIPELINE_NAME, 'metadata.db') # Output directory where created models from the pipeline will be exported. SERVING_MODEL_DIR = os.path.join('serving_model', PIPELINE_NAME) from absl import logging logging.set_verbosity(logging.INFO) # Set default logging level.
site/en-snapshot/tfx/tutorials/tfx/penguin_simple.ipynb
tensorflow/docs-l10n
apache-2.0
Prepare example data We will download the example dataset for use in our TFX pipeline. The dataset we are using is Palmer Penguins dataset which is also used in other TFX examples. There are four numeric features in this dataset: culmen_length_mm culmen_depth_mm flipper_length_mm body_mass_g All features were already normalized to have range [0,1]. We will build a classification model which predicts the species of penguins. Because TFX ExampleGen reads inputs from a directory, we need to create a directory and copy dataset to it.
import urllib.request import tempfile DATA_ROOT = tempfile.mkdtemp(prefix='tfx-data') # Create a temporary directory. _data_url = 'https://raw.githubusercontent.com/tensorflow/tfx/master/tfx/examples/penguin/data/labelled/penguins_processed.csv' _data_filepath = os.path.join(DATA_ROOT, "data.csv") urllib.request.urlretrieve(_data_url, _data_filepath)
site/en-snapshot/tfx/tutorials/tfx/penguin_simple.ipynb
tensorflow/docs-l10n
apache-2.0
Take a quick look at the CSV file.
!head {_data_filepath}
site/en-snapshot/tfx/tutorials/tfx/penguin_simple.ipynb
tensorflow/docs-l10n
apache-2.0
You should be able to see five values. species is one of 0, 1 or 2, and all other features should have values between 0 and 1. Create a pipeline TFX pipelines are defined using Python APIs. We will define a pipeline which consists of following three components. - CsvExampleGen: Reads in data files and convert them to TFX internal format for further processing. There are multiple ExampleGens for various formats. In this tutorial, we will use CsvExampleGen which takes CSV file input. - Trainer: Trains an ML model. Trainer component requires a model definition code from users. You can use TensorFlow APIs to specify how to train a model and save it in a saved_model format. - Pusher: Copies the trained model outside of the TFX pipeline. Pusher component can be thought of as a deployment process of the trained ML model. Before actually define the pipeline, we need to write a model code for the Trainer component first. Write model training code We will create a simple DNN model for classification using TensorFlow Keras API. This model training code will be saved to a separate file. In this tutorial we will use Generic Trainer of TFX which support Keras-based models. You need to write a Python file containing run_fn function, which is the entrypoint for the Trainer component.
_trainer_module_file = 'penguin_trainer.py' %%writefile {_trainer_module_file} from typing import List from absl import logging import tensorflow as tf from tensorflow import keras from tensorflow_transform.tf_metadata import schema_utils from tfx import v1 as tfx from tfx_bsl.public import tfxio from tensorflow_metadata.proto.v0 import schema_pb2 _FEATURE_KEYS = [ 'culmen_length_mm', 'culmen_depth_mm', 'flipper_length_mm', 'body_mass_g' ] _LABEL_KEY = 'species' _TRAIN_BATCH_SIZE = 20 _EVAL_BATCH_SIZE = 10 # Since we're not generating or creating a schema, we will instead create # a feature spec. Since there are a fairly small number of features this is # manageable for this dataset. _FEATURE_SPEC = { **{ feature: tf.io.FixedLenFeature(shape=[1], dtype=tf.float32) for feature in _FEATURE_KEYS }, _LABEL_KEY: tf.io.FixedLenFeature(shape=[1], dtype=tf.int64) } def _input_fn(file_pattern: List[str], data_accessor: tfx.components.DataAccessor, schema: schema_pb2.Schema, batch_size: int = 200) -> tf.data.Dataset: """Generates features and label for training. Args: file_pattern: List of paths or patterns of input tfrecord files. data_accessor: DataAccessor for converting input to RecordBatch. schema: schema of the input data. batch_size: representing the number of consecutive elements of returned dataset to combine in a single batch Returns: A dataset that contains (features, indices) tuple where features is a dictionary of Tensors, and indices is a single Tensor of label indices. """ return data_accessor.tf_dataset_factory( file_pattern, tfxio.TensorFlowDatasetOptions( batch_size=batch_size, label_key=_LABEL_KEY), schema=schema).repeat() def _build_keras_model() -> tf.keras.Model: """Creates a DNN Keras model for classifying penguin data. Returns: A Keras Model. """ # The model below is built with Functional API, please refer to # https://www.tensorflow.org/guide/keras/overview for all API options. inputs = [keras.layers.Input(shape=(1,), name=f) for f in _FEATURE_KEYS] d = keras.layers.concatenate(inputs) for _ in range(2): d = keras.layers.Dense(8, activation='relu')(d) outputs = keras.layers.Dense(3)(d) model = keras.Model(inputs=inputs, outputs=outputs) model.compile( optimizer=keras.optimizers.Adam(1e-2), loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=[keras.metrics.SparseCategoricalAccuracy()]) model.summary(print_fn=logging.info) return model # TFX Trainer will call this function. def run_fn(fn_args: tfx.components.FnArgs): """Train the model based on given args. Args: fn_args: Holds args used to train the model as name/value pairs. """ # This schema is usually either an output of SchemaGen or a manually-curated # version provided by pipeline author. A schema can also derived from TFT # graph if a Transform component is used. In the case when either is missing, # `schema_from_feature_spec` could be used to generate schema from very simple # feature_spec, but the schema returned would be very primitive. schema = schema_utils.schema_from_feature_spec(_FEATURE_SPEC) train_dataset = _input_fn( fn_args.train_files, fn_args.data_accessor, schema, batch_size=_TRAIN_BATCH_SIZE) eval_dataset = _input_fn( fn_args.eval_files, fn_args.data_accessor, schema, batch_size=_EVAL_BATCH_SIZE) model = _build_keras_model() model.fit( train_dataset, steps_per_epoch=fn_args.train_steps, validation_data=eval_dataset, validation_steps=fn_args.eval_steps) # The result of the training should be saved in `fn_args.serving_model_dir` # directory. model.save(fn_args.serving_model_dir, save_format='tf')
site/en-snapshot/tfx/tutorials/tfx/penguin_simple.ipynb
tensorflow/docs-l10n
apache-2.0
Now you have completed all preparation steps to build a TFX pipeline. Write a pipeline definition We define a function to create a TFX pipeline. A Pipeline object represents a TFX pipeline which can be run using one of the pipeline orchestration systems that TFX supports.
def _create_pipeline(pipeline_name: str, pipeline_root: str, data_root: str, module_file: str, serving_model_dir: str, metadata_path: str) -> tfx.dsl.Pipeline: """Creates a three component penguin pipeline with TFX.""" # Brings data into the pipeline. example_gen = tfx.components.CsvExampleGen(input_base=data_root) # Uses user-provided Python function that trains a model. trainer = tfx.components.Trainer( module_file=module_file, examples=example_gen.outputs['examples'], train_args=tfx.proto.TrainArgs(num_steps=100), eval_args=tfx.proto.EvalArgs(num_steps=5)) # Pushes the model to a filesystem destination. pusher = tfx.components.Pusher( model=trainer.outputs['model'], push_destination=tfx.proto.PushDestination( filesystem=tfx.proto.PushDestination.Filesystem( base_directory=serving_model_dir))) # Following three components will be included in the pipeline. components = [ example_gen, trainer, pusher, ] return tfx.dsl.Pipeline( pipeline_name=pipeline_name, pipeline_root=pipeline_root, metadata_connection_config=tfx.orchestration.metadata .sqlite_metadata_connection_config(metadata_path), components=components)
site/en-snapshot/tfx/tutorials/tfx/penguin_simple.ipynb
tensorflow/docs-l10n
apache-2.0
Run the pipeline TFX supports multiple orchestrators to run pipelines. In this tutorial we will use LocalDagRunner which is included in the TFX Python package and runs pipelines on local environment. We often call TFX pipelines "DAGs" which stands for directed acyclic graph. LocalDagRunner provides fast iterations for development and debugging. TFX also supports other orchestrators including Kubeflow Pipelines and Apache Airflow which are suitable for production use cases. See TFX on Cloud AI Platform Pipelines or TFX Airflow Tutorial to learn more about other orchestration systems. Now we create a LocalDagRunner and pass a Pipeline object created from the function we already defined. The pipeline runs directly and you can see logs for the progress of the pipeline including ML model training.
tfx.orchestration.LocalDagRunner().run( _create_pipeline( pipeline_name=PIPELINE_NAME, pipeline_root=PIPELINE_ROOT, data_root=DATA_ROOT, module_file=_trainer_module_file, serving_model_dir=SERVING_MODEL_DIR, metadata_path=METADATA_PATH))
site/en-snapshot/tfx/tutorials/tfx/penguin_simple.ipynb
tensorflow/docs-l10n
apache-2.0
You should see "INFO:absl:Component Pusher is finished." at the end of the logs if the pipeline finished successfully. Because Pusher component is the last component of the pipeline. The pusher component pushes the trained model to the SERVING_MODEL_DIR which is the serving_model/penguin-simple directory if you did not change the variables in the previous steps. You can see the result from the file browser in the left-side panel in Colab, or using the following command:
# List files in created model directory. !find {SERVING_MODEL_DIR}
site/en-snapshot/tfx/tutorials/tfx/penguin_simple.ipynb
tensorflow/docs-l10n
apache-2.0
Source localization with MNE/dSPM/sLORETA/eLORETA The aim of this tutorial is to teach you how to compute and apply a linear inverse method such as MNE/dSPM/sLORETA/eLORETA on evoked/raw/epochs data.
# sphinx_gallery_thumbnail_number = 10 import numpy as np import matplotlib.pyplot as plt import mne from mne.datasets import sample from mne.minimum_norm import make_inverse_operator, apply_inverse
0.17/_downloads/d25fdfa446b06c82b756855681845935/plot_mne_dspm_source_localization.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Process MEG data
data_path = sample.data_path() raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif' raw = mne.io.read_raw_fif(raw_fname) # already has an average reference events = mne.find_events(raw, stim_channel='STI 014') event_id = dict(aud_l=1) # event trigger and conditions tmin = -0.2 # start of each epoch (200ms before the trigger) tmax = 0.5 # end of each epoch (500ms after the trigger) raw.info['bads'] = ['MEG 2443', 'EEG 053'] picks = mne.pick_types(raw.info, meg=True, eeg=False, eog=True, exclude='bads') baseline = (None, 0) # means from the first instant to t = 0 reject = dict(grad=4000e-13, mag=4e-12, eog=150e-6) epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True, picks=picks, baseline=baseline, reject=reject)
0.17/_downloads/d25fdfa446b06c82b756855681845935/plot_mne_dspm_source_localization.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Compute regularized noise covariance For more details see tut_compute_covariance.
noise_cov = mne.compute_covariance( epochs, tmax=0., method=['shrunk', 'empirical'], rank=None, verbose=True) fig_cov, fig_spectra = mne.viz.plot_cov(noise_cov, raw.info)
0.17/_downloads/d25fdfa446b06c82b756855681845935/plot_mne_dspm_source_localization.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Compute the evoked response Let's just use MEG channels for simplicity.
evoked = epochs.average().pick_types(meg=True) evoked.plot(time_unit='s') evoked.plot_topomap(times=np.linspace(0.05, 0.15, 5), ch_type='mag', time_unit='s') # Show whitening evoked.plot_white(noise_cov, time_unit='s') del epochs # to save memory
0.17/_downloads/d25fdfa446b06c82b756855681845935/plot_mne_dspm_source_localization.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Inverse modeling: MNE/dSPM on evoked and raw data
# Read the forward solution and compute the inverse operator fname_fwd = data_path + '/MEG/sample/sample_audvis-meg-oct-6-fwd.fif' fwd = mne.read_forward_solution(fname_fwd) # make an MEG inverse operator info = evoked.info inverse_operator = make_inverse_operator(info, fwd, noise_cov, loose=0.2, depth=0.8) del fwd # You can write it to disk with:: # # >>> from mne.minimum_norm import write_inverse_operator # >>> write_inverse_operator('sample_audvis-meg-oct-6-inv.fif', # inverse_operator)
0.17/_downloads/d25fdfa446b06c82b756855681845935/plot_mne_dspm_source_localization.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Compute inverse solution
method = "dSPM" snr = 3. lambda2 = 1. / snr ** 2 stc, residual = apply_inverse(evoked, inverse_operator, lambda2, method=method, pick_ori=None, return_residual=True, verbose=True)
0.17/_downloads/d25fdfa446b06c82b756855681845935/plot_mne_dspm_source_localization.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Visualization View activation time-series
plt.figure() plt.plot(1e3 * stc.times, stc.data[::100, :].T) plt.xlabel('time (ms)') plt.ylabel('%s value' % method) plt.show()
0.17/_downloads/d25fdfa446b06c82b756855681845935/plot_mne_dspm_source_localization.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Examine the original data and the residual after fitting:
fig, axes = plt.subplots(2, 1) evoked.plot(axes=axes) for ax in axes: ax.texts = [] for line in ax.lines: line.set_color('#98df81') residual.plot(axes=axes)
0.17/_downloads/d25fdfa446b06c82b756855681845935/plot_mne_dspm_source_localization.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Here we use peak getter to move visualization to the time point of the peak and draw a marker at the maximum peak vertex.
vertno_max, time_max = stc.get_peak(hemi='rh') subjects_dir = data_path + '/subjects' surfer_kwargs = dict( hemi='rh', subjects_dir=subjects_dir, clim=dict(kind='value', lims=[8, 12, 15]), views='lateral', initial_time=time_max, time_unit='s', size=(800, 800), smoothing_steps=5) brain = stc.plot(**surfer_kwargs) brain.add_foci(vertno_max, coords_as_verts=True, hemi='rh', color='blue', scale_factor=0.6, alpha=0.5) brain.add_text(0.1, 0.9, 'dSPM (plus location of maximal activation)', 'title', font_size=14)
0.17/_downloads/d25fdfa446b06c82b756855681845935/plot_mne_dspm_source_localization.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Morph data to average brain
# setup source morph morph = mne.compute_source_morph( src=inverse_operator['src'], subject_from=stc.subject, subject_to='fsaverage', spacing=5, # to ico-5 subjects_dir=subjects_dir) # morph data stc_fsaverage = morph.apply(stc) brain = stc_fsaverage.plot(**surfer_kwargs) brain.add_text(0.1, 0.9, 'Morphed to fsaverage', 'title', font_size=20) del stc_fsaverage
0.17/_downloads/d25fdfa446b06c82b756855681845935/plot_mne_dspm_source_localization.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Dipole orientations The pick_ori parameter of the :func:mne.minimum_norm.apply_inverse function controls the orientation of the dipoles. One useful setting is pick_ori='vector', which will return an estimate that does not only contain the source power at each dipole, but also the orientation of the dipoles.
stc_vec = apply_inverse(evoked, inverse_operator, lambda2, method=method, pick_ori='vector') brain = stc_vec.plot(**surfer_kwargs) brain.add_text(0.1, 0.9, 'Vector solution', 'title', font_size=20) del stc_vec
0.17/_downloads/d25fdfa446b06c82b756855681845935/plot_mne_dspm_source_localization.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
Note that there is a relationship between the orientation of the dipoles and the surface of the cortex. For this reason, we do not use an inflated cortical surface for visualization, but the original surface used to define the source space. For more information about dipole orientations, see sphx_glr_auto_tutorials_plot_dipole_orientations.py. Now let's look at each solver:
for mi, (method, lims) in enumerate((('dSPM', [8, 12, 15]), ('sLORETA', [3, 5, 7]), ('eLORETA', [0.75, 1.25, 1.75]),)): surfer_kwargs['clim']['lims'] = lims stc = apply_inverse(evoked, inverse_operator, lambda2, method=method, pick_ori=None) brain = stc.plot(figure=mi, **surfer_kwargs) brain.add_text(0.1, 0.9, method, 'title', font_size=20) del stc
0.17/_downloads/d25fdfa446b06c82b756855681845935/plot_mne_dspm_source_localization.ipynb
mne-tools/mne-tools.github.io
bsd-3-clause
There are some infeasibilities without line extensions.
for line_name in ["316", "527", "602"]: network.lines.loc[line_name, "s_nom"] = 1200 now = network.snapshots[0]
examples/notebooks/scigrid-sclopf.ipynb
PyPSA/PyPSA
mit
Performing security-constrained linear OPF
branch_outages = network.lines.index[:15] network.sclopf(now, branch_outages=branch_outages, solver_name="cbc")
examples/notebooks/scigrid-sclopf.ipynb
PyPSA/PyPSA
mit
For the PF, set the P to the optimised P.
network.generators_t.p_set = network.generators_t.p_set.reindex( columns=network.generators.index ) network.generators_t.p_set.loc[now] = network.generators_t.p.loc[now] network.storage_units_t.p_set = network.storage_units_t.p_set.reindex( columns=network.storage_units.index ) network.storage_units_t.p_set.loc[now] = network.storage_units_t.p.loc[now]
examples/notebooks/scigrid-sclopf.ipynb
PyPSA/PyPSA
mit
Check no lines are overloaded with the linear contingency analysis
p0_test = network.lpf_contingency(now, branch_outages=branch_outages) p0_test
examples/notebooks/scigrid-sclopf.ipynb
PyPSA/PyPSA
mit
Check loading as per unit of s_nom in each contingency
max_loading = ( abs(p0_test.divide(network.passive_branches().s_nom, axis=0)).describe().loc["max"] ) max_loading np.allclose(max_loading, np.ones((len(max_loading))))
examples/notebooks/scigrid-sclopf.ipynb
PyPSA/PyPSA
mit
1.2 Train Ridge Regression on training data The first step is to train the ridge regression model on the training data with a 5-fold cross-validation with an internal line-search to find the optimal hyperparameter $\alpha$. We will plot the training errors against the validation errors, to illustrate the effect of different $\alpha$ values.
#Initialize different alpha values for the Ridge Regression model alphas = sp.logspace(-2,8,11) param_grid = dict(alpha=alphas) #5-fold cross-validation (outer-loop) outer_cv = KFold(n_splits=5,shuffle=True,random_state=random_state) #Line-search to find the optimal alpha value (internal-loop) #Model performance is measured with the negative mean squared error line_search = GridSearchCV(Ridge(random_state=random_state,solver="cholesky"), param_grid=param_grid, scoring="neg_mean_squared_error", return_train_score=True) #Execute nested cross-validation and compute mean squared error score = cross_val_score(line_search,X=training_data,y=training_target,cv=outer_cv,scoring="neg_mean_squared_error") print("5-fold nested cross-validation") print("Mean-Squared-Error:\t\t%.2f (-+ %.2f)"%(score.mean()*(-1),score.std())) print() #Estimate optimal alpha on the full training data line_search.fit(training_data,training_target) optimal_alpha = line_search.best_params_['alpha'] #Visualize training and validation error for different alphas visualized_variance_bias_tradeoff(alphas, line_search, optimal_alpha)
Toy-Example-Solution.ipynb
dominikgrimm/ridge_and_svm
mit
1.3 Train Ridge Regression with optimal $\alpha$ and evaluate model in test data Next we retrain the ridge regresssion model with the optimal $\alpha$ (from the last section). After re-training we will test the model on the not used test data to evaluate the model performance on unseen data.
#Train Ridge Regression on the full training data with optimal alpha model = Ridge(alpha=optimal_alpha,solver="cholesky") model.fit(training_data,training_target) #Use trained model the predict new instances in test data predictions = model.predict(testing_data) print("Prediction results on test data") print("MSE (test data, alpha=optimal):\t%.2f "%(mean_squared_error(testing_target,predictions))) print("Optimal Alpha:\t\t\t%.2f"%optimal_alpha) print()
Toy-Example-Solution.ipynb
dominikgrimm/ridge_and_svm
mit
<div style="text-align:justify"> Using 5-fold cross-validation on the training data leads to a mean squared error (MSE) of $MSE=587.09 \pm 53.54$. On the test data we get an error of $MSE=699.56$ ($\sim 26.5$ days). That indicates that the ridge regression model performs rather mediocre (even with hyperparameter optimization). One reason might be that the target variable (number of days until the drug shows a positive response) is insufficently described by the given features (genetic mutations). </div> 2. Prediction of patients with slow and fast response times using a Support-Vector-Machine <div style="text-align:justify"> Due to the rather bad results with the ridge regession model the machine learning lab returned to the researchers to discuss potential issues. The researches than mentioned that it might not be necessarily important to predict the exact number of days. It might be even better to only predict if a patient reacts fast or slowly on the drug. Based on some prior experiments the researchers observed, that most of the patients showed severe side-effects after 50 days of treatment. Thus we can binarise the data, such that all patients below 50 days are put into class 0 and all others into class 1. This leads to a classical classification problem for which a support vector machine could be used. </div> 2.1 Data Preprocessing
#Split data into training and testing splits, stratified by class-ratios stratiefied_splitter = StratifiedShuffleSplit(n_splits=1,test_size=0.2,random_state=42) for train_index,test_index in stratiefied_splitter.split(data,binary_target): training_data = data[train_index,:] training_target = binary_target[train_index] testing_data = data[test_index,:] testing_target = binary_target[test_index] print("Training Data") print("Number Patients:\t\t%d"%training_data.shape[0]) print("Number Features:\t\t%d"%training_data.shape[1]) print("Number Patients Class 0:\t%d"%(training_target==0).sum()) print("Number Patients Class 1:\t%d"%(training_target==1).sum()) print() print("Testing Data") print("Number Patients:\t\t%d"%testing_data.shape[0]) print("Number Features:\t\t%d"%testing_data.shape[1]) print("Number Patients Class 0:\t%d"%(testing_target==0).sum()) print("Number Patients Class 1:\t%d"%(testing_target==1).sum())
Toy-Example-Solution.ipynb
dominikgrimm/ridge_and_svm
mit
2.2 Classification with a linear SVM
Cs = sp.logspace(-7, 1, 9) param_grid = dict(C=Cs) grid = GridSearchCV(SVC(kernel="linear",random_state=random_state), param_grid=param_grid, scoring="accuracy", n_jobs=4, return_train_score=True) outer_cv = StratifiedKFold(n_splits=5,shuffle=True,random_state=random_state) #Perform 5 Fold cross-validation with internal line-search and report average Accuracy score = cross_val_score(grid,X=training_data,y=training_target,cv=outer_cv,scoring="accuracy") print("5-fold nested cross-validation on training data") print("Average(Accuracy):\t\t\t%.2f (-+ %.2f)"%(score.mean(),score.std())) print() grid.fit(training_data,training_target) optimal_C = grid.best_params_['C'] #Plot variance bias tradeoff visualized_variance_bias_tradeoff(Cs, grid, optimal_C,classification=True) #retrain model with optimal C and evaluate on test data model = SVC(C=optimal_C,random_state=random_state,kernel="linear") model.fit(training_data,training_target) predictions = model.predict(testing_data) print("Prediction with optimal C") print("Accuracy (Test data, C=Optimal):\t%.2f "%(accuracy_score(testing_target,predictions))) print("Optimal C:\t\t\t\t%.2e"%optimal_C) print() #Compute ROC FPR, TPR and AUC fpr, tpr, _ = roc_curve(testing_target, model.decision_function(testing_data)) roc_auc = auc(fpr, tpr) #Plot ROC Curve pl.figure(figsize=(8,8)) pl.plot(fpr, tpr, color='darkorange', lw=3, label='ROC curve (AUC = %0.2f)' % roc_auc) pl.plot([0, 1], [0, 1], color='navy', lw=3, linestyle='--') pl.xlim([-0.01, 1.0]) pl.ylim([0.0, 1.05]) pl.xlabel('False Positive Rate (1-Specificity)',fontsize=18) pl.ylabel('True Positive Rate (Sensitivity)',fontsize=18) pl.title('Receiver Operating Characteristic (ROC) Curve',fontsize=18) pl.legend(loc="lower right",fontsize=18)
Toy-Example-Solution.ipynb
dominikgrimm/ridge_and_svm
mit
2.3 Classification with SVM and RBF kernel
Cs = sp.logspace(-4, 4, 9) gammas = sp.logspace(-7, 1, 9) param_grid = dict(C=Cs,gamma=gammas) grid = GridSearchCV(SVC(kernel="rbf",random_state=42), param_grid=param_grid, scoring="accuracy", n_jobs=4, return_train_score=True) outer_cv = StratifiedKFold(n_splits=5,shuffle=True,random_state=random_state) #Perform 5 Fold cross-validation with internal line-search and report average Accuracy score = cross_val_score(grid,X=training_data,y=training_target,cv=outer_cv,scoring="accuracy") print("5-fold nested cross-validation on training data") print("Average(Accuracy):\t\t\t%.2f (-+ %.2f)"%(score.mean(),score.std())) print() grid.fit(training_data,training_target) optimal_C = grid.best_params_['C'] optimal_gamma = grid.best_params_['gamma'] #Retrain and test model = SVC(C=optimal_C,gamma=optimal_gamma,random_state=42,kernel="rbf") model.fit(training_data,training_target) predictions = model.predict(testing_data) print("Prediction with optimal C and Gamma") print("Accuracy (Test Data, C=Optimal):\t%.2f "%(accuracy_score(testing_target,predictions))) print("Optimal C:\t\t\t\t%.2e"%optimal_C) print("Optimal Gamma:\t\t\t\t%.2e"%optimal_gamma) print() #Compute ROC FPR, TPR and AUC fpr, tpr, _ = roc_curve(testing_target, model.decision_function(testing_data)) roc_auc = auc(fpr, tpr) #Plot ROC Curve pl.figure(figsize=(8,8)) pl.plot(fpr, tpr, color='darkorange', lw=3, label='ROC curve (AUC = %0.2f)' % roc_auc) pl.plot([0, 1], [0, 1], color='navy', lw=3, linestyle='--') pl.xlim([-0.01, 1.0]) pl.ylim([0.0, 1.05]) pl.xlabel('False Positive Rate (1-Specificity)',fontsize=18) pl.ylabel('True Positive Rate (Sensitivity)',fontsize=18) pl.title('Receiver Operating Characteristic (ROC) Curve',fontsize=18) pl.legend(loc="lower right",fontsize=18)
Toy-Example-Solution.ipynb
dominikgrimm/ridge_and_svm
mit
We use the <b> Iris dataset </b> https://en.m.wikipedia.org/wiki/Iris_flower_data_set The data set consists of 50 samples from each of three species of Iris (Iris setosa, Iris virginica and Iris versicolor). Four features were measured from each sample: the length and the width of the sepals and petals, in centimetres. Based on the combination of these four features, Fisher developed a linear discriminant model to distinguish the species from each other. logistic regression While logistic regression gives each predictor (independent variable) a coefficient ‘b’ which measures its independent contribution to variations in the dependent variable, the dependent variable can only take on one of the two values: 0 or 1. What we want to predict from knowledge of relevant independent variables and coefficients is therefore not a numerical value of a dependent variable as in linear regression, but rather the probability (p) that it is 1 rather than 0 (belonging to one group rather than the other). The outcome of the regression is not a prediction of a Y value, as in linear regression, but a probability of belonging to one of two conditions of Y, which can take on any value between 0 and 1 rather than just 0 and 1. The crucial limitation of linear regression is that it cannot deal with dependent variable’s that are dichotomous and categorical. Many interesting variables are dichotomous: for example, consumers make a decision to buy or not buy, a product may pass or fail quality control, there are good or poor credit risks, an employee may be promoted or not. A range of regression techniques have been developed for analysing data with categorical dependent variables, including logistic regression and discriminant analysis.
model = LogisticRegression() model.fit(dataset.data, dataset.target) expected = dataset.target predicted = model.predict(dataset.data) # classification metrics report builds a text report showing the main classification metrics # In pattern recognition and information retrieval with binary classification, # precision (also called positive predictive value) is the fraction of retrieved instances that are relevant, # while recall (also known as sensitivity) is the fraction of relevant instances that are retrieved. # Both precision and recall are therefore based on an understanding and measure of relevance. # Suppose a computer program for recognizing dogs in scenes from a video identifies 7 dogs in a scene containing 9 dogs # and some cats. If 4 of the identifications are correct, but 3 are actually cats, the program's precision is 4/7 # while its recall is 4/9. # In statistical analysis of binary classification, the F1 score (also F-score or F-measure) is a measure of a test's accuracy. # It considers both the precision p and the recall r of the test to compute the score: # p is the number of correct positive results divided by the number of all positive results, # and r is the number of correct positive results divided by the number of positive results that should have been returned. # The F1 score can be interpreted as a weighted average of the precision and recall print(metrics.classification_report(expected, predicted)) # Confusion matrix # https://en.wikipedia.org/wiki/Confusion_matrix # In the field of machine learning, a confusion matrix is a table layout that allows visualization of the performance # of an algorithm, typically a supervised learning one. # Each column of the matrix represents the instances in a predicted class # while each row represents the instances in an actual class (or vice-versa) # If a classification system has been trained to distinguish between cats, dogs and rabbits, # a confusion matrix will summarize the results of testing the algorithm for further inspection. # Assuming a sample of 27 animals — 8 cats, 6 dogs, and 13 rabbits, the resulting confusion matrix # could look like the table below: Image("http://www.opengardensblog.futuretext.com/wp-content/uploads/2016/01/confusion-matrix.jpg") # In this confusion matrix, of the 8 actual cats, the system predicted that three were dogs, # and of the six dogs, it predicted that one was a rabbit and two were cats. # We can see from the matrix that the system in question has trouble distinguishing between cats and dogs, # but can make the distinction between rabbits and other types of animals pretty well. # All correct guesses are located in the diagonal of the table, so it's easy to visually # inspect the table for errors, as they will be represented by values outside the diagonal. print (metrics.confusion_matrix(expected, predicted)) import pandas as pd
Session3/code/03 Supervised Learning - 00 Python basics and Logistic Regression.ipynb
catalystcomputing/DSIoT-Python-sessions
apache-2.0
We typically need the following libraries: <b> NumPy </b> Numerical Python - mainly used for n-dimensional array(which is absent in traditional Python). Also contains basic linear algebra functions, Fourier transforms, advanced random number capabilities and tools for integration with other low level languages like Fortran, C and C++ <b>SciPy</b> Scientific Python (built on NumPy). Contains a variety of high level science and engineering modules like discrete Fourier transform, Linear Algebra, Optimization and Sparse matrices. <b> Matplotlib </b> for plotting vast variety of graphs ex histograms, line plots and heat maps. <b> Pandas </b> for structured data operations and data manipulation. It is extensively used for pre processing. <b> Scikit Learn </b> for machine learning. Built on NumPy, SciPy and matplotlib, this library contains a lot of effiecient tools for machine learning and statistical modeling including classification, regression, clustering and dimensionality reduction. Statsmodels for statistical modeling. Statsmodels is a Python module that allows users to explore data, estimate statistical models, and perform statistical tests. An extensive list of descriptive statistics, statistical tests, plotting functions, and result statistics are available for different types of data and each estimator. Seaborn for statistical data visualization. Seaborn is a library for making attractive and informative statistical graphics in Python. It is based on matplotlib. Seaborn aims to make visualization a central part of exploring and understanding data. <b>Additional libraries, you might need:</b> urllib for web based operations like opening URLs and performing operations os for Operating system and file operations networkx and igraph for graph based data manipulations regular expressions for finding patterns in text data BeautifulSoup for scrapping web
integers_list = [1,3,5,7,9] # lists are seperated by square brackets print(integers_list) tuple_integers = 1,3,5,7,9 #tuples are seperated by commas and are immutable print(tuple_integers) tuple_integers[0] = 11 #Python strings can be in single or double quotes string_ds = "Data Science" string_iot = "Internet of Things" string_dsiot = string_ds + " for " + string_iot print (string_dsiot) len(string_dsiot) # sets are unordered collections with no duplicate elements prog_languages = set(['Python', 'Java', 'Scala']) prog_languages # Dictionaies are comma seperated key value pairs seperated by braces dict_marks = {'John':95, 'Mark': 100, 'Anna': 99} dict_marks['John']
Session3/code/03 Supervised Learning - 00 Python basics and Logistic Regression.ipynb
catalystcomputing/DSIoT-Python-sessions
apache-2.0
Evaluation of your model
# let's try to visualize the estimated and real house values for all data points in test dataset fig, ax = plt.subplots(figsize=(15, 5)) plt.subplot(1, 2, 1) plt.plot(X_test_1,predictions_1, 'o') plt.xlabel('% of lower status of the population') plt.ylabel('Estimated home value in $1000s') plt.subplot(1, 2, 2) plt.plot(X_test_1,y_test_1, 'o') plt.xlabel('% of lower status of the population') plt.ylabel('Median home value in $1000s') plt.tight_layout() plt.show()
aps/notebooks/ml_varsom/linear_regression.ipynb
kmunve/APS
mit
To evaulate the performance of the model, we can compute the error between the real house value (y_test_1) and the predicted values we got form our model (predictions_1). One such metric is called the residual sum of squares (RSS):
# first we define our RSS function def RSS(y, p): return sum((y - p)**2) # then we calculate RSS: RSS_model_1 = RSS(y_test_1, predictions_1) RSS_model_1
aps/notebooks/ml_varsom/linear_regression.ipynb
kmunve/APS
mit
This number doesn't tell us much - is 7027 good? Is it bad? Unfortunatelly, there is no right answer - it depends on the data. Sometimes RSS of 7000 indicates very bad model, and sometimes 7000 is as good as it gets. That's why we use RSS when comparing models - the model with lowest RSS is the best. The other metrics we can use to evaluate our model is called coefficient of determination. It's denoted as $R^{2}$ and it is the proportion of the variance in the dependent variable that is predictable from the independent variable(s). To calculate it, we use .score function in Python.
lm1.score(X_test_1,y_test_1)
aps/notebooks/ml_varsom/linear_regression.ipynb
kmunve/APS
mit
This means that only 51% of variability is explained by our model. In general, $R^{2}$ is a number between 0 and 1 - the closer it is to 1, the better the model is. Since we got only 0.51, we can conclude that this is not a very good model. But we can try to build a model with second variable - RM - and check if we can get better result. More linear regression models
# we just repeat everything as before X_train_2, X_test_2, y_train_2, y_test_2 = train_test_split(boston_data[['RM']], boston_data.MEDV, random_state = 222, test_size = 0.3) # split the data lm = linear_model.LinearRegression() model_2 = lm.fit(X_train_2, y_train_2) # train the model predictions_2 = model_2.predict(X_test_2) # predict values for test dataset print("Our second model: y = {0:.2f}".format(model_2.intercept_) + " + {0:.2f}".format(model_2.coef_[0]) + " * x") # let's visualize our regression line plt.plot(X_test_2, y_test_2, 'o') plt.plot(X_test_2, predictions_2, color = 'red') plt.xlabel('Average number of rooms') plt.ylabel('Median home value in $1000s') # let's calculate RSS and R^2 print (RSS(y_test_2, predictions_2)) print (lm.score(X_test_2, y_test_2)) # now we can compare our models print("RSS for first model is {0:.2f}".format(RSS(y_test_1, predictions_1)) + ", and RSS for second model is {0:.2f}".format(RSS(y_test_2, predictions_2)) + '\n' + '\n' + "R^2 for first model is {0:.2f}".format(lm1.score(X_test_1, y_test_1)) + ", and R^2 for second model is {0:.2f}".format(lm.score(X_test_2, y_test_2)))
aps/notebooks/ml_varsom/linear_regression.ipynb
kmunve/APS
mit
Since RSS is lower for second modell (and lower the RSS, better the model) and $R^{2}$ is higher for second modell (and we want $R^{2}$ as close to 1 as possible), both measures tells us that second model is better. However, difference is not big - out second model performs slightly better, but we still can't say it fits our data well. Next thing we can try is to build a model with all features we have available and see if using multiple features improves performace of the model.
X = boston_data[['CRIM', 'ZN', 'INDUS', 'CHAS', 'RM', 'AGE', 'RAD', 'TAX', 'PTRATIO', 'B', 'LSTAT']] y = boston_data["MEDV"] X_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 222, test_size = 0.3) # split the data lm = linear_model.LinearRegression() model_lr = lm.fit(X_train, y_train) # train the model predictions_lr = model_lr.predict(X_test) # predict values for test dataset print("Our third model: \n \ny = {0:.2f}".format(model_lr.intercept_) + " {0:.2f}".format(model_lr.coef_[0]) + " * CRIM" + " + {0:.2f}".format(model_lr.coef_[1]) + " * ZN" + " + {0:.2f}".format(model_lr.coef_[2]) + " * INDUS" + " + {0:.2f}".format(model_lr.coef_[3]) + " + * CHAS" + " {0:.2f}".format(model_lr.coef_[4]) + " * RM" + " + {0:.2f}".format(model_lr.coef_[5]) + " * AGE" + " + {0:.2f}".format(model_lr.coef_[6]) + " * RAD" + "\n {0:.2f}".format(model_lr.coef_[7]) + " * TAX" + " {0:.2f}".format(model_lr.coef_[8]) + " * PTRATIO" + " + {0:.2f}".format(model_lr.coef_[9]) + " * B" + " {0:.2f}".format(model_lr.coef_[10]) + " * LSTAT") # let's evaluate the model print("RSS for the third model is {0:.2f}".format(RSS(y_test, predictions_lr)) + '\n' + '\n' + "R^2 for the third model is {0:.2f}".format(lm.score(X_test, y_test)) )
aps/notebooks/ml_varsom/linear_regression.ipynb
kmunve/APS
mit
Navigation Handling the loop yourself Comparing with the high level API 1. Handling the loop yourself For the purposes of this notebook we are going to use one of the predefined objective functions that come with GPyOpt. However, the key thing to realize is that the function could be anything (e.g., the results of a physical experiment). As long as users are able to externally evaluate the suggested points and provide GPyOpt with the results, the library has options for setting the objective function's origin.
from emukit.test_functions import forrester_function from emukit.core.loop import UserFunctionWrapper target_function, space = forrester_function()
notebooks/Emukit-tutorial-bayesian-optimization-external-objective-evaluation.ipynb
EmuKit/emukit
apache-2.0
First we are going to run the optimization loop outside of Emukit, and only use the library to get the next point at which to evaluate our function. There are two things to pay attention to when creating the main optimization object: Since we recreate the object anew for each iteration, we need to pass data about all previous iterations to it. The model gets optimized from the scratch in every iteration but the parameters of the model could be saved and used to update the state (TODO). We start with three initial points at which we evaluate the objective function.
X = np.array([[0.1],[0.6],[0.9]]) Y = target_function(X)
notebooks/Emukit-tutorial-bayesian-optimization-external-objective-evaluation.ipynb
EmuKit/emukit
apache-2.0
And we run the loop externally.
from emukit.examples.gp_bayesian_optimization.single_objective_bayesian_optimization import GPBayesianOptimization from emukit.core.loop import UserFunctionResult num_iterations = 10 bo = GPBayesianOptimization(variables_list=space.parameters, X=X, Y=Y) results = None for _ in range(num_iterations): X_new = bo.get_next_points(results) Y_new = target_function(X_new) results = [UserFunctionResult(X_new[0], Y_new[0])] X = bo.loop_state.X Y = bo.loop_state.Y
notebooks/Emukit-tutorial-bayesian-optimization-external-objective-evaluation.ipynb
EmuKit/emukit
apache-2.0
Let's visualize the results. The size of the marker denotes the order in which the point was evaluated - the bigger the marker the later was the evaluation.
x = np.arange(0.0, 1.0, 0.01) y = target_function(x) plt.figure() plt.plot(x, y) for i, (xs, ys) in enumerate(zip(X, Y)): plt.plot(xs, ys, 'ro', markersize=10 + 10 * (i+1)/len(X)) X
notebooks/Emukit-tutorial-bayesian-optimization-external-objective-evaluation.ipynb
EmuKit/emukit
apache-2.0
2. Comparing with the high level API To compare the results, let's now execute the whole loop with Emukit.
X = np.array([[0.1],[0.6],[0.9]]) Y = target_function(X) bo_loop = GPBayesianOptimization(variables_list=space.parameters, X=X, Y=Y) bo_loop.run_optimization(target_function, num_iterations)
notebooks/Emukit-tutorial-bayesian-optimization-external-objective-evaluation.ipynb
EmuKit/emukit
apache-2.0
Now let's print the results of this optimization and compare it to the previous external evaluation run. As before, the size of the marker corresponds to its evaluation order.
x = np.arange(0.0, 1.0, 0.01) y = target_function(x) plt.figure() plt.plot(x, y) for i, (xs, ys) in enumerate(zip(bo_loop.model.model.X, bo_loop.model.model.Y)): plt.plot(xs, ys, 'ro', markersize=10 + 10 * (i+1)/len(bo_loop.model.model.X))
notebooks/Emukit-tutorial-bayesian-optimization-external-objective-evaluation.ipynb
EmuKit/emukit
apache-2.0
Test data We create test data consisting of 5 variables.
psi0 = np.array([ [ 0. , 0. , -0.25, 0. , 0. ], [-0.38, 0. , 0.14, 0. , 0. ], [ 0. , 0. , 0. , 0. , 0. ], [ 0.44, -0.2 , -0.09, 0. , 0. ], [ 0.07, -0.06, 0. , 0.07, 0. ] ]) phi1 = np.array([ [-0.04, -0.29, -0.26, 0.14, 0.47], [-0.42, 0.2 , 0.1 , 0.24, 0.25], [-0.25, 0.18, -0.06, 0.15, 0.18], [ 0.22, 0.39, 0.08, 0.12, -0.37], [-0.43, 0.09, -0.23, 0.16, 0.25] ]) theta1 = np.array([ [ 0.15, -0.02, -0.3 , -0.2 , 0.21], [ 0.32, 0.12, -0.11, 0.03, 0.42], [-0.07, -0.5 , 0.03, -0.27, -0.21], [-0.17, 0.35, 0.25, 0.24, -0.25], [ 0.09, 0.4 , 0.41, 0.24, -0.31] ]) causal_order = [2, 0, 1, 3, 4] # data generated from psi0 and phi1 and theta1, causal_order X = np.loadtxt('data/sample_data_varma_lingam.csv', delimiter=',')
examples/VARMALiNGAM.ipynb
cdt15/lingam
mit
Causal Discovery To run causal discovery, we create a VARMALiNGAM object and call the fit method.
model = lingam.VARMALiNGAM(order=(1, 1), criterion=None) model.fit(X)
examples/VARMALiNGAM.ipynb
cdt15/lingam
mit
Using the causal_order_ properties, we can see the causal ordering as a result of the causal discovery.
model.causal_order_
examples/VARMALiNGAM.ipynb
cdt15/lingam
mit
Also, using the adjacency_matrices_ properties, we can see the adjacency matrix as a result of the causal discovery.
# psi0 model.adjacency_matrices_[0][0] # psi1 model.adjacency_matrices_[0][1] # omega0 model.adjacency_matrices_[1][0]
examples/VARMALiNGAM.ipynb
cdt15/lingam
mit
Using DirectLiNGAM for the residuals_ properties, we can calculate psi0 matrix.
dlingam = lingam.DirectLiNGAM() dlingam.fit(model.residuals_) dlingam.adjacency_matrix_
examples/VARMALiNGAM.ipynb
cdt15/lingam
mit
We can draw a causal graph by utility funciton
labels = ['y0(t)', 'y1(t)', 'y2(t)', 'y3(t)', 'y4(t)', 'y0(t-1)', 'y1(t-1)', 'y2(t-1)', 'y3(t-1)', 'y4(t-1)'] make_dot(np.hstack(model.adjacency_matrices_[0]), lower_limit=0.3, ignore_shape=True, labels=labels)
examples/VARMALiNGAM.ipynb
cdt15/lingam
mit
Independence between error variables To check if the LiNGAM assumption is broken, we can get p-values of independence between error variables. The value in the i-th row and j-th column of the obtained matrix shows the p-value of the independence of the error variables $e_i$ and $e_j$.
p_values = model.get_error_independence_p_values() print(p_values)
examples/VARMALiNGAM.ipynb
cdt15/lingam
mit
Bootstrap Bootstrapping We call bootstrap() method instead of fit(). Here, the second argument specifies the number of bootstrap sampling.
model = lingam.VARMALiNGAM() result = model.bootstrap(X, n_sampling=100)
examples/VARMALiNGAM.ipynb
cdt15/lingam
mit
Causal Directions Since BootstrapResult object is returned, we can get the ranking of the causal directions extracted by get_causal_direction_counts() method. In the following sample code, n_directions option is limited to the causal directions of the top 8 rankings, and min_causal_effect option is limited to causal directions with a coefficient of 0.4 or more.
cdc = result.get_causal_direction_counts(n_directions=8, min_causal_effect=0.4, split_by_causal_effect_sign=True)
examples/VARMALiNGAM.ipynb
cdt15/lingam
mit
We can check the result by utility function.
labels = ['y0(t)', 'y1(t)', 'y2(t)', 'y3(t)', 'y4(t)', 'y0(t-1)', 'y1(t-1)', 'y2(t-1)', 'y3(t-1)', 'y4(t-1)', 'e0(t-1)', 'e1(t-1)', 'e2(t-1)', 'e3(t-1)', 'e4(t-1)'] print_causal_directions(cdc, 100, labels=labels)
examples/VARMALiNGAM.ipynb
cdt15/lingam
mit
Directed Acyclic Graphs Also, using the get_directed_acyclic_graph_counts() method, we can get the ranking of the DAGs extracted. In the following sample code, n_dags option is limited to the dags of the top 3 rankings, and min_causal_effect option is limited to causal directions with a coefficient of 0.3 or more.
dagc = result.get_directed_acyclic_graph_counts(n_dags=3, min_causal_effect=0.3, split_by_causal_effect_sign=True)
examples/VARMALiNGAM.ipynb
cdt15/lingam
mit
We can check the result by utility function.
print_dagc(dagc, 100, labels=labels)
examples/VARMALiNGAM.ipynb
cdt15/lingam
mit
Probability Using the get_probabilities() method, we can get the probability of bootstrapping.
prob = result.get_probabilities(min_causal_effect=0.1) print('Probability of psi0:\n', prob[0]) print('Probability of psi1:\n', prob[1]) print('Probability of omega1:\n', prob[2])
examples/VARMALiNGAM.ipynb
cdt15/lingam
mit
Total Causal Effects Using the get_total causal_effects() method, we can get the list of total causal effect. The total causal effects we can get are dictionary type variable. We can display the list nicely by assigning it to pandas.DataFrame. Also, we have replaced the variable index with a label below.
causal_effects = result.get_total_causal_effects(min_causal_effect=0.01) df = pd.DataFrame(causal_effects) df['from'] = df['from'].apply(lambda x : labels[x]) df['to'] = df['to'].apply(lambda x : labels[x]) df
examples/VARMALiNGAM.ipynb
cdt15/lingam
mit
We can easily perform sorting operations with pandas.DataFrame.
df.sort_values('effect', ascending=False).head()
examples/VARMALiNGAM.ipynb
cdt15/lingam
mit
And with pandas.DataFrame, we can easily filter by keywords. The following code extracts the causal direction towards y2(t).
df[df['to']=='y2(t)'].head()
examples/VARMALiNGAM.ipynb
cdt15/lingam
mit
Because it holds the raw data of the causal effect (the original data for calculating the median), it is possible to draw a histogram of the values of the causal effect, as shown below.
import matplotlib.pyplot as plt import seaborn as sns sns.set() %matplotlib inline from_index = 5 # index of y0(t-1). (index:0)+(n_features:5)*(lag:1) = 5 to_index = 2 # index of y2(t). (index:2)+(n_features:5)*(lag:0) = 2 plt.hist(result.total_effects_[:, to_index, from_index])
examples/VARMALiNGAM.ipynb
cdt15/lingam
mit
First we'll load the text file and convert it into integers for our network to use.
with open('anna.txt', 'r') as f: text=f.read() vocab = set(text) vocab_to_int = {c: i for i, c in enumerate(vocab)} int_to_vocab = dict(enumerate(vocab)) chars = np.array([vocab_to_int[c] for c in text], dtype=np.int32) text[:100] chars[:100]
tensorboard/Anna_KaRNNa.ipynb
mdiaz236/DeepLearningFoundations
mit
Now I need to split up the data into batches, and into training and validation sets. I should be making a test set here, but I'm not going to worry about that. My test will be if the network can generate new text. Here I'll make both input and target arrays. The targets are the same as the inputs, except shifted one character over. I'll also drop the last bit of data so that I'll only have completely full batches. The idea here is to make a 2D matrix where the number of rows is equal to the number of batches. Each row will be one long concatenated string from the character data. We'll split this data into a training set and validation set using the split_frac keyword. This will keep 90% of the batches in the training set, the other 10% in the validation set.
def split_data(chars, batch_size, num_steps, split_frac=0.9): """ Split character data into training and validation sets, inputs and targets for each set. Arguments --------- chars: character array batch_size: Size of examples in each of batch num_steps: Number of sequence steps to keep in the input and pass to the network split_frac: Fraction of batches to keep in the training set Returns train_x, train_y, val_x, val_y """ slice_size = batch_size * num_steps n_batches = int(len(chars) / slice_size) # Drop the last few characters to make only full batches x = chars[: n_batches*slice_size] y = chars[1: n_batches*slice_size + 1] # Split the data into batch_size slices, then stack them into a 2D matrix x = np.stack(np.split(x, batch_size)) y = np.stack(np.split(y, batch_size)) # Now x and y are arrays with dimensions batch_size x n_batches*num_steps # Split into training and validation sets, keep the virst split_frac batches for training split_idx = int(n_batches*split_frac) train_x, train_y= x[:, :split_idx*num_steps], y[:, :split_idx*num_steps] val_x, val_y = x[:, split_idx*num_steps:], y[:, split_idx*num_steps:] return train_x, train_y, val_x, val_y train_x, train_y, val_x, val_y = split_data(chars, 10, 200) train_x.shape train_x[:,:10]
tensorboard/Anna_KaRNNa.ipynb
mdiaz236/DeepLearningFoundations
mit
I'll write another function to grab batches out of the arrays made by split data. Here each batch will be a sliding window on these arrays with size batch_size X num_steps. For example, if we want our network to train on a sequence of 100 characters, num_steps = 100. For the next batch, we'll shift this window the next sequence of num_steps characters. In this way we can feed batches to the network and the cell states will continue through on each batch.
def get_batch(arrs, num_steps): batch_size, slice_size = arrs[0].shape n_batches = int(slice_size/num_steps) for b in range(n_batches): yield [x[:, b*num_steps: (b+1)*num_steps] for x in arrs] def build_rnn(num_classes, batch_size=50, num_steps=50, lstm_size=128, num_layers=2, learning_rate=0.001, grad_clip=5, sampling=False): if sampling == True: batch_size, num_steps = 1, 1 tf.reset_default_graph() # Declare placeholders we'll feed into the graph inputs = tf.placeholder(tf.int32, [batch_size, num_steps], name='inputs') x_one_hot = tf.one_hot(inputs, num_classes, name='x_one_hot') targets = tf.placeholder(tf.int32, [batch_size, num_steps], name='targets') y_one_hot = tf.one_hot(targets, num_classes, name='y_one_hot') y_reshaped = tf.reshape(y_one_hot, [-1, num_classes]) keep_prob = tf.placeholder(tf.float32, name='keep_prob') # Build the RNN layers lstm = tf.contrib.rnn.BasicLSTMCell(lstm_size) drop = tf.contrib.rnn.DropoutWrapper(lstm, output_keep_prob=keep_prob) cell = tf.contrib.rnn.MultiRNNCell([drop] * num_layers) initial_state = cell.zero_state(batch_size, tf.float32) # Run the data through the RNN layers outputs, state = tf.nn.dynamic_rnn(cell, x_one_hot, initial_state=initial_state) final_state = state # Reshape output so it's a bunch of rows, one row for each cell output seq_output = tf.concat(outputs, axis=1,name='seq_output') output = tf.reshape(seq_output, [-1, lstm_size], name='graph_output') # Now connect the RNN putputs to a softmax layer and calculate the cost softmax_w = tf.Variable(tf.truncated_normal((lstm_size, num_classes), stddev=0.1), name='softmax_w') softmax_b = tf.Variable(tf.zeros(num_classes), name='softmax_b') logits = tf.matmul(output, softmax_w) + softmax_b preds = tf.nn.softmax(logits, name='predictions') loss = tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=y_reshaped, name='loss') cost = tf.reduce_mean(loss, name='cost') # Optimizer for training, using gradient clipping to control exploding gradients tvars = tf.trainable_variables() grads, _ = tf.clip_by_global_norm(tf.gradients(cost, tvars), grad_clip) train_op = tf.train.AdamOptimizer(learning_rate) optimizer = train_op.apply_gradients(zip(grads, tvars)) # Export the nodes export_nodes = ['inputs', 'targets', 'initial_state', 'final_state', 'keep_prob', 'cost', 'preds', 'optimizer'] Graph = namedtuple('Graph', export_nodes) local_dict = locals() graph = Graph(*[local_dict[each] for each in export_nodes]) return graph
tensorboard/Anna_KaRNNa.ipynb
mdiaz236/DeepLearningFoundations
mit
Hyperparameters Here I'm defining the hyperparameters for the network. The two you probably haven't seen before are lstm_size and num_layers. These set the number of hidden units in the LSTM layers and the number of LSTM layers, respectively. Of course, making these bigger will improve the network's performance but you'll have to watch out for overfitting. If your validation loss is much larger than the training loss, you're probably overfitting. Decrease the size of the network or decrease the dropout keep probability.
batch_size = 100 num_steps = 100 lstm_size = 512 num_layers = 2 learning_rate = 0.001
tensorboard/Anna_KaRNNa.ipynb
mdiaz236/DeepLearningFoundations
mit
Write out the graph for TensorBoard
model = build_rnn(len(vocab), batch_size=batch_size, num_steps=num_steps, learning_rate=learning_rate, lstm_size=lstm_size, num_layers=num_layers) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) file_writer = tf.summary.FileWriter('./logs/1', sess.graph)
tensorboard/Anna_KaRNNa.ipynb
mdiaz236/DeepLearningFoundations
mit
Training Time for training which is is pretty straightforward. Here I pass in some data, and get an LSTM state back. Then I pass that state back in to the network so the next batch can continue the state from the previous batch. And every so often (set by save_every_n) I calculate the validation loss and save a checkpoint.
!mkdir -p checkpoints/anna epochs = 1 save_every_n = 200 train_x, train_y, val_x, val_y = split_data(chars, batch_size, num_steps) model = build_rnn(len(vocab), batch_size=batch_size, num_steps=num_steps, learning_rate=learning_rate, lstm_size=lstm_size, num_layers=num_layers) saver = tf.train.Saver(max_to_keep=100) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) # Use the line below to load a checkpoint and resume training #saver.restore(sess, 'checkpoints/anna20.ckpt') n_batches = int(train_x.shape[1]/num_steps) iterations = n_batches * epochs for e in range(epochs): # Train network new_state = sess.run(model.initial_state) loss = 0 for b, (x, y) in enumerate(get_batch([train_x, train_y], num_steps), 1): iteration = e*n_batches + b start = time.time() feed = {model.inputs: x, model.targets: y, model.keep_prob: 0.5, model.initial_state: new_state} batch_loss, new_state, _ = sess.run([model.cost, model.final_state, model.optimizer], feed_dict=feed) loss += batch_loss end = time.time() print('Epoch {}/{} '.format(e+1, epochs), 'Iteration {}/{}'.format(iteration, iterations), 'Training loss: {:.4f}'.format(loss/b), '{:.4f} sec/batch'.format((end-start))) if (iteration%save_every_n == 0) or (iteration == iterations): # Check performance, notice dropout has been set to 1 val_loss = [] new_state = sess.run(model.initial_state) for x, y in get_batch([val_x, val_y], num_steps): feed = {model.inputs: x, model.targets: y, model.keep_prob: 1., model.initial_state: new_state} batch_loss, new_state = sess.run([model.cost, model.final_state], feed_dict=feed) val_loss.append(batch_loss) print('Validation loss:', np.mean(val_loss), 'Saving checkpoint!') saver.save(sess, "checkpoints/anna/i{}_l{}_{:.3f}.ckpt".format(iteration, lstm_size, np.mean(val_loss))) tf.train.get_checkpoint_state('checkpoints/anna')
tensorboard/Anna_KaRNNa.ipynb
mdiaz236/DeepLearningFoundations
mit
Sampling Now that the network is trained, we'll can use it to generate new text. The idea is that we pass in a character, then the network will predict the next character. We can use the new one, to predict the next one. And we keep doing this to generate all new text. I also included some functionality to prime the network with some text by passing in a string and building up a state from that. The network gives us predictions for each character. To reduce noise and make things a little less random, I'm going to only choose a new character from the top N most likely characters.
def pick_top_n(preds, vocab_size, top_n=5): p = np.squeeze(preds) p[np.argsort(p)[:-top_n]] = 0 p = p / np.sum(p) c = np.random.choice(vocab_size, 1, p=p)[0] return c def sample(checkpoint, n_samples, lstm_size, vocab_size, prime="The "): prime = "Far" samples = [c for c in prime] model = build_rnn(vocab_size, lstm_size=lstm_size, sampling=True) saver = tf.train.Saver() with tf.Session() as sess: saver.restore(sess, checkpoint) new_state = sess.run(model.initial_state) for c in prime: x = np.zeros((1, 1)) x[0,0] = vocab_to_int[c] feed = {model.inputs: x, model.keep_prob: 1., model.initial_state: new_state} preds, new_state = sess.run([model.preds, model.final_state], feed_dict=feed) c = pick_top_n(preds, len(vocab)) samples.append(int_to_vocab[c]) for i in range(n_samples): x[0,0] = c feed = {model.inputs: x, model.keep_prob: 1., model.initial_state: new_state} preds, new_state = sess.run([model.preds, model.final_state], feed_dict=feed) c = pick_top_n(preds, len(vocab)) samples.append(int_to_vocab[c]) return ''.join(samples) checkpoint = "checkpoints/anna/i3560_l512_1.122.ckpt" samp = sample(checkpoint, 2000, lstm_size, len(vocab), prime="Far") print(samp) checkpoint = "checkpoints/anna/i200_l512_2.432.ckpt" samp = sample(checkpoint, 1000, lstm_size, len(vocab), prime="Far") print(samp) checkpoint = "checkpoints/anna/i600_l512_1.750.ckpt" samp = sample(checkpoint, 1000, lstm_size, len(vocab), prime="Far") print(samp) checkpoint = "checkpoints/anna/i1000_l512_1.484.ckpt" samp = sample(checkpoint, 1000, lstm_size, len(vocab), prime="Far") print(samp)
tensorboard/Anna_KaRNNa.ipynb
mdiaz236/DeepLearningFoundations
mit
int16 アクティベーションによるトレーニング後の整数量子化 <table class="tfo-notebook-buttons" align="left"> <td> <a target="_blank" href="https://www.tensorflow.org/lite/performance/post_training_integer_quant_16x8"><img src="https://www.tensorflow.org/images/tf_logo_32px.png">View on TensorFlow.org</a> </td> <td> <a target="_blank" href="https://colab.research.google.com/github/tensorflow/docs-l10n/blob/master/site/ja/lite/performance/post_training_integer_quant_16x8.ipynb"><img src="https://www.tensorflow.org/images/colab_logo_32px.png">Run in Google Colab</a> </td> <td> <a target="_blank" href="https://github.com/tensorflow/docs-l10n/blob/master/site/ja/lite/performance/post_training_integer_quant_16x8.ipynb"><img src="https://www.tensorflow.org/images/GitHub-Mark-32px.png">View source on GitHub</a> </td> <td><a href="https://storage.googleapis.com/tensorflow_docs/docs-l10n/site/ja/lite/performance/post_training_integer_quant_16x8.ipynb"><img src="https://www.tensorflow.org/images/download_logo_32px.png"> ノートブックをダウンロード</a></td> </table> 概要 現在、TensorFlow Lite はモデルを TensorFlow から TensorFlow Lite のフラットバッファ形式に変換する際に、アクティベーションを 16 ビット整数値に、重みを 8 ビット整数値に変換することをサポートしています。このモードは「16x8 量子化モード」と呼ばれています。このモードでは、アクティベーションが量子化の影響を受けやすい場合に、量子化モデルの精度を大幅に向上させ、モデルサイズを約 1/3〜1/4 に縮小することができます。また、この完全に量子化されたモデルは、整数のみのハードウェアアクセラレータで使用できます。 次のようなモデルでは、このモードのトレーニング後の量子化が有用です。 超解像 ノイズキャンセリングやビームフォーミングなどのオーディオ信号処理 画像ノイズ除去 単一の画像からの HDR 再構成 このチュートリアルでは、MNIST モデルを新規にトレーニングし、TensorFlow でその精度を確認してから、このモードを使用してモデルを Tensorflow Lite フラットバッファに変換します。最後に、変換されたモデルの精度を確認し、元の float32 モデルと比較します。この例は、このモードの使用法を示しており、TensorFlow Liteで利用可能な他の量子化手法と比較した場合の利点は示していません。 MNIST モデルの構築 セットアップ
import logging logging.getLogger("tensorflow").setLevel(logging.DEBUG) import tensorflow as tf from tensorflow import keras import numpy as np import pathlib
site/ja/lite/performance/post_training_integer_quant_16x8.ipynb
tensorflow/docs-l10n
apache-2.0
16x8 量子化モードが使用可能であることを確認します
tf.lite.OpsSet.EXPERIMENTAL_TFLITE_BUILTINS_ACTIVATIONS_INT16_WEIGHTS_INT8
site/ja/lite/performance/post_training_integer_quant_16x8.ipynb
tensorflow/docs-l10n
apache-2.0
モデルをトレーニングしてエクスポートする
# Load MNIST dataset mnist = keras.datasets.mnist (train_images, train_labels), (test_images, test_labels) = mnist.load_data() # Normalize the input image so that each pixel value is between 0 to 1. train_images = train_images / 255.0 test_images = test_images / 255.0 # Define the model architecture model = keras.Sequential([ keras.layers.InputLayer(input_shape=(28, 28)), keras.layers.Reshape(target_shape=(28, 28, 1)), keras.layers.Conv2D(filters=12, kernel_size=(3, 3), activation=tf.nn.relu), keras.layers.MaxPooling2D(pool_size=(2, 2)), keras.layers.Flatten(), keras.layers.Dense(10) ]) # Train the digit classification model model.compile(optimizer='adam', loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy']) model.fit( train_images, train_labels, epochs=1, validation_data=(test_images, test_labels) )
site/ja/lite/performance/post_training_integer_quant_16x8.ipynb
tensorflow/docs-l10n
apache-2.0
この例では、モデルを 1 エポックでトレーニングしたので、トレーニングの精度は 96% 以下になります。 TensorFlow Lite モデルに変換する Python TFLiteConverter を使用して、トレーニング済みモデルを TensorFlow Lite モデルに変換できるようになりました。 次に、TFliteConverterを使用してモデルをデフォルトの float32 形式に変換します。
converter = tf.lite.TFLiteConverter.from_keras_model(model) tflite_model = converter.convert()
site/ja/lite/performance/post_training_integer_quant_16x8.ipynb
tensorflow/docs-l10n
apache-2.0
.tfliteファイルに書き込みます。
tflite_models_dir = pathlib.Path("/tmp/mnist_tflite_models/") tflite_models_dir.mkdir(exist_ok=True, parents=True) tflite_model_file = tflite_models_dir/"mnist_model.tflite" tflite_model_file.write_bytes(tflite_model)
site/ja/lite/performance/post_training_integer_quant_16x8.ipynb
tensorflow/docs-l10n
apache-2.0
モデルを 16x8 量子化モードに量子化するには、最初にoptimizationsフラグを設定してデフォルトの最適化を使用します。次に、16x8 量子化モードがターゲット仕様でサポートされる必要な演算であることを指定します。
converter.optimizations = [tf.lite.Optimize.DEFAULT] converter.target_spec.supported_ops = [tf.lite.OpsSet.EXPERIMENTAL_TFLITE_BUILTINS_ACTIVATIONS_INT16_WEIGHTS_INT8]
site/ja/lite/performance/post_training_integer_quant_16x8.ipynb
tensorflow/docs-l10n
apache-2.0
int8 トレーニング後の量子化の場合と同様に、コンバーターオプションinference_input(output)_typeを tf.int16 に設定することで、完全整数量子化モデルを生成できます。 キャリブレーションデータを設定します。
mnist_train, _ = tf.keras.datasets.mnist.load_data() images = tf.cast(mnist_train[0], tf.float32) / 255.0 mnist_ds = tf.data.Dataset.from_tensor_slices((images)).batch(1) def representative_data_gen(): for input_value in mnist_ds.take(100): # Model has only one input so each data point has one element. yield [input_value] converter.representative_dataset = representative_data_gen
site/ja/lite/performance/post_training_integer_quant_16x8.ipynb
tensorflow/docs-l10n
apache-2.0
最後に、通常どおりにモデルを変換します。デフォルトでは、変換されたモデルは呼び出しの便宜上、浮動小数点の入力と出力を引き続き使用します。
tflite_16x8_model = converter.convert() tflite_model_16x8_file = tflite_models_dir/"mnist_model_quant_16x8.tflite" tflite_model_16x8_file.write_bytes(tflite_16x8_model)
site/ja/lite/performance/post_training_integer_quant_16x8.ipynb
tensorflow/docs-l10n
apache-2.0
生成されるファイルのサイズが約1/3であることに注目してください。
!ls -lh {tflite_models_dir}
site/ja/lite/performance/post_training_integer_quant_16x8.ipynb
tensorflow/docs-l10n
apache-2.0
TensorFlow Lite モデルを実行する Python TensorFlow Lite インタープリタを使用して TensorFlow Lite モデルを実行します。 モデルをインタープリタに読み込む
interpreter = tf.lite.Interpreter(model_path=str(tflite_model_file)) interpreter.allocate_tensors() interpreter_16x8 = tf.lite.Interpreter(model_path=str(tflite_model_16x8_file)) interpreter_16x8.allocate_tensors()
site/ja/lite/performance/post_training_integer_quant_16x8.ipynb
tensorflow/docs-l10n
apache-2.0
1 つの画像でモデルをテストする
test_image = np.expand_dims(test_images[0], axis=0).astype(np.float32) input_index = interpreter.get_input_details()[0]["index"] output_index = interpreter.get_output_details()[0]["index"] interpreter.set_tensor(input_index, test_image) interpreter.invoke() predictions = interpreter.get_tensor(output_index) import matplotlib.pylab as plt plt.imshow(test_images[0]) template = "True:{true}, predicted:{predict}" _ = plt.title(template.format(true= str(test_labels[0]), predict=str(np.argmax(predictions[0])))) plt.grid(False) test_image = np.expand_dims(test_images[0], axis=0).astype(np.float32) input_index = interpreter_16x8.get_input_details()[0]["index"] output_index = interpreter_16x8.get_output_details()[0]["index"] interpreter_16x8.set_tensor(input_index, test_image) interpreter_16x8.invoke() predictions = interpreter_16x8.get_tensor(output_index) plt.imshow(test_images[0]) template = "True:{true}, predicted:{predict}" _ = plt.title(template.format(true= str(test_labels[0]), predict=str(np.argmax(predictions[0])))) plt.grid(False)
site/ja/lite/performance/post_training_integer_quant_16x8.ipynb
tensorflow/docs-l10n
apache-2.0
モデルを評価する
# A helper function to evaluate the TF Lite model using "test" dataset. def evaluate_model(interpreter): input_index = interpreter.get_input_details()[0]["index"] output_index = interpreter.get_output_details()[0]["index"] # Run predictions on every image in the "test" dataset. prediction_digits = [] for test_image in test_images: # Pre-processing: add batch dimension and convert to float32 to match with # the model's input data format. test_image = np.expand_dims(test_image, axis=0).astype(np.float32) interpreter.set_tensor(input_index, test_image) # Run inference. interpreter.invoke() # Post-processing: remove batch dimension and find the digit with highest # probability. output = interpreter.tensor(output_index) digit = np.argmax(output()[0]) prediction_digits.append(digit) # Compare prediction results with ground truth labels to calculate accuracy. accurate_count = 0 for index in range(len(prediction_digits)): if prediction_digits[index] == test_labels[index]: accurate_count += 1 accuracy = accurate_count * 1.0 / len(prediction_digits) return accuracy print(evaluate_model(interpreter))
site/ja/lite/performance/post_training_integer_quant_16x8.ipynb
tensorflow/docs-l10n
apache-2.0
16x8 量子化モデルで評価を繰り返します。
# NOTE: This quantization mode is an experimental post-training mode, # it does not have any optimized kernels implementations or # specialized machine learning hardware accelerators. Therefore, # it could be slower than the float interpreter. print(evaluate_model(interpreter_16x8))
site/ja/lite/performance/post_training_integer_quant_16x8.ipynb
tensorflow/docs-l10n
apache-2.0
Vertex SDK: Train & deploy a TensorFlow model with hosted runtimes (aka pre-built containers) Installation Install the latest (preview) version of Vertex SDK.
! pip3 install -U google-cloud-aiplatform --user
notebooks/community/migration/UJ2,12 Custom Training Prebuilt Container TF Keras.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"): # Automatically restart kernel after installs import IPython app = IPython.Application.instance() app.kernel.do_shutdown(True)
notebooks/community/migration/UJ2,12 Custom Training Prebuilt Container TF Keras.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Before you begin GPU run-time Make sure you're running this notebook in a GPU runtime if you have that option. In Colab, select Runtime > Change Runtime Type > GPU Set up your GCP project The following steps are required, regardless of your notebook environment. Select or create a GCP project. When you first create an account, you get a $300 free credit towards your compute/storage costs. Make sure that billing is enabled for your project. Enable the Vertex APIs and Compute Engine APIs. Google Cloud SDK is already installed in Google Cloud Notebooks. Enter your project ID in the cell below. Then run the cell to make sure the Cloud SDK uses the right project for all the commands in this notebook. Note: Jupyter runs lines prefixed with ! as shell commands, and it interpolates Python variables prefixed with $ into these commands.
PROJECT_ID = "[your-project-id]" # @param {type:"string"} if PROJECT_ID == "" or PROJECT_ID is None or PROJECT_ID == "[your-project-id]": # Get your GCP project id from gcloud shell_output = !gcloud config list --format 'value(core.project)' 2>/dev/null PROJECT_ID = shell_output[0] print("Project ID:", PROJECT_ID) ! gcloud config set project $PROJECT_ID
notebooks/community/migration/UJ2,12 Custom Training Prebuilt Container TF Keras.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Region You can also change the REGION variable, which is used for operations throughout the rest of this notebook. Below are regions supported for Vertex AI. We recommend when possible, to choose the region closest to you. Americas: us-central1 Europe: europe-west4 Asia Pacific: asia-east1 You cannot use a Multi-Regional Storage bucket for training with Vertex. Not all regions provide support for all Vertex services. For the latest support per region, see Region support for Vertex AI services
REGION = "us-central1" # @param {type: "string"}
notebooks/community/migration/UJ2,12 Custom Training Prebuilt Container TF Keras.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Authenticate your GCP account If you are using Google Cloud Notebooks, your environment is already authenticated. Skip this step. Note: If you are on an Vertex notebook and run the cell, the cell knows to skip executing the authentication steps.
import os import sys # If you are running this notebook in Colab, run this cell and follow the # instructions to authenticate your Google Cloud account. This provides access # to your Cloud Storage bucket and lets you submit training jobs and prediction # requests. # If on Vertex, then don't execute this code if not os.path.exists("/opt/deeplearning/metadata/env_version"): if "google.colab" in sys.modules: from google.colab import auth as google_auth google_auth.authenticate_user() # If you are running this tutorial in a notebook locally, replace the string # below with the path to your service account key and run this cell to # authenticate your Google Cloud account. else: %env GOOGLE_APPLICATION_CREDENTIALS your_path_to_credentials.json # Log in to your account on Google Cloud ! gcloud auth login
notebooks/community/migration/UJ2,12 Custom Training Prebuilt Container TF Keras.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Set up variables Next, set up some variables used throughout the tutorial. Import libraries and define constants Import Vertex SDK Import the Vertex SDK into our Python environment.
import time from google.cloud.aiplatform import gapic as aip from google.protobuf import json_format from google.protobuf.json_format import MessageToJson, ParseDict from google.protobuf.struct_pb2 import Value
notebooks/community/migration/UJ2,12 Custom Training Prebuilt Container TF Keras.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Vertex AI constants Setup up the following constants for Vertex AI: API_ENDPOINT: The Vertex AI API service endpoint for dataset, model, job, pipeline and endpoint services. API_PREDICT_ENDPOINT: The Vertex AI API service endpoint for prediction. PARENT: The Vertex AI location root path for dataset, model and endpoint resources.
# API Endpoint API_ENDPOINT = "{}-aiplatform.googleapis.com".format(REGION) # Vertex AI location root path for your dataset, model and endpoint resources PARENT = "projects/" + PROJECT_ID + "/locations/" + REGION
notebooks/community/migration/UJ2,12 Custom Training Prebuilt Container TF Keras.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 managed models. Pipeline Service for training. Endpoint Service for deployment. Job Service for batch jobs and custom training. Prediction Service for serving. Note: Prediction has a different service endpoint.
# client options same for all services client_options = {"api_endpoint": API_ENDPOINT} def create_model_client(): client = aip.ModelServiceClient(client_options=client_options) return client def create_endpoint_client(): client = aip.EndpointServiceClient(client_options=client_options) return client def create_prediction_client(): client = aip.PredictionServiceClient(client_options=client_options) return client def create_job_client(): client = aip.JobServiceClient(client_options=client_options) return client clients = {} clients["model"] = create_model_client() clients["endpoint"] = create_endpoint_client() clients["prediction"] = create_prediction_client() clients["job"] = create_job_client() for client in clients.items(): print(client)
notebooks/community/migration/UJ2,12 Custom Training Prebuilt Container TF Keras.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Prepare a trainer script Package assembly
! rm -rf cifar ! mkdir cifar ! touch cifar/README.md setup_cfg = "[egg_info]\n\ tag_build =\n\ tag_date = 0" ! echo "$setup_cfg" > cifar/setup.cfg setup_py = "import setuptools\n\ # Requires TensorFlow Datasets\n\ setuptools.setup(\n\ install_requires=[\n\ 'tensorflow_datasets==1.3.0',\n\ ],\n\ packages=setuptools.find_packages())" ! echo "$setup_py" > cifar/setup.py pkg_info = "Metadata-Version: 1.0\n\ Name: Custom Training CIFAR-10\n\ Version: 0.0.0\n\ Summary: Demonstration training script\n\ Home-page: www.google.com\n\ Author: Google\n\ Author-email: [email protected]\n\ License: Public\n\ Description: Demo\n\ Platform: Vertex AI" ! echo "$pkg_info" > cifar/PKG-INFO ! mkdir cifar/trainer ! touch cifar/trainer/__init__.py
notebooks/community/migration/UJ2,12 Custom Training Prebuilt Container TF Keras.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Task.py contents
%%writefile cifar/trainer/task.py import tensorflow_datasets as tfds import tensorflow as tf from tensorflow.python.client import device_lib import argparse import os import sys tfds.disable_progress_bar() parser = argparse.ArgumentParser() parser.add_argument('--model-dir', dest='model_dir', default='/tmp/saved_model', type=str, help='Model dir.') parser.add_argument('--lr', dest='lr', default=0.01, type=float, help='Learning rate.') parser.add_argument('--epochs', dest='epochs', default=10, type=int, help='Number of epochs.') parser.add_argument('--steps', dest='steps', default=200, type=int, help='Number of steps per epoch.') parser.add_argument('--distribute', dest='distribute', type=str, default='single', help='distributed training strategy') args = parser.parse_args() print('Python Version = {}'.format(sys.version)) print('TensorFlow Version = {}'.format(tf.__version__)) print('TF_CONFIG = {}'.format(os.environ.get('TF_CONFIG', 'Not found'))) print('DEVICES', device_lib.list_local_devices()) if args.distribute == 'single': if tf.test.is_gpu_available(): strategy = tf.distribute.OneDeviceStrategy(device="/gpu:0") else: strategy = tf.distribute.OneDeviceStrategy(device="/cpu:0") elif args.distribute == 'mirror': strategy = tf.distribute.MirroredStrategy() elif args.distribute == 'multi': strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy() print('num_replicas_in_sync = {}'.format(strategy.num_replicas_in_sync)) BUFFER_SIZE = 10000 BATCH_SIZE = 64 def make_datasets_unbatched(): def scale(image, label): image = tf.cast(image, tf.float32) image /= 255.0 return image, label datasets, info = tfds.load(name='cifar10', with_info=True, as_supervised=True) return datasets['train'].map(scale).cache().shuffle(BUFFER_SIZE).repeat() def build_and_compile_cnn_model(): model = tf.keras.Sequential([ tf.keras.layers.Conv2D(32, 3, activation='relu', input_shape=(32, 32, 3)), tf.keras.layers.MaxPooling2D(), tf.keras.layers.Conv2D(32, 3, activation='relu'), tf.keras.layers.MaxPooling2D(), tf.keras.layers.Flatten(), tf.keras.layers.Dense(10, activation='softmax') ]) model.compile( loss=tf.keras.losses.sparse_categorical_crossentropy, optimizer=tf.keras.optimizers.SGD(learning_rate=args.lr), metrics=['accuracy']) return model NUM_WORKERS = strategy.num_replicas_in_sync GLOBAL_BATCH_SIZE = BATCH_SIZE * NUM_WORKERS train_dataset = make_datasets_unbatched().batch(GLOBAL_BATCH_SIZE) with strategy.scope(): model = build_and_compile_cnn_model() model.fit(x=train_dataset, epochs=args.epochs, steps_per_epoch=args.steps) model.save(args.model_dir)
notebooks/community/migration/UJ2,12 Custom Training Prebuilt Container TF Keras.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Store training script on your Cloud Storage bucket
! rm -f cifar.tar cifar.tar.gz ! tar cvf cifar.tar cifar ! gzip cifar.tar ! gsutil cp cifar.tar.gz gs://$BUCKET_NAME/trainer_cifar.tar.gz
notebooks/community/migration/UJ2,12 Custom Training Prebuilt Container TF Keras.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Train a model projects.locations.customJobs.create Request
JOB_NAME = "custom_job_TF_" + TIMESTAMP TRAIN_IMAGE = "gcr.io/cloud-aiplatform/training/tf-gpu.2-1:latest" TRAIN_NGPU = 1 TRAIN_GPU = aip.AcceleratorType.NVIDIA_TESLA_K80 worker_pool_specs = [ { "replica_count": 1, "machine_spec": { "machine_type": "n1-standard-4", "accelerator_type": TRAIN_GPU, "accelerator_count": TRAIN_NGPU, }, "python_package_spec": { "executor_image_uri": TRAIN_IMAGE, "package_uris": ["gs://" + BUCKET_NAME + "/trainer_cifar.tar.gz"], "python_module": "trainer.task", "args": [ "--model-dir=" + "gs://{}/{}".format(BUCKET_NAME, JOB_NAME), "--epochs=" + str(20), "--steps=" + str(100), "--distribute=" + "single", ], }, } ] training_job = { "display_name": JOB_NAME, "job_spec": {"worker_pool_specs": worker_pool_specs}, } print( MessageToJson( aip.CreateCustomJobRequest(parent=PARENT, custom_job=training_job).__dict__[ "_pb" ] ) )
notebooks/community/migration/UJ2,12 Custom Training Prebuilt Container TF Keras.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Example output: { "parent": "projects/migration-ucaip-training/locations/us-central1", "customJob": { "displayName": "custom_job_TF_20210227173057", "jobSpec": { "workerPoolSpecs": [ { "machineSpec": { "machineType": "n1-standard-4", "acceleratorType": "NVIDIA_TESLA_K80", "acceleratorCount": 1 }, "replicaCount": "1", "pythonPackageSpec": { "executorImageUri": "gcr.io/cloud-aiplatform/training/tf-gpu.2-1:latest", "packageUris": [ "gs://migration-ucaip-trainingaip-20210227173057/trainer_cifar.tar.gz" ], "pythonModule": "trainer.task", "args": [ "--model-dir=gs://migration-ucaip-trainingaip-20210227173057/custom_job_TF_20210227173057", "--epochs=20", "--steps=100", "--distribute=single" ] } } ] } } } Call
request = clients["job"].create_custom_job(parent=PARENT, custom_job=training_job)
notebooks/community/migration/UJ2,12 Custom Training Prebuilt Container TF Keras.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Example output: { "name": "projects/116273516712/locations/us-central1/customJobs/2970106362064797696", "displayName": "custom_job_TF_20210227173057", "jobSpec": { "workerPoolSpecs": [ { "machineSpec": { "machineType": "n1-standard-4", "acceleratorType": "NVIDIA_TESLA_K80", "acceleratorCount": 1 }, "replicaCount": "1", "diskSpec": { "bootDiskType": "pd-ssd", "bootDiskSizeGb": 100 }, "pythonPackageSpec": { "executorImageUri": "gcr.io/cloud-aiplatform/training/tf-gpu.2-1:latest", "packageUris": [ "gs://migration-ucaip-trainingaip-20210227173057/trainer_cifar.tar.gz" ], "pythonModule": "trainer.task", "args": [ "--model-dir=gs://migration-ucaip-trainingaip-20210227173057/custom_job_TF_20210227173057", "--epochs=20", "--steps=100", "--distribute=single" ] } } ] }, "state": "JOB_STATE_PENDING", "createTime": "2021-02-27T17:31:04.494716Z", "updateTime": "2021-02-27T17:31:04.494716Z" }
# The full unique ID for the custom training job custom_training_id = request.name # The short numeric ID for the custom training job custom_training_short_id = custom_training_id.split("/")[-1] print(custom_training_id)
notebooks/community/migration/UJ2,12 Custom Training Prebuilt Container TF Keras.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
projects.locations.customJobs.get Call
request = clients["job"].get_custom_job(name=custom_training_id)
notebooks/community/migration/UJ2,12 Custom Training Prebuilt Container TF Keras.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Example output: { "name": "projects/116273516712/locations/us-central1/customJobs/2970106362064797696", "displayName": "custom_job_TF_20210227173057", "jobSpec": { "workerPoolSpecs": [ { "machineSpec": { "machineType": "n1-standard-4", "acceleratorType": "NVIDIA_TESLA_K80", "acceleratorCount": 1 }, "replicaCount": "1", "diskSpec": { "bootDiskType": "pd-ssd", "bootDiskSizeGb": 100 }, "pythonPackageSpec": { "executorImageUri": "gcr.io/cloud-aiplatform/training/tf-gpu.2-1:latest", "packageUris": [ "gs://migration-ucaip-trainingaip-20210227173057/trainer_cifar.tar.gz" ], "pythonModule": "trainer.task", "args": [ "--model-dir=gs://migration-ucaip-trainingaip-20210227173057/custom_job_TF_20210227173057", "--epochs=20", "--steps=100", "--distribute=single" ] } } ] }, "state": "JOB_STATE_PENDING", "createTime": "2021-02-27T17:31:04.494716Z", "updateTime": "2021-02-27T17:31:04.494716Z" }
while True: response = clients["job"].get_custom_job(name=custom_training_id) if response.state != aip.PipelineState.PIPELINE_STATE_SUCCEEDED: print("Training job has not completed:", response.state) if response.state == aip.PipelineState.PIPELINE_STATE_FAILED: break else: print("Training Time:", response.end_time - response.start_time) break time.sleep(20) # model artifact output directory on Google Cloud Storage model_artifact_dir = ( response.job_spec.worker_pool_specs[0].python_package_spec.args[0].split("=")[-1] ) print("artifact location " + model_artifact_dir)
notebooks/community/migration/UJ2,12 Custom Training Prebuilt Container TF Keras.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Deploy the model Load the saved model
import tensorflow as tf model = tf.keras.models.load_model(model_artifact_dir)
notebooks/community/migration/UJ2,12 Custom Training Prebuilt Container TF Keras.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Serving function for image data
CONCRETE_INPUT = "numpy_inputs" def _preprocess(bytes_input): decoded = tf.io.decode_jpeg(bytes_input, channels=3) decoded = tf.image.convert_image_dtype(decoded, tf.float32) resized = tf.image.resize(decoded, size=(32, 32)) rescale = tf.cast(resized / 255.0, tf.float32) return rescale @tf.function(input_signature=[tf.TensorSpec([None], tf.string)]) def preprocess_fn(bytes_inputs): decoded_images = tf.map_fn( _preprocess, bytes_inputs, dtype=tf.float32, back_prop=False ) return { CONCRETE_INPUT: decoded_images } # User needs to make sure the key matches model's input m_call = tf.function(model.call).get_concrete_function( [tf.TensorSpec(shape=[None, 32, 32, 3], dtype=tf.float32, name=CONCRETE_INPUT)] ) @tf.function(input_signature=[tf.TensorSpec([None], tf.string)]) def serving_fn(bytes_inputs): images = preprocess_fn(bytes_inputs) prob = m_call(**images) return prob tf.saved_model.save( model, model_artifact_dir, signatures={ "serving_default": serving_fn, }, )
notebooks/community/migration/UJ2,12 Custom Training Prebuilt Container TF Keras.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Get the serving function signature
loaded = tf.saved_model.load(model_artifact_dir) input_name = list( loaded.signatures["serving_default"].structured_input_signature[1].keys() )[0] print("Serving function input:", input_name)
notebooks/community/migration/UJ2,12 Custom Training Prebuilt Container TF Keras.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0