當前位置: 首頁>>代碼示例>>Python>>正文


Python tensorflow.tensor方法代碼示例

本文整理匯總了Python中tensorflow.tensor方法的典型用法代碼示例。如果您正苦於以下問題:Python tensorflow.tensor方法的具體用法?Python tensorflow.tensor怎麽用?Python tensorflow.tensor使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在tensorflow的用法示例。


在下文中一共展示了tensorflow.tensor方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: from_float32_to_uint8

# 需要導入模塊: import tensorflow [as 別名]
# 或者: from tensorflow import tensor [as 別名]
def from_float32_to_uint8(
        tensor,
        tensor_key='tensor',
        min_key='min',
        max_key='max'):
    """

    :param tensor:
    :param tensor_key:
    :param min_key:
    :param max_key:
    :returns:
    """
    tensor_min = tf.reduce_min(tensor)
    tensor_max = tf.reduce_max(tensor)
    return {
        tensor_key: tf.cast(
            (tensor - tensor_min) / (tensor_max - tensor_min + 1e-16)
            * 255.9999, dtype=tf.uint8),
        min_key: tensor_min,
        max_key: tensor_max
    } 
開發者ID:deezer,項目名稱:spleeter,代碼行數:24,代碼來源:tensor.py

示例2: check_tensor_shape

# 需要導入模塊: import tensorflow [as 別名]
# 或者: from tensorflow import tensor [as 別名]
def check_tensor_shape(tensor_tf, target_shape):
    """ Return a Tensorflow boolean graph that indicates whether
    sample[features_key] has the specified target shape. Only check
    not None entries of target_shape.

    :param tensor_tf: Tensor to check shape for.
    :param target_shape: Target shape to compare tensor to.
    :returns: True if shape is valid, False otherwise (as TF boolean).
    """
    result = tf.constant(True)
    for i, target_length in enumerate(target_shape):
        if target_length:
            result = tf.logical_and(
                result,
                tf.equal(tf.constant(target_length), tf.shape(tensor_tf)[i]))
    return result 
開發者ID:deezer,項目名稱:spleeter,代碼行數:18,代碼來源:tensor.py

示例3: call

# 需要導入模塊: import tensorflow [as 別名]
# 或者: from tensorflow import tensor [as 別名]
def call(self, inputs):
    """Invokes this layer.

    Parameters
    ----------
    inputs: list
      Should be of form `inputs=[coords, nbr_list]` where `coords` is a tensor of shape `(None, N, 3)` and `nbr_list` is a list.
    """
    if len(inputs) != 2:
      raise ValueError("InteratomicDistances requires coords,nbr_list")
    coords, nbr_list = (inputs[0], inputs[1])
    N_atoms, M_nbrs, ndim = self.N_atoms, self.M_nbrs, self.ndim
    # Shape (N_atoms, M_nbrs, ndim)
    nbr_coords = tf.gather(coords, nbr_list)
    # Shape (N_atoms, M_nbrs, ndim)
    tiled_coords = tf.tile(
        tf.reshape(coords, (N_atoms, 1, ndim)), (1, M_nbrs, 1))
    # Shape (N_atoms, M_nbrs)
    return tf.reduce_sum((tiled_coords - nbr_coords)**2, axis=2) 
開發者ID:deepchem,項目名稱:deepchem,代碼行數:21,代碼來源:layers.py

示例4: distance_matrix

# 需要導入模塊: import tensorflow [as 別名]
# 或者: from tensorflow import tensor [as 別名]
def distance_matrix(self, D):
    """Calcuates the distance matrix from the distance tensor

    B = batch_size, N = max_num_atoms, M = max_num_neighbors, d = num_features

    Parameters
    ----------
    D: tf.Tensor of shape (B, N, M, d)
      Distance tensor.

    Returns
    -------
    R: tf.Tensor of shape (B, N, M)
       Distance matrix.
    """
    R = tf.reduce_sum(tf.multiply(D, D), 3)
    R = tf.sqrt(R)
    return R 
開發者ID:deepchem,項目名稱:deepchem,代碼行數:20,代碼來源:layers.py

示例5: __init__

# 需要導入模塊: import tensorflow [as 別名]
# 或者: from tensorflow import tensor [as 別名]
def __init__(self, num_filters, **kwargs):
    """
    Parameters
    ----------
    num_filters: int
      Number of filters to have in the output

    in_layers: list of Layers or tensors
      [V, A, mask]
      V are the vertex features must be of shape (batch, vertex, channel)

      A are the adjacency matrixes for each graph
        Shape (batch, from_vertex, adj_matrix, to_vertex)

      mask is optional, to be used when not every graph has the
      same number of vertices

    Returns: tf.tensor
    Returns a tf.tensor with a graph convolution applied
    The shape will be (batch, vertex, self.num_filters)
    """
    super(GraphCNN, self).__init__(**kwargs)
    self.num_filters = num_filters 
開發者ID:deepchem,項目名稱:deepchem,代碼行數:25,代碼來源:layers.py

示例6: call

# 需要導入模塊: import tensorflow [as 別名]
# 或者: from tensorflow import tensor [as 別名]
def call(self, inputs, training=None):
        """
        :Note: Equivalent to __call__()
        :param inputs: Tensor to be applied
        :type inputs: tf.Tensor
        :return: Tensor after applying the layer which is just the original tensor
        :rtype: tf.Tensor
        """
        if self.always_on:
            return tf.stop_gradient(inputs)
        else:
            if training is None:
                training = tfk.backend.learning_phase()
            output_tensor = tf.where(tf.equal(training, True), tf.stop_gradient(inputs), inputs)
            output_tensor._uses_learning_phase = True
            return output_tensor 
開發者ID:henrysky,項目名稱:astroNN,代碼行數:18,代碼來源:layers.py

示例7: _deconvolution

# 需要導入模塊: import tensorflow [as 別名]
# 或者: from tensorflow import tensor [as 別名]
def _deconvolution(graph, sess, op_tensor, X, feed_dict):
    out = []
    with graph.as_default() as g:
        # get shape of tensor
        tensor_shape = op_tensor.get_shape().as_list()

        with sess.as_default() as sess:
            # creating placeholders to pass featuremaps and
            # creating gradient ops
            featuremap = [tf.placeholder(tf.int32) for i in range(config["N"])]
            reconstruct = [tf.gradients(tf.transpose(tf.transpose(op_tensor)[featuremap[i]]), X)[0] for i in range(config["N"])]

            # Execute the gradient operations in batches of 'n'
            for i in range(0, tensor_shape[-1], config["N"]):
                c = 0
                for j in range(config["N"]):
                    if (i + j) < tensor_shape[-1]:
                        feed_dict[featuremap[j]] = i + j
                        c += 1
                if c > 0:
                    out.extend(sess.run(reconstruct[:c], feed_dict = feed_dict))
    return out 
開發者ID:InFoCusp,項目名稱:tf_cnnvis,代碼行數:24,代碼來源:tf_cnnvis.py

示例8: shared

# 需要導入模塊: import tensorflow [as 別名]
# 或者: from tensorflow import tensor [as 別名]
def shared(self, in_layers):
    """
    Create a copy of this layer that shares variables with it.

    This is similar to clone(), but where clone() creates two independent layers,
    this causes the layers to share variables with each other.

    Parameters
    ----------
    in_layers: list tensor
    List in tensors for the shared layer

    Returns
    -------
    Layer
    """
    if self.variable_scope == '':
      return self.clone(in_layers)
    raise ValueError('%s does not implement shared()' % self.__class__.__name__) 
開發者ID:simonfqy,項目名稱:PADME,代碼行數:21,代碼來源:layers.py

示例9: set_summary

# 需要導入模塊: import tensorflow [as 別名]
# 或者: from tensorflow import tensor [as 別名]
def set_summary(self, summary_op, summary_description=None, collections=None):
    """Annotates a tensor with a tf.summary operation

    This causes self.out_tensor to be logged to Tensorboard.

    Parameters
    ----------
    summary_op: str
      summary operation to annotate node
    summary_description: object, optional
      Optional summary_pb2.SummaryDescription()
    collections: list of graph collections keys, optional
      New summary op is added to these collections. Defaults to [GraphKeys.SUMMARIES]
    """
    supported_ops = {'tensor_summary', 'scalar', 'histogram'}
    if summary_op not in supported_ops:
      raise ValueError(
          "Invalid summary_op arg. Only 'tensor_summary', 'scalar', 'histogram' supported"
      )
    self.summary_op = summary_op
    self.summary_description = summary_description
    self.collections = collections
    self.tensorboard = True 
開發者ID:simonfqy,項目名稱:PADME,代碼行數:25,代碼來源:layers.py

示例10: add_summary_to_tg

# 需要導入模塊: import tensorflow [as 別名]
# 或者: from tensorflow import tensor [as 別名]
def add_summary_to_tg(self, tb_input=None):
    """
    Create the summary operation for this layer, if set_summary() has been called on it.
    Can only be called after self.create_layer to gaurentee that name is not None.

    Parameters
    ----------
    tb_input: tensor
      the tensor to log to Tensorboard. If None, self.out_tensor is used.
    """
    if self.tensorboard == False:
      return
    if tb_input == None:
      tb_input = self.out_tensor
    if self.summary_op == "tensor_summary":
      tf.summary.tensor_summary(self.name, tb_input, self.summary_description, 
                                self.collections)
    elif self.summary_op == 'scalar':
      tf.summary.scalar(self.name, tb_input, self.collections)
    elif self.summary_op == 'histogram':
      tf.summary.histogram(self.name, tb_input, self.collections) 
開發者ID:simonfqy,項目名稱:PADME,代碼行數:23,代碼來源:layers.py

示例11: distance_matrix

# 需要導入模塊: import tensorflow [as 別名]
# 或者: from tensorflow import tensor [as 別名]
def distance_matrix(self, D):
    """Calcuates the distance matrix from the distance tensor

    B = batch_size, N = max_num_atoms, M = max_num_neighbors, d = num_features

    Parameters
    ----------
    D: tf.Tensor of shape (B, N, M, d)
      Distance tensor.

    Returns
    -------
    R: tf.Tensor of shape (B, N, M)
       Distance matrix.

    """

    R = tf.reduce_sum(tf.multiply(D, D), 3)
    R = tf.sqrt(R)
    return R 
開發者ID:simonfqy,項目名稱:PADME,代碼行數:22,代碼來源:layers.py

示例12: __init__

# 需要導入模塊: import tensorflow [as 別名]
# 或者: from tensorflow import tensor [as 別名]
def __init__(self, num_filters, **kwargs):
    """

    Parameters
    ----------
    num_filters: int
      Number of filters to have in the output

    in_layers: list of Layers or tensors
      [V, A, mask]
      V are the vertex features must be of shape (batch, vertex, channel)

      A are the adjacency matrixes for each graph
        Shape (batch, from_vertex, adj_matrix, to_vertex)

      mask is optional, to be used when not every graph has the
      same number of vertices

    Returns: tf.tensor
    Returns a tf.tensor with a graph convolution applied
    The shape will be (batch, vertex, self.num_filters)
    """
    self.num_filters = num_filters
    super(GraphCNN, self).__init__(**kwargs) 
開發者ID:simonfqy,項目名稱:PADME,代碼行數:26,代碼來源:layers.py

示例13: __dense_p

# 需要導入模塊: import tensorflow [as 別名]
# 或者: from tensorflow import tensor [as 別名]
def __dense_p(name, x, w=None, output_dim=128, initializer=tf.contrib.layers.xavier_initializer(), l2_strength=0.0,
              bias=0.0):
    """
    Fully connected layer
    :param name: (string) The name scope provided by the upper tf.name_scope('name') as scope.
    :param x: (tf.tensor) The input to the layer (N, D).
    :param output_dim: (integer) It specifies H, the output second dimension of the fully connected layer [ie:(N, H)]
    :param initializer: (tf.contrib initializer) The initialization scheme, He et al. normal or Xavier normal are recommended.
    :param l2_strength:(weight decay) (float) L2 regularization parameter.
    :param bias: (float) Amount of bias. (if not float, it means pretrained bias)
    :return out: The output of the layer. (N, H)
    """
    n_in = x.get_shape()[-1].value
    with tf.variable_scope(name):
        if w == None:
            w = __variable_with_weight_decay([n_in, output_dim], initializer, l2_strength)
        __variable_summaries(w)
        if isinstance(bias, float):
            bias = tf.get_variable("layer_biases", [output_dim], tf.float32, tf.constant_initializer(bias))
        __variable_summaries(bias)
        output = tf.nn.bias_add(tf.matmul(x, w), bias)
        return output 
開發者ID:MG2033,項目名稱:MobileNet,代碼行數:24,代碼來源:layers.py

示例14: avg_pool_2d

# 需要導入模塊: import tensorflow [as 別名]
# 或者: from tensorflow import tensor [as 別名]
def avg_pool_2d(x, size=(2, 2), stride=(2, 2), name='avg_pooling'):
    """
        Average pooling 2D Wrapper
        :param x: (tf.tensor) The input to the layer (N,H,W,C).
        :param size: (tuple) This specifies the size of the filter as well as the stride.
        :param name: (string) Scope name.
        :return: The output is the same input but halfed in both width and height (N,H/2,W/2,C).
    """
    size_x, size_y = size
    stride_x, stride_y = stride
    return tf.nn.avg_pool(x, ksize=[1, size_x, size_y, 1], strides=[1, stride_x, stride_y, 1], padding='VALID',
                          name=name)


############################################################################################################
# Utilities for layers 
開發者ID:MG2033,項目名稱:MobileNet,代碼行數:18,代碼來源:layers.py

示例15: _build

# 需要導入模塊: import tensorflow [as 別名]
# 或者: from tensorflow import tensor [as 別名]
def _build(self, obs_input, name=None):
        """Build model.

        Args:
            obs_input (tf.Tensor): Entire time-series observation input.
            name (str): Inner model name, also the variable scope of the
                inner model, if exist. One example is
                garage.tf.models.Sequential.

        Returns:
            tf.tensor: Mean.
            tf.Tensor: Log of standard deviation.
            garage.distributions.DiagonalGaussian: Distribution.

        """
        del name
        return_var = tf.compat.v1.get_variable(
            'return_var', (), initializer=tf.constant_initializer(0.5))
        mean = tf.fill((tf.shape(obs_input)[0], self.output_dim), return_var)
        log_std = tf.fill((tf.shape(obs_input)[0], self.output_dim),
                          np.log(0.5))
        dist = DiagonalGaussian(self.output_dim)
        # action will be 0.5 + 0.5 * 0.5 = 0.75
        return mean, log_std, dist 
開發者ID:rlworkgroup,項目名稱:garage,代碼行數:26,代碼來源:simple_gaussian_mlp_model.py


注:本文中的tensorflow.tensor方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。