INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Returns a degree vectors for the input.
def _create_input_order(input_size, input_order="left-to-right"): """Returns a degree vectors for the input.""" if isinstance(input_order, six.string_types): if input_order == "left-to-right": return np.arange(start=1, stop=input_size + 1) elif input_order == "right-to-left": return np.arange(st...
Returns a list of degree vectors one for each input and hidden layer.
def _create_degrees(input_size, hidden_units=None, input_order="left-to-right", hidden_degrees="equal"): """Returns a list of degree vectors, one for each input and hidden layer. A unit with degree d can only receive input from units with degree < d. Outp...
Returns a list of binary mask matrices enforcing autoregressivity.
def _create_masks(degrees): """Returns a list of binary mask matrices enforcing autoregressivity.""" return [ # Create input->hidden and hidden->hidden masks. inp[:, np.newaxis] <= out for inp, out in zip(degrees[:-1], degrees[1:]) ] + [ # Create hidden->output mask. degrees[-1][:, n...
Returns a masked version of the given initializer.
def _make_masked_initializer(mask, initializer): """Returns a masked version of the given initializer.""" initializer = tf.keras.initializers.get(initializer) def masked_initializer(shape, dtype=None, partition_info=None): # If no `partition_info` is given, then don't pass it to `initializer`, as # `initi...
See tfkl. Layer. build.
def build(self, input_shape): """See tfkl.Layer.build.""" if self._event_shape is None: # `event_shape` wasn't specied at __init__, so infer from `input_shape`. self._event_shape = [tf.compat.dimension_value(input_shape[-1])] self._event_size = self._event_shape[-1] self._event_ndims = l...
See tfkl. Layer. call.
def call(self, x): """See tfkl.Layer.call.""" with tf.compat.v2.name_scope(self.name or "AutoregressiveLayer_call"): x = tf.convert_to_tensor(value=x, dtype=self.dtype, name="x") input_shape = tf.shape(input=x) # TODO(b/67594795): Better support for dynamic shapes. if tensorshape_util.ra...
Sample a multinomial.
def draw_sample(num_samples, num_classes, logits, num_trials, dtype, seed): """Sample a multinomial. The batch shape is given by broadcasting num_trials with remove_last_dimension(logits). Args: num_samples: Python int or singleton integer Tensor: number of multinomial samples to draw. num_class...
Build a zero - dimensional MVNDiag object.
def _zero_dimensional_mvndiag(dtype): """Build a zero-dimensional MVNDiag object.""" dummy_mvndiag = tfd.MultivariateNormalDiag( scale_diag=tf.ones([0], dtype=dtype)) dummy_mvndiag.covariance = lambda: dummy_mvndiag.variance()[..., tf.newaxis] return dummy_mvndiag
Build an observation_noise_fn that observes a Tensor timeseries.
def _observe_timeseries_fn(timeseries): """Build an observation_noise_fn that observes a Tensor timeseries.""" def observation_noise_fn(t): current_slice = timeseries[..., t, :] return tfd.MultivariateNormalDiag( loc=current_slice, scale_diag=tf.zeros_like(current_slice)) return observatio...
Build regression weights from model parameters.
def params_to_weights(self, global_scale_variance, global_scale_noncentered, local_scale_variances, local_scales_noncentered, weights_noncentered): """Build regression weights from model parameter...
Computes the number of edges on longest path from node to root.
def _depth(g): """Computes the number of edges on longest path from node to root.""" def _explore(v): if v.depth < 0: v.depth = ((1 + max([-1] + [_explore(annotated_graph[u]) for u in v.parents])) if v.parents else 0) return v.depth annotated_graph ...
Creates tuple of str tuple - str pairs representing resolved & sorted DAG.
def _best_order(g): """Creates tuple of str tuple-str pairs representing resolved & sorted DAG.""" def _explore(u): """Recursive function to ascend up through unvisited dependencies.""" if u.depth < 0: return # Already visited. if not u.parents: result.append((u.name, u.parents)) u.de...
Creates lists of callables suitable for JDSeq.
def _prob_chain_rule_flatten(named_makers): """Creates lists of callables suitable for JDSeq.""" def _make(dist_fn, args): if args is None: return lambda *_: dist_fn if not args: return lambda *_: dist_fn() def _fn(*xs): kwargs = dict(zip(args, reversed(xs[-len(args):]))) kwargs....
Creates dist_fn dist_fn_wrapped dist_fn_args dist_fn_name.
def _build(self, model): """Creates `dist_fn`, `dist_fn_wrapped`, `dist_fn_args`, `dist_fn_name`.""" if not _is_dict_like(model): raise TypeError('`model` must be convertible to `dict` (saw: {}).'.format( type(model).__name__)) [ self._dist_fn, self._dist_fn_wrapped, ...
Variational loss for the VGP.
def variational_loss(self, observations, observation_index_points=None, kl_weight=1., name='variational_loss'): """Variational loss for the VGP. Given `observations` and `observation_index_points`, compute the negat...
Model selection for optimal variational hyperparameters.
def optimal_variational_posterior( kernel, inducing_index_points, observation_index_points, observations, observation_noise_variance, mean_fn=None, jitter=1e-6, name=None): """Model selection for optimal variational hyperparameters. Given the full training set (p...
Build utility method to compute whether the season is changing.
def build_is_last_day_of_season(num_steps_per_season): """Build utility method to compute whether the season is changing.""" num_steps_per_cycle = np.sum(num_steps_per_season) changepoints = np.cumsum(np.ravel(num_steps_per_season)) - 1 def is_last_day_of_season(t): t_ = dist_util.maybe_get_static_value(t) ...
Build change - of - basis matrices for constrained seasonal effects.
def build_effects_to_residuals_matrix(num_seasons, dtype): """Build change-of-basis matrices for constrained seasonal effects. This method builds the matrix that transforms seasonal effects into effect residuals (differences from the mean effect), and additionally projects these residuals onto the subspace whe...
Build a function computing transitions for a seasonal effect model.
def build_seasonal_transition_matrix( num_seasons, is_last_day_of_season, dtype, basis_change_matrix=None, basis_change_matrix_inv=None): """Build a function computing transitions for a seasonal effect model.""" with tf.compat.v1.name_scope('build_seasonal_transition_matrix'): # If the season is changi...
Build the transition noise model for a SeasonalStateSpaceModel.
def build_seasonal_transition_noise( drift_scale, num_seasons, is_last_day_of_season): """Build the transition noise model for a SeasonalStateSpaceModel.""" # If the current season has just ended, increase the variance of its effect # following drift_scale. (the just-ended seasonal effect will always be the ...
Build transition noise distribution for a ConstrainedSeasonalSSM.
def build_constrained_seasonal_transition_noise( drift_scale, num_seasons, is_last_day_of_season): """Build transition noise distribution for a ConstrainedSeasonalSSM.""" # Conceptually, this method takes the noise covariance on effects L @ L' # computed by `build_seasonal_transition_noise`, with scale facto...
Returns True if given observation data is empty.
def _is_empty_observation_data( feature_ndims, observation_index_points, observations): """Returns `True` if given observation data is empty. Emptiness means either 1. Both `observation_index_points` and `observations` are `None`, or 2. the "number of observations" shape is 0. The shape of `observa...
Ensure that observation data and locations have consistent shapes.
def _validate_observation_data( kernel, observation_index_points, observations): """Ensure that observation data and locations have consistent shapes. This basically means that the batch shapes are broadcastable. We can only ensure this when those shapes are fully statically defined. Args: kernel: Th...
Calculate the batched KL divergence KL ( g0 || g1 ) with g0 and g1 Gamma.
def _kl_gamma_gamma(g0, g1, name=None): """Calculate the batched KL divergence KL(g0 || g1) with g0 and g1 Gamma. Args: g0: instance of a Gamma distribution object. g1: instance of a Gamma distribution object. name: (optional) Name to use for created operations. Default is "kl_gamma_gamma". Re...
Add a learning rate scheduler to the contained schedules
def add(self, scheduler, max_iteration, bigdl_type="float"): """ Add a learning rate scheduler to the contained `schedules` :param scheduler: learning rate scheduler to be add :param max_iteration: iteration numbers this scheduler will run """ return callBigDlFunc(bigdl_...
save OptimMethod: param path path: param overWrite whether to overwrite
def save(self, path, overWrite): """ save OptimMethod :param path path :param overWrite whether to overwrite """ method=self.value return callBigDlFunc(self.bigdl_type, "saveOptimMethod", method, path, overWrite)
Configure checkpoint settings.
def set_checkpoint(self, checkpoint_trigger, checkpoint_path, isOverWrite=True): """ Configure checkpoint settings. :param checkpoint_trigger: the interval to write snapshots :param checkpoint_path: the path to write snapshots into :param isOverWrite: whe...
Configure constant clipping settings.
def set_gradclip_const(self, min_value, max_value): """ Configure constant clipping settings. :param min_value: the minimum value to clip by :param max_value: the maxmimum value to clip by """ callBigDlFunc(self.bigdl_type, "setConstantClip", self.value, min_value, max_...
Do an optimization.
def optimize(self): """ Do an optimization. """ jmodel = callJavaFunc(self.value.optimize) from bigdl.nn.layer import Layer return Layer.of(jmodel)
Set train summary. A TrainSummary object contains information necessary for the optimizer to know how often the logs are recorded where to store the logs and how to retrieve them etc. For details refer to the docs of TrainSummary.
def set_train_summary(self, summary): """ Set train summary. A TrainSummary object contains information necessary for the optimizer to know how often the logs are recorded, where to store the logs and how to retrieve them, etc. For details, refer to the docs of TrainSummary. ...
Set validation summary. A ValidationSummary object contains information necessary for the optimizer to know how often the logs are recorded where to store the logs and how to retrieve them etc. For details refer to the docs of ValidationSummary.
def set_val_summary(self, summary): """ Set validation summary. A ValidationSummary object contains information necessary for the optimizer to know how often the logs are recorded, where to store the logs and how to retrieve them, etc. For details, refer to the docs of Validation...
Create an optimizer. Depend on the input type the returning optimizer can be a local optimizer \ or a distributed optimizer.
def create(model, training_set, criterion, end_trigger=None, batch_size=32, optim_method=None, cores=None, bigdl_type="float"): """ Create an optimizer. Depend on the input type, the returnin...
Configure validation settings.
def set_validation(self, batch_size, val_rdd, trigger, val_method=None): """ Configure validation settings. :param batch_size: validation batch size :param val_rdd: validation dataset :param trigger: validation interval :param val_method: the ValidationMethod to use,e.g...
Set new training dataset for optimizer reuse
def set_traindata(self, training_rdd, batch_size): """ Set new training dataset, for optimizer reuse :param training_rdd: the training dataset :param batch_size: training batch size :return: """ callBigDlFunc(self.bigdl_type, "setTrainData", self.value, ...
Configure validation settings.
def set_validation(self, batch_size, X_val, Y_val, trigger, val_method=None): """ Configure validation settings. :param batch_size: validation batch size :param X_val: features of validation dataset :param Y_val: label of validation dataset :param trigger: validation int...
Set the interval of recording for each indicator.
def set_summary_trigger(self, name, trigger): """ Set the interval of recording for each indicator. :param tag: tag name. Supported tag names are "LearningRate", "Loss","Throughput", "Parameters". "Parameters" is an umbrella tag thatincludes weight, bias, gradWeight, gradBias, and some running...
Parse or download mnist data if train_dir is empty.
def read_data_sets(train_dir, data_type="train"): """ Parse or download mnist data if train_dir is empty. :param: train_dir: The directory storing the mnist data :param: data_type: Reading training set or testing set.It can be either "train" or "test" :return: ``` (ndarray, ndarray) repr...
Parse or download news20 if source_dir is empty.
def get_news20(source_dir="./data/news20/"): """ Parse or download news20 if source_dir is empty. :param source_dir: The directory storing news data. :return: A list of (tokens, label) """ news_dir = download_news20(source_dir) texts = [] # list of text samples label_id = 0 for nam...
Parse or download the pre - trained glove word2vec if source_dir is empty.
def get_glove_w2v(source_dir="./data/news20/", dim=100): """ Parse or download the pre-trained glove word2vec if source_dir is empty. :param source_dir: The directory storing the pre-trained word2vec :param dim: The dimension of a vector :return: A dict mapping from word to vector """ w2v_d...
Configures the learning process. Must be called before fit or evaluate.
def compile(self, optimizer, loss, metrics=None): """ Configures the learning process. Must be called before fit or evaluate. # Arguments optimizer: Optimization method to be used. One can alternatively pass in the corresponding string representation, such as 'sgd'. ...
Train a model for a fixed number of epochs on a dataset.
def fit(self, x, y=None, batch_size=32, nb_epoch=10, validation_data=None, distributed=True): """ Train a model for a fixed number of epochs on a dataset. # Arguments x: Input data. A Numpy array or RDD of Sample or Image DataSet. y: Labels. A Numpy array. Default is None if x i...
Evaluate a model on a given dataset in distributed mode.
def evaluate(self, x, y=None, batch_size=32): """ Evaluate a model on a given dataset in distributed mode. # Arguments x: Input data. A Numpy array or RDD of Sample. y: Labels. A Numpy array. Default is None if x is already RDD of Sample. batch_size: Number of samples pe...
Use a model to do prediction.
def predict(self, x, distributed=True): """ Use a model to do prediction. # Arguments x: Input data. A Numpy array or RDD of Sample. distributed: Boolean. Whether to do prediction in distributed mode or local mode. Default is True. In local mode, x must be a...
Create a Python Model base on the given java value: param jvalue: Java object create by Py4j: return: A Python Model
def from_jvalue(jvalue, bigdl_type="float"): """ Create a Python Model base on the given java value :param jvalue: Java object create by Py4j :return: A Python Model """ model = Sequential(jvalue=jvalue) model.value = jvalue return model
Create a Python Model base on the given java value: param jvalue: Java object create by Py4j: return: A Python Model
def from_jvalue(jvalue, bigdl_type="float"): """ Create a Python Model base on the given java value :param jvalue: Java object create by Py4j :return: A Python Model """ model = Model([], [], jvalue=jvalue) model.value = jvalue return model
Get mnist dataset and parallelize into RDDs. Data would be downloaded automatically if it doesn t present at the specific location.
def get_mnist(sc, data_type="train", location="/tmp/mnist"): """ Get mnist dataset and parallelize into RDDs. Data would be downloaded automatically if it doesn't present at the specific location. :param sc: SparkContext. :param data_type: "train" for training data and "test" for testing data. ...
Preprocess mnist dataset. Normalize and transform into Sample of RDDs.
def preprocess_mnist(sc, options): """ Preprocess mnist dataset. Normalize and transform into Sample of RDDs. """ train_data = get_mnist(sc, "train", options.dataPath)\ .map(lambda rec_tuple: (normalizer(rec_tuple[0], mnist.TRAIN_MEAN, mnist.TRAIN_STD), rec_tu...
When to end the optimization based on input option.
def get_end_trigger(options): """ When to end the optimization based on input option. """ if options.endTriggerType.lower() == "epoch": return MaxEpoch(options.endTriggerNum) else: return MaxIteration(options.endTriggerNum)
Set validation and checkpoint for distributed optimizer.
def validate_optimizer(optimizer, test_data, options): """ Set validation and checkpoint for distributed optimizer. """ optimizer.set_validation( batch_size=options.batchSize, val_rdd=test_data, trigger=EveryEpoch(), val_method=[Top1Accuracy()] ) optimizer.set_che...
Sets the value of: py: attr: batchSize.
def setBatchSize(self, val): """ Sets the value of :py:attr:`batchSize`. """ self._paramMap[self.batchSize] = val pythonBigDL_method_name = "setBatchSize" + self.__class__.__name__ callBigDlFunc(self.bigdl_type, pythonBigDL_method_name, self.value, val) return sel...
Return the broadcasted value
def value(self): """ Return the broadcasted value """ if not hasattr(self, "_value") and self._path is not None: self._value = self._load(self._path) return self._value
Conver x and y into RDD [ Sample ]: param x: ndarray and the first dimension should be batch: param y: ndarray and the first dimension should be batch: param numSlices:: return:
def to_sample_rdd(x, y, numSlices=None): """ Conver x and y into RDD[Sample] :param x: ndarray and the first dimension should be batch :param y: ndarray and the first dimension should be batch :param numSlices: :return: """ sc = get_spark_context() from bigdl.util.common import Sampl...
Get the current active spark context and create one if no active instance: param conf: combining bigdl configs into spark conf: return: SparkContext
def get_spark_context(conf=None): """ Get the current active spark context and create one if no active instance :param conf: combining bigdl configs into spark conf :return: SparkContext """ if hasattr(SparkContext, "getOrCreate"): with SparkContext._lock: if SparkContext._ac...
Call API in PythonBigDL
def callBigDlFunc(bigdl_type, name, *args): """ Call API in PythonBigDL """ gateway = _get_gateway() error = Exception("Cannot find function: %s" % name) for jinvoker in JavaCreator.instance(bigdl_type, gateway).value: # hasattr(jinvoker, name) always return true here, # so you need to i...
Call Java Function
def callJavaFunc(func, *args): """ Call Java Function """ gateway = _get_gateway() args = [_py2java(gateway, a) for a in args] result = func(*args) return _java2py(gateway, result)
Return a JavaRDD of Object by unpickling
def _to_java_object_rdd(rdd): """ Return a JavaRDD of Object by unpickling It will convert each Python object into Java object by Pyrolite, whenever the RDD is serialized in batch or not. """ rdd = rdd._reserialize(AutoBatchedSerializer(PickleSerializer())) return \ rdd.ctx._jvm.org.ap...
Convert Python object into Java
def _py2java(gateway, obj): """ Convert Python object into Java """ if isinstance(obj, RDD): obj = _to_java_object_rdd(obj) elif isinstance(obj, DataFrame): obj = obj._jdf elif isinstance(obj, SparkContext): obj = obj._jsc elif isinstance(obj, (list, tuple)): obj = Li...
Convert to a bigdl activation layer given the name of the activation as a string
def get_activation_by_name(activation_name, activation_id=None): """ Convert to a bigdl activation layer given the name of the activation as a string """ import bigdl.nn.layer as BLayer activation = None activation_name = activation_name.lower() if activation_name == "tanh": activat...
Convert a ndarray to a DenseTensor which would be used in Java side.
def from_ndarray(cls, a_ndarray, bigdl_type="float"): """ Convert a ndarray to a DenseTensor which would be used in Java side. >>> import numpy as np >>> from bigdl.util.common import JTensor >>> from bigdl.util.common import callBigDlFunc >>> np.random.seed(123) ...
Convert a three ndarray to SparseTensor which would be used in Java side. For example: a_ndarray = [ 1 3 2 4 ] i_ndarray = [[ 0 0 1 2 ] [ 0 3 2 1 ]] shape = [ 3 4 ] Present a dense tensor [[ 1 0 0 3 ] [ 0 0 2 0 ] [ 0 4 0 0 ]]
def sparse(cls, a_ndarray, i_ndarray, shape, bigdl_type="float"): """ Convert a three ndarray to SparseTensor which would be used in Java side. For example: a_ndarray = [1, 3, 2, 4] i_ndarray = [[0, 0, 1, 2], [0, 3, 2, 1]] shape = [3, 4] Prese...
Transfer JTensor to ndarray. As SparseTensor may generate an very big ndarray so we don t support this function for SparseTensor.: return: a ndarray
def to_ndarray(self): """ Transfer JTensor to ndarray. As SparseTensor may generate an very big ndarray, so we don't support this function for SparseTensor. :return: a ndarray """ assert self.indices is None, "sparseTensor to ndarray is not supported" return np.ar...
Convert a ndarray of features and labels to Sample which would be used in Java side.: param features: an ndarray or a list of ndarrays: param labels: an ndarray or a list of ndarrays or a scalar: param bigdl_type: double or float
def from_ndarray(cls, features, labels, bigdl_type="float"): """ Convert a ndarray of features and labels to Sample, which would be used in Java side. :param features: an ndarray or a list of ndarrays :param labels: an ndarray or a list of ndarrays or a scalar :param bigdl_type: ...
transform ImageFeature
def transform(self, image_feature, bigdl_type="float"): """ transform ImageFeature """ callBigDlFunc(bigdl_type, "transformImageFeature", self.value, image_feature) return image_feature
get label as ndarray from ImageFeature
def get_label(self): """ get label as ndarray from ImageFeature """ label = callBigDlFunc(self.bigdl_type, "imageFeatureToLabelTensor", self.value) return label.to_ndarray()
Read images as Image Frame if sc is defined Read image as DistributedImageFrame from local file system or HDFS if sc is null Read image as LocalImageFrame from local file system: param path path to read images if sc is defined path can be local or HDFS. Wildcard character are supported. if sc is null path is local dire...
def read(cls, path, sc=None, min_partitions=1, bigdl_type="float"): """ Read images as Image Frame if sc is defined, Read image as DistributedImageFrame from local file system or HDFS if sc is null, Read image as LocalImageFrame from local file system :param path path to read ima...
Read parquet file as DistributedImageFrame
def read_parquet(cls, path, sc, bigdl_type="float"): """ Read parquet file as DistributedImageFrame """ return DistributedImageFrame(jvalue=callBigDlFunc(bigdl_type, "readParquet", path, sc))
write ImageFrame as parquet file
def write_parquet(cls, path, output, sc, partition_num = 1, bigdl_type="float"): """ write ImageFrame as parquet file """ return callBigDlFunc(bigdl_type, "writeParquet", path, output, sc, partition_num)
transformImageFrame
def transform(self, transformer, bigdl_type="float"): """ transformImageFrame """ self.value = callBigDlFunc(bigdl_type, "transformImageFrame", transformer, self.value) return self
get image from ImageFrame
def get_image(self, float_key="floats", to_chw=True): """ get image from ImageFrame """ return self.image_frame.get_image(float_key, to_chw)
Random split imageframes according to weights: param weights: weights for each ImageFrame: return:
def random_split(self, weights): """ Random split imageframes according to weights :param weights: weights for each ImageFrame :return: """ jvalues = self.image_frame.random_split(weights) return [ImageFrame(jvalue) for jvalue in jvalues]
get image list from ImageFrame
def get_image(self, float_key="floats", to_chw=True): """ get image list from ImageFrame """ tensors = callBigDlFunc(self.bigdl_type, "localImageFrameToImageTensor", self.value, float_key, to_chw) return map(lambda tensor: tensor.to_ndarray(), t...
get label rdd from ImageFrame
def get_label(self): """ get label rdd from ImageFrame """ tensor_rdd = callBigDlFunc(self.bigdl_type, "distributedImageFrameToLabelTensorRdd", self.value) return tensor_rdd.map(lambda tensor: tensor.to_ndarray())
get prediction rdd from ImageFrame
def get_predict(self, key="predict"): """ get prediction rdd from ImageFrame """ predicts = callBigDlFunc(self.bigdl_type, "distributedImageFrameToPredict", self.value, key) return predicts.map(lambda predict: (predict[0], predict[1].to_ndarray()) if predict[1] else (predict[0], ...
Extract hadoop sequence files from an HDFS path as ImageFrame: param url: sequence files folder path: param sc: spark context: param class_num: class number of data: param partition_num: partition number default: Engine. nodeNumber () * Engine. coreNumber ()
def files_to_image_frame(cls, url, sc, class_num, partition_num=-1, bigdl_type="float"): """ Extract hadoop sequence files from an HDFS path as ImageFrame ...
Evaluate a model by the given metrics.: param x: ndarray or list of ndarray for local mode. RDD [ Sample ] for distributed mode: param y: ndarray or list of ndarray for local mode and would be None for cluster mode.: param batch_size: param is_distributed: run in local mode or distributed mode. NB: if is_distributed = ...
def evaluate(self, x, y, batch_size=32, sample_weight=None, is_distributed=False): """ Evaluate a model by the given metrics. :param x: ndarray or list of ndarray for local mode. RDD[Sample] for distributed mode :param y: ndarray or list of ndarray for local mode and wo...
Generates output predictions for the input samples processing the samples in a batched way.
def predict(self, x, batch_size=None, verbose=None, is_distributed=False): """Generates output predictions for the input samples, processing the samples in a batched way. # Arguments x: the input data, as a Numpy array or list of Numpy array for local mode. as RDD[Sam...
Optimize the model by the given options
def fit(self, x, y=None, batch_size=32, nb_epoch=10, verbose=1, callbacks=None, validation_split=0., validation_data=None, shuffle=True, class_weight=None, sample_weight=None, initial_epoch=0, is_distributed=False): """Optimize the model by the given options :param x: ndarray or...
Apply the transformer to the images in inputCol and store the transformed result into outputCols
def transform(self, dataset): """ Apply the transformer to the images in "inputCol" and store the transformed result into "outputCols" """ self._transfer_params_to_java() return callBigDlFunc(self.bigdl_type, "dlImageTransform", self.value, dataset)
Save a Keras model definition to JSON with given path
def save_keras_definition(keras_model, path): """ Save a Keras model definition to JSON with given path """ model_json = keras_model.to_json() with open(path, "w") as json_file: json_file.write(model_json)
Download or load MNIST dataset to/ from the specified path. Normalize and transform input data into an RDD of Sample
def get_mnist(sc, data_type="train", location="/tmp/mnist"): """ Download or load MNIST dataset to/from the specified path. Normalize and transform input data into an RDD of Sample """ from bigdl.dataset import mnist from bigdl.dataset.transformer import normalizer (images, labels) = mnist.r...
Define a convnet model in Keras 1. 2. 2
def build_keras_model(): """ Define a convnet model in Keras 1.2.2 """ from keras.models import Sequential from keras.layers import Dense, Dropout, Activation, Flatten from keras.layers import Convolution2D, MaxPooling2D keras_model = Sequential() keras_model.add(Convolution2D(32, 3, 3,...
Load a pre - trained Bigdl model.
def load(path, bigdl_type="float"): """ Load a pre-trained Bigdl model. :param path: The path containing the pre-trained model. :return: A pre-trained model. """ jmodel = callBigDlFunc(bigdl_type, "loadBigDL", path) return Layer.of(jmodel)
Create a Python Layer base on the given java value and the real type.: param jvalue: Java object create by Py4j: return: A Python Layer
def of(jvalue, bigdl_type="float"): """ Create a Python Layer base on the given java value and the real type. :param jvalue: Java object create by Py4j :return: A Python Layer """ def get_py_name(jclass_name): if jclass_name == "StaticGraph" or jclass_name == ...
Set the running mean of the layer. Only use this method for a BatchNormalization layer.: param running_mean: a Numpy array.
def set_running_mean(self, running_mean): """ Set the running mean of the layer. Only use this method for a BatchNormalization layer. :param running_mean: a Numpy array. """ callBigDlFunc(self.bigdl_type, "setRunningMean", self.value, JTensor.from_nd...
Set the running variance of the layer. Only use this method for a BatchNormalization layer.: param running_std: a Numpy array.
def set_running_std(self, running_std): """ Set the running variance of the layer. Only use this method for a BatchNormalization layer. :param running_std: a Numpy array. """ callBigDlFunc(self.bigdl_type, "setRunningStd", self.value, JTensor.from_nd...
Create a Python Model base on the given java value: param jvalue: Java object create by Py4j: return: A Python Model
def from_jvalue(jvalue, bigdl_type="float"): """ Create a Python Model base on the given java value :param jvalue: Java object create by Py4j :return: A Python Model """ model = Layer(jvalue=jvalue, bigdl_type=bigdl_type) model.value = jvalue return model
: param input: ndarray or list of ndarray or JTensor or list of JTensor.: return: ( list of JTensor isTable )
def check_input(input): """ :param input: ndarray or list of ndarray or JTensor or list of JTensor. :return: (list of JTensor, isTable) """ def to_jtensor(i): if isinstance(i, np.ndarray): return JTensor.from_ndarray(i) elif isinstance(i, J...
NB: It s for debug only please use optimizer. optimize () in production. Takes an input object and computes the corresponding output of the module
def forward(self, input): """ NB: It's for debug only, please use optimizer.optimize() in production. Takes an input object, and computes the corresponding output of the module :param input: ndarray or list of ndarray :param input: ndarray or list of ndarray or JTensor or list o...
NB: It s for debug only please use optimizer. optimize () in production. Performs a back - propagation step through the module with respect to the given input. In general this method makes the assumption forward ( input ) has been called before with the same input. This is necessary for optimization reasons. If you do ...
def backward(self, input, grad_output): """ NB: It's for debug only, please use optimizer.optimize() in production. Performs a back-propagation step through the module, with respect to the given input. In general this method makes the assumption forward(input) has been called before, wit...
Get the model parameters which containing: weight bias gradBias gradWeight
def parameters(self): """ Get the model parameters which containing: weight, bias, gradBias, gradWeight :return: dict(layername -> dict(parametername -> ndarray)) """ name_to_params = callBigDlFunc(self.bigdl_type, "modelGetParameters", ...
No argument passed in: Evaluate the model to set train = false useful when doing test/ forward: return: layer itself
def evaluate(self, *args): """ No argument passed in: Evaluate the model to set train = false, useful when doing test/forward :return: layer itself Three arguments passed in: A method to benchmark the model quality. :param dataset: the input data :param ...
: param X: X can be a ndarray or list of ndarray if the model has multiple inputs. The first dimension of X should be batch.: param batch_size: total batch size of prediction.: return: a ndarray as the prediction result.
def predict_local(self, X, batch_size = -1): """ :param X: X can be a ndarray or list of ndarray if the model has multiple inputs. The first dimension of X should be batch. :param batch_size: total batch size of prediction. :return: a ndarray as the prediction result. ...
Model inference base on the given data.: param features: it can be a ndarray or list of ndarray for locally inference or RDD [ Sample ] for running in distributed fashion: param batch_size: total batch size of prediction.: return: ndarray or RDD [ Sample ] depend on the the type of features.
def predict(self, features, batch_size = -1): """ Model inference base on the given data. :param features: it can be a ndarray or list of ndarray for locally inference or RDD[Sample] for running in distributed fashion :param batch_size: total batch size of predic...
Model inference base on the given data which returning label: param features: it can be a ndarray or list of ndarray for locally inference or RDD [ Sample ] for running in distributed fashion: return: ndarray or RDD [ Sample ] depend on the the type of features.
def predict_class(self, features): """ Model inference base on the given data which returning label :param features: it can be a ndarray or list of ndarray for locally inference or RDD[Sample] for running in distributed fashion :return: ndarray or RDD[Sample] dep...
Model inference base on the given data. You need to invoke collect () to trigger those action \ as the returning result is an RDD.
def predict_distributed(self, data_rdd, batch_size = -1): """ Model inference base on the given data. You need to invoke collect() to trigger those action \ as the returning result is an RDD. :param data_rdd: the data to be predict. :param batch_size: total batch size of...
module predict return the predict label
def predict_class_distributed(self, data_rdd): """ module predict, return the predict label :param data_rdd: the data to be predict. :return: An RDD represent the predict label. """ result = callBigDlFunc(self.bigdl_type, "modelPredictClass...
model predict images return imageFrame with predicted tensor: param image_frame imageFrame that contains images: param output_layer if output_layer is not null the output of layer that matches output_layer will be used as predicted output: param share_buffer whether to share same memory for each batch predict results: ...
def predict_image(self, image_frame, output_layer=None, share_buffer=False, batch_per_partition=4, predict_key="predict"): """ model predict images, return imageFrame with predicted tensor :param image_frame imageFrame that contains images :param output_layer if out...
Set weights for this layer
def set_weights(self, weights): """ Set weights for this layer :param weights: a list of numpy arrays which represent weight and bias :return: >>> linear = Linear(3,2) creating: createLinear >>> linear.set_weights([np.array([[1,2,3],[4,5,6]]), np.array([7,8])]) ...
Get weights for this layer
def get_weights(self): """ Get weights for this layer :return: list of numpy arrays which represent weight and bias """ tensorWeights = callBigDlFunc(self.bigdl_type, "getWeights", self.value) if tensorWeights is not None: return...
Save a model to protobuf files so that it can be used in tensorflow inference.
def save_tensorflow(self, inputs, path, byte_order="little_endian", data_format="nhwc"): """ Save a model to protobuf files so that it can be used in tensorflow inference. When saving the model, placeholders will be added to the tf model as input nodes. So you need to pass in the names ...