markdown
stringlengths
0
37k
code
stringlengths
1
33.3k
path
stringlengths
8
215
repo_name
stringlengths
6
77
license
stringclasses
15 values
The simulator and the region_model It is important to note that the simulator provides a wrapping of underlying API functionality. It is designed to provide a quick and simple interface for conducting runs based on a configuration saved in a .yaml file, or otherwise. Core functionality is contained in the region_model ...
#simulator. #try tab completion n_cells = simulator.region_model.size() print(n_cells)
notebooks/nea-example/simulation-configured.ipynb
statkraft/shyft-doc
lgpl-3.0
3. Running a SHyFT simulation Okay, so thus far we have set up our cfg object which contains most the information required to run the simulation. We can simply run the simulation using the run method.
simulator.run()
notebooks/nea-example/simulation-configured.ipynb
statkraft/shyft-doc
lgpl-3.0
But this is may be too simple. Let's explore the simulator.run method a bit further:
help(simulator.run)
notebooks/nea-example/simulation-configured.ipynb
statkraft/shyft-doc
lgpl-3.0
Note that you can pass two parameters to run. To run a simulation, we need a time_axis (length of the simulation), and an initial state. Initially we got both of these from the cfg object (which takes it from the .yaml files). However, in some cases you will likely want to change these and conduct simulations for diffe...
# Here we are going to extact data from the simulator object. # let's work directly with the `region_model` region_model = simulator.region_model print(region_model.catchment_ids)
notebooks/nea-example/simulation-configured.ipynb
statkraft/shyft-doc
lgpl-3.0
We see here that each sub-catchment in our simulation is associated with a unique ID. These are user defined IDs. In the case of the nea-nidelva simulation, they are taken from the GIS database used to create the example configuration files. To get data out of the region_model you need to specify which catchments you a...
q_1228_ts = simulator.region_model.statistics.discharge([1228]) q_1228_np = simulator.region_model.statistics.discharge([1228]).values print(type(q_1228_ts)) print(type(q_1228_np))
notebooks/nea-example/simulation-configured.ipynb
statkraft/shyft-doc
lgpl-3.0
Look at the discharge timeseries As mentioned above, Shyft has it's own Timeseries class. This class is quite powerful, and the api-timeseries notebook shows more of the functionality. For now, let's look at some key aspects, and how to create a quick plot of the individual catchment discharge.
# We can make a quick plot of the data of each sub-catchment fig, ax = plt.subplots(figsize=(20,15)) # plot each catchment discharge in the catchment_ids for i,cid in enumerate(region_model.catchment_ids): # a ts.time_axis can be enumerated to it's UtcPeriod, # that will have a .start and .end of type utctime...
notebooks/nea-example/simulation-configured.ipynb
statkraft/shyft-doc
lgpl-3.0
Visualizing the distributed catchment data An important, but difficult concept, to remember when working with Shyft, is that internally there is no 'grid' to speak of. The simulation is vectorized, and each 'cell' represents a spatial area with it's own area and geolocation information. Therefore, we cannot just load a...
cells = region_model.get_cells() # Once we have the cells, we can get their coordinate information # and fetch the x- and y-location of the cells x = np.array([cell.geo.mid_point().x for cell in cells]) y = np.array([cell.geo.mid_point().y for cell in cells])
notebooks/nea-example/simulation-configured.ipynb
statkraft/shyft-doc
lgpl-3.0
We also will need to get a 'z' value to make things interesting. Since this is the first time we've visualized our catchment, let's make a map of the sub-catchments. To do this, the first thing we need to do is get the membership of each cell. That is, to which catchment does it below. We do this by extracting the catc...
# let's create the mapping of catchment_id to an integer: catchment_ids = region_model.catchment_ids cid_z_map = dict([ (catchment_ids[i],i) for i in range(len(catchment_ids))]) # then create an array the same length as our 'x' and 'y', which holds the # integer value that we'll use for the 'z' value catch_ids = np.ar...
notebooks/nea-example/simulation-configured.ipynb
statkraft/shyft-doc
lgpl-3.0
Visualing the Snow Cover Area of all cells for a certain point in time Here we'll do some more work to look at a snapshot value of data in each of the cells. This example is collecting the response variable (here the Snow Cover Area (SCA)) for each of the cells for a certain point of time. The "response collector" is a...
#first, set a date: year, month, day, (hour of day if hourly time step) oslo = api.Calendar('Europe/Oslo') # specifying input calendar in Oslo tz-id time_x = oslo.time(2014,5,15) # the oslo calendar(incl dst) converts calendar coordinates Y,M,D.. to its utc-time # we need to get the index of the time_axis for the tim...
notebooks/nea-example/simulation-configured.ipynb
statkraft/shyft-doc
lgpl-3.0
Let's take a closer look at this... simulator.region_model.time_axis.index_of(time_x) Simply provided an index value that we can use to index the cells for the time we're interested in looking at. Next we use: simulator.region_model.gamma_snow_response What is this? This is a collector from the simulation. In this c...
# for attr in dir(simulator.region_model): # if attr[0] is not '_': #ignore privates # print(attr) # # and don't forget: # help(simulator.region_model.gamma_snow_state)
notebooks/nea-example/simulation-configured.ipynb
statkraft/shyft-doc
lgpl-3.0
We are now ready to explore some of the variables from the simulation. We'll continue on with SCA.
# We can make a simple scatter plot again for quick visualization fig, ax = plt.subplots(figsize=(15,5)) cm = plt.cm.get_cmap('winter') plot = ax.scatter(x, y, c=sca, vmin=0, vmax=1, marker='s', s=40, lw=0, cmap=cm) plt.colorbar(plot) plt.title('Snow Covered area...
notebooks/nea-example/simulation-configured.ipynb
statkraft/shyft-doc
lgpl-3.0
A note about the geometry of the region Again, keep in mind that while we have created a variable that contains the values for sca in each cell, this is only an iterable object. The only reason we know where each value is located is because we have corresponding x and y values for each cell. It is not an array. We can ...
# look at the catchment-wide average: nea_avg_sca = np.average(sca) print("Average SCA for Nea Nidelva: {0}".format(nea_avg_sca)) # And let's compute histogram of the snow covered area as well fig, ax = plt.subplots() ax.hist(sca, bins=20, range=(0,1), color='y', alpha=0.5) ax.set_xlabel("SCA of grid cell") ax.set_yla...
notebooks/nea-example/simulation-configured.ipynb
statkraft/shyft-doc
lgpl-3.0
Before we can start training the model, we need to create a dictionary with all preprocessing settings and poimt to the yaml file corresponding to the model: cifar10.yaml.
run_settings = { "model type":"pylearn2", "yaml file": "cifar10.yaml", "preprocessing":{"resize":[48,48]}, "final_shape":[48,48], "augmentation_factor":1, "train_split": 0.8 }
notebooks/tutorials/Training a Maxout CIFAR10-based model.ipynb
Neuroglycerin/neukrill-net-work
mit
To set up the path for settings, utils and os must be imported.
import neukrill_net.utils import os reload(neukrill_net.utils) cd .. run_settings["run_settings_path"] = os.path.abspath("run_settings/cifar10_based.json") run_settings
notebooks/tutorials/Training a Maxout CIFAR10-based model.ipynb
Neuroglycerin/neukrill-net-work
mit
Now the settings can be saved.
neukrill_net.utils.save_run_settings(run_settings) !cat run_settings/cifar10_based.json
notebooks/tutorials/Training a Maxout CIFAR10-based model.ipynb
Neuroglycerin/neukrill-net-work
mit
Now we can start training the model with:
python train.py run_settings/cifar10_based.json
notebooks/tutorials/Training a Maxout CIFAR10-based model.ipynb
Neuroglycerin/neukrill-net-work
mit
After trying to run the model, it broke with an error that partialSum does not divide numModules. Turns out that partialSum is a parameter of a convolutional layer that affects the performance of the weight gradient computation and it has to divide the area of the output grid in this layer, which is given by numModules...
!obj:pylearn2.train.Train { dataset: &train !obj:neukrill_net.dense_dataset.DensePNGDataset { settings_path: %(settings_path)s, run_settings: %(run_settings_path)s, training_set_mode: "train" }, model: !obj:pylearn2.models.mlp.MLP { batch_size: &batch_size 128, ...
notebooks/tutorials/Training a Maxout CIFAR10-based model.ipynb
Neuroglycerin/neukrill-net-work
mit
Regression as sum-of-squares decomposition Example data sets We setup two synthetic data sets -- one where $Y$ is independent of $X$, and a second where $Y$ is depedendent on $X$.
n = 25 x = np.linspace(-5, 5, n) + stats.norm.rvs(loc=0, scale=1, size=n) a, b = 1, 0.75 # I've chosen values to make yind and ydep have about the same variance yind = a + stats.norm.rvs(loc=0, scale=np.sqrt(8), size=n) ydep = a + b*x + stats.norm.rvs(loc=0, scale=1, size=n) # create two different data frames for e...
2016-04-25-Parallels-Regression-and-ANOVA.ipynb
Bio204-class/bio204-notebooks
cc0-1.0
And we plot the data sets
fig, (ax1, ax2) = plt.subplots(1,2, figsize=(10,4), sharex=True, sharey=True) ax1.scatter(x, yind, s=60, alpha=0.75, color='steelblue') ax2.scatter(x, ydep, s=60, alpha=0.75, color='steelblue') ax1.set_xlabel("X",fontsize=15) ax1.set_ylabel("Y",fontsize=15) ax1.set_title("Y independent of X", fontsize=18) ax2.set_xla...
2016-04-25-Parallels-Regression-and-ANOVA.ipynb
Bio204-class/bio204-notebooks
cc0-1.0
Fit the regressions with statsmodels
fit_ind = smf.ols('y ~ x', data_ind).fit() fit_dep = smf.ols('y ~ x', data_dep).fit()
2016-04-25-Parallels-Regression-and-ANOVA.ipynb
Bio204-class/bio204-notebooks
cc0-1.0
Plot the regressions using info return by statsmodels
fig, (ax1, ax2) = plt.subplots(1,2, figsize=(10,4), sharex=True, sharey=True) ax1.scatter(x, yind, s=60, alpha=0.75, color='steelblue') ax1.plot(x, fit_ind.predict(), color='firebrick', alpha=0.5) ax2.scatter(x, ydep, s=60, alpha=0.75, color='steelblue') ax2.plot(x, fit_dep.predict(), color='firebrick', alpha=0.5) a...
2016-04-25-Parallels-Regression-and-ANOVA.ipynb
Bio204-class/bio204-notebooks
cc0-1.0
Functions to decompose sums of squares
def sum_squares(x): x = np.asarray(x) return np.sum((x - np.mean(x))**2) def bivariate_regression_table(fit): """ A function to create an ANOVA-like table for a bivariate regression""" df_model = fit.df_model df_resid = fit.df_resid df_total = df_model + df_resid SStotal = sum_squares(fit...
2016-04-25-Parallels-Regression-and-ANOVA.ipynb
Bio204-class/bio204-notebooks
cc0-1.0
ANOVA like tables for each regression
Ftable_ind = bivariate_regression_table(fit_ind) Ftable_ind Ftable_dep = bivariate_regression_table(fit_dep) Ftable_dep
2016-04-25-Parallels-Regression-and-ANOVA.ipynb
Bio204-class/bio204-notebooks
cc0-1.0
Two-group one-way ANOVA as a bivariate regression To setup ANOVA for two-groups as a regression problem, we use "dummy coding" where we incorporate group information into a predictor variable.
Y1 = stats.norm.rvs(loc=0, scale=1, size=10) Y2 = stats.norm.rvs(loc=1, scale=1, size=10) Y = np.concatenate([Y1,Y2]) groups = [-1]*10 + [1]*10 # setup dummy variable to represent grouping data = pd.DataFrame(dict(Y = Y, group = groups)) data.head(3) data.tail(3) data.corr() sbn.stripplot(x...
2016-04-25-Parallels-Regression-and-ANOVA.ipynb
Bio204-class/bio204-notebooks
cc0-1.0
Fit regression model
fit_data = smf.ols('Y ~ group', data).fit()
2016-04-25-Parallels-Regression-and-ANOVA.ipynb
Bio204-class/bio204-notebooks
cc0-1.0
Plot regression
plt.scatter(data.group[data.group == -1], data.Y[data.group == -1], s=60, alpha=0.75, color='steelblue') plt.scatter(data.group[data.group == 1], data.Y[data.group == 1], s=60, alpha=0.75, color='forestgreen') groups = [-1,1] predicted = fit_data.predict(dict(group=groups)) plt.plot(groups, predicted, color='firebrick'...
2016-04-25-Parallels-Regression-and-ANOVA.ipynb
Bio204-class/bio204-notebooks
cc0-1.0
Compare regression F-statistic and corresponding p-value to that from ANOVA
fit_data.fvalue, fit_data.f_pvalue stats.f_oneway(data.Y[data.group == -1], data.Y[data.group == 1])
2016-04-25-Parallels-Regression-and-ANOVA.ipynb
Bio204-class/bio204-notebooks
cc0-1.0
Multi-group one-way ANOVA as a multiple regression When we want to consider multiple groups, we have to extend the idea of dummy coding to allow for more groups. We can setup simple dummy variables for $g-1$ groups, or we can use a slight variant called "effect coding". The results when using effect coding are usually...
iris = pd.read_csv("http://roybatty.org/iris.csv") iris.Species.unique() iris.columns = iris.columns.str.replace('.','') iris.columns sbn.violinplot(x="Species", y="SepalLength", data=iris) effect1 = [] effect2 = [] for s in iris.Species: if s == 'setosa': effect1.append(1) effect2.append(0) ...
2016-04-25-Parallels-Regression-and-ANOVA.ipynb
Bio204-class/bio204-notebooks
cc0-1.0
If using statsmodels you don't need to explicit create the effect coding variables like we did above. You can specify that a variable is a categorical variables in the formula itself.
iris_fit2 = smf.ols('SepalLength ~ C(Species)', iris).fit()
2016-04-25-Parallels-Regression-and-ANOVA.ipynb
Bio204-class/bio204-notebooks
cc0-1.0
You can then pass the model fit results to statsmodels.stats.anova.anova_lm to get an appropriate ANOVA table.
anova.anova_lm(iris_fit2)
2016-04-25-Parallels-Regression-and-ANOVA.ipynb
Bio204-class/bio204-notebooks
cc0-1.0
concat() documentation: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html separate data frame into a list with 3 elements
pieces = [sample_df_2[:2], sample_df_2[2:4], sample_df_2[4:]] pieces
python-scripts/data_analytics_learn/link_pandas/Ex_Files_Pandas_Data/Exercise Files/02_06/Final/.ipynb_checkpoints/60 Merge-checkpoint.ipynb
adityaka/misc_scripts
bsd-3-clause
concatenate first and last elements
new_list = pieces[0], pieces[2] pd.concat(new_list)
python-scripts/data_analytics_learn/link_pandas/Ex_Files_Pandas_Data/Exercise Files/02_06/Final/.ipynb_checkpoints/60 Merge-checkpoint.ipynb
adityaka/misc_scripts
bsd-3-clause
append() documentation: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.append.html
new_last_row = sample_df_2.iloc[2] sample_df_2.append(new_last_row) sample_df_2
python-scripts/data_analytics_learn/link_pandas/Ex_Files_Pandas_Data/Exercise Files/02_06/Final/.ipynb_checkpoints/60 Merge-checkpoint.ipynb
adityaka/misc_scripts
bsd-3-clause
merge() documentation: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.merge.html Merge DataFrame objects by performing a database-style join operation by columns or indexes. If joining columns on columns, the DataFrame indexes will be ignored. Otherwise if joining indexes on indexes or indexes o...
left = pd.DataFrame({'my_key': ['K0', 'K1', 'K2', 'K3'], 'A': ['A0', 'A1', 'A2', 'A3'], 'B': ['B0', 'B1', 'B2', 'B3']}) right = pd.DataFrame({'my_key': ['K0', 'K1', 'K2', 'K3'], 'C': ['C0', 'C1', 'C2', 'C3'], 'D': ['D0', 'D1', 'D2', 'D3']}) result = pd.merge(left, right, on='my_key') result
python-scripts/data_analytics_learn/link_pandas/Ex_Files_Pandas_Data/Exercise Files/02_06/Final/.ipynb_checkpoints/60 Merge-checkpoint.ipynb
adityaka/misc_scripts
bsd-3-clause
Load the training data into feature matrix, class labels, and event ids:
from proj1_helpers import * DATA_TRAIN_PATH = '' # TODO: download train data and supply path here y, tX, ids = load_csv_data(DATA_TRAIN_PATH)
projects/project1/scripts/project1.ipynb
kcyu1993/ML_course_kyu
mit
Do your thing crazy machine learning thing here :) ... Generate predictions and save ouput in csv format for submission:
DATA_TEST_PATH = '' # TODO: download train data and supply path here _, tX_test, ids_test = load_csv_data(DATA_TEST_PATH) OUTPUT_PATH = '' # TODO: fill in desired name of output file for submission y_pred = predict_labels(weights, tX_test) create_csv_submission(ids_test, y_pred, OUTPUT_PATH) from helpers import samp...
projects/project1/scripts/project1.ipynb
kcyu1993/ML_course_kyu
mit
Where's the data?
file_path = '../data/' DESKEWED = True if DESKEWED: train_img_filename = 'train-images_deskewed.csv' test_img_filename = 't10k-images_deskewed.csv' else: train_img_filename = 'train-images.csv' test_img_filename = 't10k-images.csv' train_label_filename = 'train-labels.csv' test_label_filename ...
svm.scikit/svm_rbf.scikit_random_gridsearch.ipynb
grfiv/MNIST
mit
How much of the data will we use?
portion = 1.0 # set to 1.0 for all of it, less than 1.0 for less
svm.scikit/svm_rbf.scikit_random_gridsearch.ipynb
grfiv/MNIST
mit
Read the training images and labels
# read trainX with open(file_path + train_img_filename,'r') as f: data_iter = csv.reader(f, delimiter = ',') data = [data for data in data_iter] trainX = np.ascontiguousarray(data, dtype = np.float64) if portion < 1.0: trainX = trainX[:portion*trainX.shape[0]] # scale trainX scaler = StandardScaler...
svm.scikit/svm_rbf.scikit_random_gridsearch.ipynb
grfiv/MNIST
mit
Read the test images and labels
# read testX with open(file_path + test_img_filename,'r') as f: data_iter = csv.reader(f, delimiter = ',') data = [data for data in data_iter] testX = np.ascontiguousarray(data, dtype = np.float64) if portion < 1.0: testX = testX[:portion*testX.shape[0]] # scale testX testX = scaler.transform(testX...
svm.scikit/svm_rbf.scikit_random_gridsearch.ipynb
grfiv/MNIST
mit
Use the smaller, fewer images for testing Print a sample
print_imgs(images = trainX, actual_labels = trainY.ravel(), predicted_labels = trainY.ravel(), starting_index = np.random.randint(0, high=trainY.shape[0]-36, size=1)[0], size = 6)
svm.scikit/svm_rbf.scikit_random_gridsearch.ipynb
grfiv/MNIST
mit
SVC Default Parameter Settings
# default parameters for SVC # ========================== default_svc_params = {} default_svc_params['C'] = 1.0 # penalty default_svc_params['class_weight'] = None # Set the parameter C of class i to class_weight[i]*C # set to 'auto' for unbalanced clas...
svm.scikit/svm_rbf.scikit_random_gridsearch.ipynb
grfiv/MNIST
mit
RANDOMIZED grid search
t0 = time.time() # search grid # =========== search_grid = dict(C = np.logspace( 0, 3, 50), gamma = np.logspace(-5, -3, 50)) # stratified K-Fold indices # ========================= SKFolds = StratifiedKFold(y = trainY.ravel(), n_folds = 3, ...
svm.scikit/svm_rbf.scikit_random_gridsearch.ipynb
grfiv/MNIST
mit
Analyze the results of the parameter pairs randomly selected
from operator import itemgetter # how many duds? mean_score_list = [score.mean_validation_score for score in random_search.grid_scores_] print("\nProportion of random scores below 98%: {0:.2f}\n".format(sum(np.array(mean_score_list)<0.98)/len(mean_score_list))) # what do the best ones look like? for score in sort...
svm.scikit/svm_rbf.scikit_random_gridsearch.ipynb
grfiv/MNIST
mit
Heatmap of the accuracy of the C and gamma pairs chosen in the grid search see http://scikit-learn.org/stable/auto_examples/svm/plot_rbf_parameters.html This script was extensively modified to work with the score results from RandomizedSearchCV
from matplotlib.colors import Normalize class MidpointNormalize(Normalize): """Utility function to move the midpoint of a colormap to be around the values of interest.""" def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False): self.midpoint = midpoint Normalize.__init__(self, vmin...
svm.scikit/svm_rbf.scikit_random_gridsearch.ipynb
grfiv/MNIST
mit
Predict the test set and analyze the result
target_names = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] predicted_values = random_search.predict(testX) y_true, y_pred = testY.ravel(), predicted_values print(classification_report(y_true, y_pred, target_names=target_names)) def plot_confusion_matrix(cm, target_names, ...
svm.scikit/svm_rbf.scikit_random_gridsearch.ipynb
grfiv/MNIST
mit
Learning Curves see http://scikit-learn.org/stable/auto_examples/model_selection/plot_learning_curve.html The red line shows how well we fit the training data. The larger the score, the lower the bias. We expect the red line to start very near to 1.0 since we ought to be able to fit just a few points very well. We expe...
t0 = time.time() from sklearn.learning_curve import learning_curve from sklearn.cross_validation import ShuffleSplit def plot_learning_curve(estimator, title, X, y, ylim=None, cv=None, n_jobs=1, train_sizes=np.linspace(.1, 1.0, 5)): """ Generate a simple plot of the test and trainin...
svm.scikit/svm_rbf.scikit_random_gridsearch.ipynb
grfiv/MNIST
mit
Vertex client library: AutoML tabular classification model for online prediction with explanation <table align="left"> <td> <a href="https://colab.research.google.com/github/GoogleCloudPlatform/vertex-ai-samples/blob/master/notebooks/community/gapic/automl/showcase_automl_tabular_classification_online_explain.ipy...
import os import sys # Google Cloud Notebook if os.path.exists("/opt/deeplearning/metadata/env_version"): USER_FLAG = "--user" else: USER_FLAG = "" ! pip3 install -U google-cloud-aiplatform $USER_FLAG
notebooks/community/gapic/automl/showcase_automl_tabular_classification_online_explain.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 client library Import the Vertex client library into our Python environment.
import time import google.cloud.aiplatform_v1beta1 as aip from google.protobuf import json_format from google.protobuf.json_format import MessageToJson, ParseDict from google.protobuf.struct_pb2 import Struct, Value
notebooks/community/gapic/automl/showcase_automl_tabular_classification_online_explain.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
AutoML constants Set constants unique to AutoML datasets and training: Dataset Schemas: Tells the Dataset resource service which type of dataset it is. Data Labeling (Annotations) Schemas: Tells the Dataset resource service how the data is labeled (annotated). Dataset Training Schemas: Tells the Pipeline resource serv...
# Tabular Dataset type DATA_SCHEMA = "gs://google-cloud-aiplatform/schema/dataset/metadata/tables_1.0.0.yaml" # Tabular Labeling type LABEL_SCHEMA = ( "gs://google-cloud-aiplatform/schema/dataset/ioformat/table_io_format_1.0.0.yaml" ) # Tabular Training task TRAINING_SCHEMA = "gs://google-cloud-aiplatform/schema/tr...
notebooks/community/gapic/automl/showcase_automl_tabular_classification_online_explain.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Tutorial Now you are ready to start creating your own AutoML tabular classification model. Set up clients The Vertex client library 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 Vertex server. You will use different clients ...
# 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/gapic/automl/showcase_automl_tabular_classification_online_explain.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Dataset Now that your clients are ready, your first step is to create a Dataset resource instance. This step differs from Vision, Video and Language. For those products, after the Dataset resource is created, one then separately imports the data, using the import_data method. For tabular, importing of the data is defer...
IMPORT_FILE = "gs://cloud-samples-data/tables/iris_1000.csv"
notebooks/community/gapic/automl/showcase_automl_tabular_classification_online_explain.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Quick peek at your data You will use a version of the Iris dataset that is stored in a public Cloud Storage bucket, using a CSV index file. Start by doing a quick peek at the data. You count the number of examples by counting the number of rows in the CSV index file (wc -l) and then peek at the first few rows. You als...
count = ! gsutil cat $IMPORT_FILE | wc -l print("Number of Examples", int(count[0])) print("First 10 rows") ! gsutil cat $IMPORT_FILE | head heading = ! gsutil cat $IMPORT_FILE | head -n1 label_column = str(heading).split(",")[-1].split("'")[0] print("Label Column Name", label_column) if label_column is None: rai...
notebooks/community/gapic/automl/showcase_automl_tabular_classification_online_explain.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Dataset Now that your clients are ready, your first step in training a model is to create a managed dataset instance, and then upload your labeled data to it. Create Dataset resource instance Use the helper function create_dataset to create the instance of a Dataset resource. This function does the following: Uses the...
TIMEOUT = 90 def create_dataset(name, schema, src_uri=None, labels=None, timeout=TIMEOUT): start_time = time.time() try: if src_uri.startswith("gs://"): metadata = {"input_config": {"gcs_source": {"uri": [src_uri]}}} elif src_uri.startswith("bq://"): metadata = {"input_...
notebooks/community/gapic/automl/showcase_automl_tabular_classification_online_explain.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Train the model Now train an AutoML tabular classification model using your Vertex Dataset resource. To train the model, do the following steps: Create an Vertex training pipeline for the Dataset resource. Execute the pipeline to start the training. Create a training pipeline You may ask, what do we use a pipeline fo...
def create_pipeline(pipeline_name, model_name, dataset, schema, task): dataset_id = dataset.split("/")[-1] input_config = { "dataset_id": dataset_id, "fraction_split": { "training_fraction": 0.8, "validation_fraction": 0.1, "test_fraction": 0.1, }, ...
notebooks/community/gapic/automl/showcase_automl_tabular_classification_online_explain.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Construct the task requirements Next, construct the task requirements. Unlike other parameters which take a Python (JSON-like) dictionary, the task field takes a Google protobuf Struct, which is very similar to a Python dictionary. Use the json_format.ParseDict method for the conversion. The minimal fields you need to ...
TRANSFORMATIONS = [ {"auto": {"column_name": "sepal_width"}}, {"auto": {"column_name": "sepal_length"}}, {"auto": {"column_name": "petal_length"}}, {"auto": {"column_name": "petal_width"}}, ] PIPE_NAME = "iris_pipe-" + TIMESTAMP MODEL_NAME = "iris_model-" + TIMESTAMP task = Value( struct_value=Str...
notebooks/community/gapic/automl/showcase_automl_tabular_classification_online_explain.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Deployment Training the above model may take upwards of 30 minutes time. Once your model is done training, you can calculate the actual time it took to train the model by subtracting end_time from start_time. For your model, you will need to know the fully qualified Vertex Model resource identifier, which the pipeline ...
while True: response = get_training_pipeline(pipeline_id, True) if response.state != aip.PipelineState.PIPELINE_STATE_SUCCEEDED: print("Training job has not completed:", response.state) model_to_deploy_id = None if response.state == aip.PipelineState.PIPELINE_STATE_FAILED: ra...
notebooks/community/gapic/automl/showcase_automl_tabular_classification_online_explain.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Model information Now that your model is trained, you can get some information on your model. Evaluate the Model resource Now find out how good the model service believes your model is. As part of training, some portion of the dataset was set aside as the test (holdout) data, which is used by the pipeline service to ev...
def list_model_evaluations(name): response = clients["model"].list_model_evaluations(parent=name) for evaluation in response: print("model_evaluation") print(" name:", evaluation.name) print(" metrics_schema_uri:", evaluation.metrics_schema_uri) metrics = json_format.MessageToDic...
notebooks/community/gapic/automl/showcase_automl_tabular_classification_online_explain.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Deploy the Model resource Now deploy the trained Vertex Model resource you created with AutoML. This requires two steps: Create an Endpoint resource for deploying the Model resource to. Deploy the Model resource to the Endpoint resource. Create an Endpoint resource Use this helper function create_endpoint to crea...
ENDPOINT_NAME = "iris_endpoint-" + TIMESTAMP def create_endpoint(display_name): endpoint = {"display_name": display_name} response = clients["endpoint"].create_endpoint(parent=PARENT, endpoint=endpoint) print("Long running operation:", response.operation.name) result = response.result(timeout=300) ...
notebooks/community/gapic/automl/showcase_automl_tabular_classification_online_explain.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Deploy Model resource to the Endpoint resource Use this helper function deploy_model to deploy the model to the endpoint you created for serving predictions, with the following parameters: model: The Vertex fully qualified identifier of the Model resource to upload (deploy) from the training pipeline. deploy_model_dis...
DEPLOYED_NAME = "iris_deployed-" + TIMESTAMP def deploy_model( model, deployed_model_display_name, endpoint, traffic_split={"0": 100} ): if DEPLOY_GPU: machine_spec = { "machine_type": DEPLOY_COMPUTE, "accelerator_type": DEPLOY_GPU, "accelerator_count": DEPLOY_NGPU...
notebooks/community/gapic/automl/showcase_automl_tabular_classification_online_explain.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Make a online prediction request with explainability Now do a online prediction with explainability to your deployed model. In this method, the predicted response will include an explanation on how the features contributed to the explanation. Make test item You will use synthetic data as a test data item. Don't be conc...
INSTANCE = { "petal_length": "1.4", "petal_width": "1.3", "sepal_length": "5.1", "sepal_width": "2.8", }
notebooks/community/gapic/automl/showcase_automl_tabular_classification_online_explain.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Make a prediction with explanation Ok, now you have a test item. Use this helper function explain_item, which takes the following parameters: data_items: The test tabular data items. endpoint: The Vertex fully qualified identifier for the Endpoint resource where the Model resource was deployed. parameters_dict: Additi...
def explain_item( data_items, endpoint, parameters_dict, deployed_model_id, silent=False ): parameters = json_format.ParseDict(parameters_dict, Value()) # The format of each instance should conform to the deployed model's prediction input schema. instances = [json_format.ParseDict(s, Value()) for s in ...
notebooks/community/gapic/automl/showcase_automl_tabular_classification_online_explain.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Understanding the explanations response First, you will look what your model predicted and compare it to the actual value.
import numpy as np try: predictions = response.predictions label = np.argmax(predictions[0]["scores"]) cls = predictions[0]["classes"][label] print("Predicted Value:", cls, predictions[0]["scores"][label]) except: pass
notebooks/community/gapic/automl/showcase_automl_tabular_classification_online_explain.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Examine feature attributions Next you will look at the feature attributions for this particular example. Positive attribution values mean a particular feature pushed your model prediction up by that amount, and vice versa for negative attribution values.
from tabulate import tabulate feature_names = ["petal_length", "petal_width", "sepal_length", "sepal_width"] attributions = response.explanations[0].attributions[0].feature_attributions rows = [] for i, val in enumerate(feature_names): rows.append([val, INSTANCE[val], attributions[val]]) print(tabulate(rows, head...
notebooks/community/gapic/automl/showcase_automl_tabular_classification_online_explain.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Check your explanations and baselines To better make sense of the feature attributions you're getting, you should compare them with your model's baseline. In most cases, the sum of your attribution values + the baseline should be very close to your model's predicted value for each input. Also note that for regression m...
import random # Prepare 10 test examples to your model for prediction using a random distribution to generate # test instances instances = [] for i in range(10): pl = str(random.uniform(1.0, 2.0)) pw = str(random.uniform(1.0, 2.0)) sl = str(random.uniform(4.0, 6.0)) sw = str(random.uniform(2.0, 4.0)) ...
notebooks/community/gapic/automl/showcase_automl_tabular_classification_online_explain.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Sanity check In the function below you perform a sanity check on the explanations.
def sanity_check_explanations( explanation, prediction, mean_tgt_value=None, variance_tgt_value=None ): passed_test = 0 total_test = 1 # `attributions` is a dict where keys are the feature names # and values are the feature attributions for each feature baseline_score = explanation.attributions[...
notebooks/community/gapic/automl/showcase_automl_tabular_classification_online_explain.ipynb
GoogleCloudPlatform/vertex-ai-samples
apache-2.0
Plot the charge density on a plane lying along the x-y axis.
# Plane refers to one of the pages of the n and r matrices. plane=0 npl = n[plane*S[1]*S[2]:(plane+1)*S[1]*S[2]] rpl = crystal._r[plane*S[1]*S[2]:(plane+1)*S[1]*S[2]] xpl = [rpl[i,0] for i in range(len(rpl))] ypl = [rpl[i,1] for i in range(len(rpl))] fig = plt.figure() ax = plt.gca(projection='3d') ax.scatter(xpl,ypl...
tests/Example.ipynb
jerjorg/dft
gpl-3.0
Ewald Sum
from pydft.crystal import * from pydft.energies.ewald import * import numpy as np # We should get something close to what Arias got with similar parameters. LC = 6 r = [LC,0,0] R = makeR(r) S = [15,15,15] crystal = Crystal(R, S, LC) crystal._X = [[0., 0., 0.]] energy = ewald_energy(crystal) print(energy)
tests/Example.ipynb
jerjorg/dft
gpl-3.0
In the assignment Arias got -1./3 so this is fairly close
error = abs(energy - (-1./3)) print(error)
tests/Example.ipynb
jerjorg/dft
gpl-3.0
Energy from Solving Schrodinger
from pydft.energies.schrodinger import * from pydft.crystal import * LC = 1. R = makeR([LC, 0., 0.]) S = [2,2,2] crystal = Crystal(R, S, LC) basis = "planewave" potential = "sho" w = 1. E = getE(crystal, basis, potential, [w]) E
tests/Example.ipynb
jerjorg/dft
gpl-3.0
We could integrate this system and the planet would go around the star at a fixed orbit with $a=1$ forever. Let's add an additional constant force that acting on the planet and is pointing in one direction $F_x = m\cdot c$, where $m$ is the planet's mass and $c$ a constant. This is called the Stark problem. In python w...
ps = sim.particles c = 0.01 def starkForce(reb_sim): ps[1].ax += c
ipython_examples/Forces.ipynb
silburt/rebound2
gpl-3.0
Next, we need to tell REBOUND about this function.
sim.additional_forces = starkForce
ipython_examples/Forces.ipynb
silburt/rebound2
gpl-3.0
Now we can just integrate as usual. Let's keep track of the eccentricity as we integrate as it will change due to the additional force.
import numpy as np Nout = 1000 es = np.zeros(Nout) times = np.linspace(0.,100.*2.*np.pi,Nout) for i, time in enumerate(times): sim.integrate(time, exact_finish_time=0) # integrate to the nearest timestep so WHFast's timestep stays constant es[i] = sim.particles[1].e
ipython_examples/Forces.ipynb
silburt/rebound2
gpl-3.0
And let's plot the result.
%matplotlib inline import matplotlib.pyplot as plt fig = plt.figure(figsize=(15,5)) ax = plt.subplot(111) plt.plot(times, es);
ipython_examples/Forces.ipynb
silburt/rebound2
gpl-3.0
You can see that the eccentricity is oscillating between 0 and almost 1. Non-conservative forces The previous example assumed a conservative force, i.e. we could describe it as a potential as it is velocity independent. Now, let's assume we have a velocity dependent force. This could be a migration force in a protopla...
sim = rebound.Simulation() sim.integrator = "ias15" sim.add(m=1.) sim.add(m=1e-6,a=1.) sim.move_to_com() # Moves to the center of momentum frame
ipython_examples/Forces.ipynb
silburt/rebound2
gpl-3.0
But we change the additional force to be
ps = sim.particles tau = 1000. def migrationForce(reb_sim): ps[1].ax -= ps[1].vx/tau ps[1].ay -= ps[1].vy/tau ps[1].az -= ps[1].vz/tau
ipython_examples/Forces.ipynb
silburt/rebound2
gpl-3.0
We need to let REBOUND know that our force is velocity dependent. Otherwise, REBOUND will not update the velocities of the particles.
sim.additional_forces = migrationForce sim.force_is_velocity_dependent = 1
ipython_examples/Forces.ipynb
silburt/rebound2
gpl-3.0
Now, we integrate as before. But this time we keep track of the semi-major axis instead of the eccentricity.
Nout = 1000 a_s = np.zeros(Nout) times = np.linspace(0.,100.*2.*np.pi,Nout) for i, time in enumerate(times): sim.integrate(time) a_s[i] = sim.particles[1].a fig = plt.figure(figsize=(15,5)) ax = plt.subplot(111) ax.set_xlabel("time") ax.set_ylabel("semi-major axis") plt.plot(times, a_s);
ipython_examples/Forces.ipynb
silburt/rebound2
gpl-3.0
TFX Estimator Component Tutorial A Component-by-Component Introduction to TensorFlow Extended (TFX) Note: We recommend running this tutorial in a Colab notebook, with no setup required! Just click "Run in Google Colab". <div class="devsite-table-wrapper"><table class="tfo-notebook-buttons" align="left"> <td><a target=...
try: import colab !pip install --upgrade pip except: pass
site/en-snapshot/tfx/tutorials/tfx/components.ipynb
tensorflow/docs-l10n
apache-2.0
Install TFX Note: In Google Colab, because of package updates, the first time you run this cell you must restart the runtime (Runtime > Restart runtime ...).
!pip install -U tfx
site/en-snapshot/tfx/tutorials/tfx/components.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 (Runtime > Restart runtime ...). This is because of the way that Colab loads packages. Import packages We import necessary packages, including standard TFX component classes.
import os import pprint import tempfile import urllib import absl import tensorflow as tf import tensorflow_model_analysis as tfma tf.get_logger().propagate = False pp = pprint.PrettyPrinter() from tfx import v1 as tfx from tfx.orchestration.experimental.interactive.interactive_context import InteractiveContext %loa...
site/en-snapshot/tfx/tutorials/tfx/components.ipynb
tensorflow/docs-l10n
apache-2.0
Set up pipeline paths
# This is the root directory for your TFX pip package installation. _tfx_root = tfx.__path__[0] # This is the directory containing the TFX Chicago Taxi Pipeline example. _taxi_root = os.path.join(_tfx_root, 'examples/chicago_taxi_pipeline') # This is the path where your model will be pushed for serving. _serving_mode...
site/en-snapshot/tfx/tutorials/tfx/components.ipynb
tensorflow/docs-l10n
apache-2.0
Download example data We download the example dataset for use in our TFX pipeline. The dataset we're using is the Taxi Trips dataset released by the City of Chicago. The columns in this dataset are: <table> <tr><td>pickup_community_area</td><td>fare</td><td>trip_start_month</td></tr> <tr><td>trip_start_hour</td><td>tri...
_data_root = tempfile.mkdtemp(prefix='tfx-data') DATA_PATH = 'https://raw.githubusercontent.com/tensorflow/tfx/master/tfx/examples/chicago_taxi_pipeline/data/simple/data.csv' _data_filepath = os.path.join(_data_root, "data.csv") urllib.request.urlretrieve(DATA_PATH, _data_filepath)
site/en-snapshot/tfx/tutorials/tfx/components.ipynb
tensorflow/docs-l10n
apache-2.0
Disclaimer: This site provides applications using data that has been modified for use from its original source, www.cityofchicago.org, the official website of the City of Chicago. The City of Chicago makes no claims as to the content, accuracy, timeliness, or completeness of any of the data provided at this site. The d...
# Here, we create an InteractiveContext using default parameters. This will # use a temporary directory with an ephemeral ML Metadata database instance. # To use your own pipeline root or database, the optional properties # `pipeline_root` and `metadata_connection_config` may be passed to # InteractiveContext. Calls to...
site/en-snapshot/tfx/tutorials/tfx/components.ipynb
tensorflow/docs-l10n
apache-2.0
Run TFX components interactively In the cells that follow, we create TFX components one-by-one, run each of them, and visualize their output artifacts. ExampleGen The ExampleGen component is usually at the start of a TFX pipeline. It will: Split data into training and evaluation sets (by default, 2/3 training + 1/3 ev...
example_gen = tfx.components.CsvExampleGen(input_base=_data_root) context.run(example_gen)
site/en-snapshot/tfx/tutorials/tfx/components.ipynb
tensorflow/docs-l10n
apache-2.0
We can also take a look at the first three training examples:
# Get the URI of the output artifact representing the training examples, which is a directory train_uri = os.path.join(example_gen.outputs['examples'].get()[0].uri, 'Split-train') # Get the list of files in this directory (all compressed TFRecord files) tfrecord_filenames = [os.path.join(train_uri, name) ...
site/en-snapshot/tfx/tutorials/tfx/components.ipynb
tensorflow/docs-l10n
apache-2.0
Now that ExampleGen has finished ingesting the data, the next step is data analysis. StatisticsGen The StatisticsGen component computes statistics over your dataset for data analysis, as well as for use in downstream components. It uses the TensorFlow Data Validation library. StatisticsGen takes as input the dataset we...
statistics_gen = tfx.components.StatisticsGen(examples=example_gen.outputs['examples']) context.run(statistics_gen)
site/en-snapshot/tfx/tutorials/tfx/components.ipynb
tensorflow/docs-l10n
apache-2.0
After StatisticsGen finishes running, we can visualize the outputted statistics. Try playing with the different plots!
context.show(statistics_gen.outputs['statistics'])
site/en-snapshot/tfx/tutorials/tfx/components.ipynb
tensorflow/docs-l10n
apache-2.0
SchemaGen The SchemaGen component generates a schema based on your data statistics. (A schema defines the expected bounds, types, and properties of the features in your dataset.) It also uses the TensorFlow Data Validation library. SchemaGen will take as input the statistics that we generated with StatisticsGen, lookin...
schema_gen = tfx.components.SchemaGen( statistics=statistics_gen.outputs['statistics'], infer_feature_shape=False) context.run(schema_gen)
site/en-snapshot/tfx/tutorials/tfx/components.ipynb
tensorflow/docs-l10n
apache-2.0
After SchemaGen finishes running, we can visualize the generated schema as a table.
context.show(schema_gen.outputs['schema'])
site/en-snapshot/tfx/tutorials/tfx/components.ipynb
tensorflow/docs-l10n
apache-2.0
Each feature in your dataset shows up as a row in the schema table, alongside its properties. The schema also captures all the values that a categorical feature takes on, denoted as its domain. To learn more about schemas, see the SchemaGen documentation. ExampleValidator The ExampleValidator component detects anomalie...
example_validator = tfx.components.ExampleValidator( statistics=statistics_gen.outputs['statistics'], schema=schema_gen.outputs['schema']) context.run(example_validator)
site/en-snapshot/tfx/tutorials/tfx/components.ipynb
tensorflow/docs-l10n
apache-2.0
After ExampleValidator finishes running, we can visualize the anomalies as a table.
context.show(example_validator.outputs['anomalies'])
site/en-snapshot/tfx/tutorials/tfx/components.ipynb
tensorflow/docs-l10n
apache-2.0
In the anomalies table, we can see that there are no anomalies. This is what we'd expect, since this the first dataset that we've analyzed and the schema is tailored to it. You should review this schema -- anything unexpected means an anomaly in the data. Once reviewed, the schema can be used to guard future data, and ...
_taxi_constants_module_file = 'taxi_constants.py' %%writefile {_taxi_constants_module_file} # Categorical features are assumed to each have a maximum value in the dataset. MAX_CATEGORICAL_FEATURE_VALUES = [24, 31, 12] CATEGORICAL_FEATURE_KEYS = [ 'trip_start_hour', 'trip_start_day', 'trip_start_month', 'pick...
site/en-snapshot/tfx/tutorials/tfx/components.ipynb
tensorflow/docs-l10n
apache-2.0
Next, we write a preprocessing_fn that takes in raw data as input, and returns transformed features that our model can train on:
_taxi_transform_module_file = 'taxi_transform.py' %%writefile {_taxi_transform_module_file} import tensorflow as tf import tensorflow_transform as tft import taxi_constants _DENSE_FLOAT_FEATURE_KEYS = taxi_constants.DENSE_FLOAT_FEATURE_KEYS _VOCAB_FEATURE_KEYS = taxi_constants.VOCAB_FEATURE_KEYS _VOCAB_SIZE = taxi_...
site/en-snapshot/tfx/tutorials/tfx/components.ipynb
tensorflow/docs-l10n
apache-2.0
Now, we pass in this feature engineering code to the Transform component and run it to transform your data.
transform = tfx.components.Transform( examples=example_gen.outputs['examples'], schema=schema_gen.outputs['schema'], module_file=os.path.abspath(_taxi_transform_module_file)) context.run(transform)
site/en-snapshot/tfx/tutorials/tfx/components.ipynb
tensorflow/docs-l10n
apache-2.0
The transformed_metadata subdirectory contains the schema of the preprocessed data. The transform_fn subdirectory contains the actual preprocessing graph. The metadata subdirectory contains the schema of the original data. We can also take a look at the first three transformed examples:
# Get the URI of the output artifact representing the transformed examples, which is a directory train_uri = os.path.join(transform.outputs['transformed_examples'].get()[0].uri, 'Split-train') # Get the list of files in this directory (all compressed TFRecord files) tfrecord_filenames = [os.path.join(train_uri, name) ...
site/en-snapshot/tfx/tutorials/tfx/components.ipynb
tensorflow/docs-l10n
apache-2.0
After the Transform component has transformed your data into features, and the next step is to train a model. Trainer The Trainer component will train a model that you define in TensorFlow (either using the Estimator API or the Keras API with model_to_estimator). Trainer takes as input the schema from SchemaGen, the tr...
_taxi_trainer_module_file = 'taxi_trainer.py' %%writefile {_taxi_trainer_module_file} import tensorflow as tf import tensorflow_model_analysis as tfma import tensorflow_transform as tft from tensorflow_transform.tf_metadata import schema_utils from tfx_bsl.tfxio import dataset_options import taxi_constants _DENSE_F...
site/en-snapshot/tfx/tutorials/tfx/components.ipynb
tensorflow/docs-l10n
apache-2.0
Now, we pass in this model code to the Trainer component and run it to train the model.
from tfx.components.trainer.executor import Executor from tfx.dsl.components.base import executor_spec trainer = tfx.components.Trainer( module_file=os.path.abspath(_taxi_trainer_module_file), custom_executor_spec=executor_spec.ExecutorClassSpec(Executor), examples=transform.outputs['transformed_examples']...
site/en-snapshot/tfx/tutorials/tfx/components.ipynb
tensorflow/docs-l10n
apache-2.0
Analyze Training with TensorBoard Optionally, we can connect TensorBoard to the Trainer to analyze our model's training curves.
# Get the URI of the output artifact representing the training logs, which is a directory model_run_dir = trainer.outputs['model_run'].get()[0].uri %load_ext tensorboard %tensorboard --logdir {model_run_dir}
site/en-snapshot/tfx/tutorials/tfx/components.ipynb
tensorflow/docs-l10n
apache-2.0
Evaluator The Evaluator component computes model performance metrics over the evaluation set. It uses the TensorFlow Model Analysis library. The Evaluator can also optionally validate that a newly trained model is better than the previous model. This is useful in a production pipeline setting where you may automaticall...
eval_config = tfma.EvalConfig( model_specs=[ # Using signature 'eval' implies the use of an EvalSavedModel. To use # a serving model remove the signature to defaults to 'serving_default' # and add a label_key. tfma.ModelSpec(signature_name='eval') ], metrics_specs=[ t...
site/en-snapshot/tfx/tutorials/tfx/components.ipynb
tensorflow/docs-l10n
apache-2.0