当前位置: 首页>>代码示例>>Python>>正文


Python backend.random_uniform方法代码示例

本文整理汇总了Python中tensorflow.keras.backend.random_uniform方法的典型用法代码示例。如果您正苦于以下问题:Python backend.random_uniform方法的具体用法?Python backend.random_uniform怎么用?Python backend.random_uniform使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在tensorflow.keras.backend的用法示例。


在下文中一共展示了backend.random_uniform方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: loss

# 需要导入模块: from tensorflow.keras import backend [as 别名]
# 或者: from tensorflow.keras.backend import random_uniform [as 别名]
def loss(self, y_true, y_pred):

        # get the value for the true and fake images
        disc_true = self.disc(y_true)
        disc_pred = self.disc(y_pred)

        # sample a x_hat by sampling along the line between true and pred
        # z = tf.placeholder(tf.float32, shape=[None, 1])
        # shp = y_true.get_shape()[0]
        # WARNING: SHOULD REALLY BE shape=[batch_size, 1] !!!
        # self.batch_size does not work, since it's not None!!!
        alpha = K.random_uniform(shape=[K.shape(y_pred)[0], 1, 1, 1])
        diff = y_pred - y_true
        interp = y_true + alpha * diff

        # take gradient of D(x_hat)
        gradients = K.gradients(self.disc(interp), [interp])[0]
        grad_pen = K.mean(K.square(K.sqrt(K.sum(K.square(gradients), axis=1))-1))

        # compute loss
        return (K.mean(disc_pred) - K.mean(disc_true)) + self.lambda_gp * grad_pen 
开发者ID:adalca,项目名称:neuron,代码行数:23,代码来源:metrics.py

示例2: call

# 需要导入模块: from tensorflow.keras import backend [as 别名]
# 或者: from tensorflow.keras.backend import random_uniform [as 别名]
def call(self, inputs):
        # Implement Eq.(9)
        perturbed_kernel = self.kernel + \
            self.sigma_kernel * K.random_uniform(shape=self.kernel_shape)
        outputs = K.dot(inputs, perturbed_kernel)
        if self.use_bias:
            perturbed_bias = self.bias + \
                self.sigma_bias * K.random_uniform(shape=self.bias_shape)
            outputs = K.bias_add(outputs, perturbed_bias)
        if self.activation is not None:
            outputs = self.activation(outputs)
        return outputs 
开发者ID:keiohta,项目名称:tf2rl,代码行数:14,代码来源:noisy_dense.py

示例3: _generate_bert_mask

# 需要导入模块: from tensorflow.keras import backend [as 别名]
# 或者: from tensorflow.keras.backend import random_uniform [as 别名]
def _generate_bert_mask(self, inputs):
        mask_shape = K.shape(inputs)
        bert_mask = K.random_uniform(mask_shape) < self.percentage
        return bert_mask 
开发者ID:songlab-cal,项目名称:tape-neurips2019,代码行数:6,代码来源:RandomSequenceMask.py

示例4: call

# 需要导入模块: from tensorflow.keras import backend [as 别名]
# 或者: from tensorflow.keras.backend import random_uniform [as 别名]
def call(self,
             inputs: tf.Tensor,
             mask: Optional[tf.Tensor] = None):
        """
        Args:
            inputs (tf.Tensor[ndims=2, int]): Tensor of values to mask
            mask (Optional[tf.Tensor[bool]]): Locations in the inputs to that are valid
                                                     (i.e. not padding, start tokens, etc.)
        Returns:
            masked_inputs (tf.Tensor[ndims=2, int]): Tensor of masked values
            bert_mask: Locations in the input that were masked
        """

        bert_mask = self._generate_bert_mask(inputs)

        if mask is not None:
            bert_mask &= mask

        masked_inputs = inputs * tf.cast(~bert_mask, inputs.dtype)

        token_bert_mask = K.random_uniform(K.shape(bert_mask)) < 0.8
        random_bert_mask = (K.random_uniform(
            K.shape(bert_mask)) < 0.1) & ~token_bert_mask
        true_bert_mask = ~token_bert_mask & ~random_bert_mask

        token_bert_mask = tf.cast(token_bert_mask & bert_mask, inputs.dtype)
        random_bert_mask = tf.cast(random_bert_mask & bert_mask, inputs.dtype)
        true_bert_mask = tf.cast(true_bert_mask & bert_mask, inputs.dtype)

        masked_inputs += self.mask_token * token_bert_mask  # type: ignore

        masked_inputs += K.random_uniform(
            K.shape(bert_mask), 0, self.n_symbols, dtype=inputs.dtype) * random_bert_mask

        masked_inputs += inputs * true_bert_mask

        return masked_inputs, bert_mask 
开发者ID:songlab-cal,项目名称:tape-neurips2019,代码行数:39,代码来源:RandomSequenceMask.py

示例5: call

# 需要导入模块: from tensorflow.keras import backend [as 别名]
# 或者: from tensorflow.keras.backend import random_uniform [as 别名]
def call(self,
             inputs: tf.Tensor,
             mask: Optional[tf.Tensor] = None):
        """
        Args:
            inputs (tf.Tensor[ndims=2, int]): Tensor of values to mask
            mask (Optional[tf.Tensor[bool]]): Locations in the inputs to that are valid
                                                     (i.e. not padding, start tokens, etc.)
        Returns:
            masked_inputs (tf.Tensor[ndims=2, int]): Tensor of masked values
            bert_mask: Locations in the input that were masked
        """

        random_mask = self._generate_bert_mask(inputs)

        if mask is not None:
            random_mask &= mask

        masked_inputs = inputs * tf.cast(~random_mask, inputs.dtype)

        random_mask = tf.cast(random_mask, inputs.dtype)

        masked_inputs += K.random_uniform(
            K.shape(random_mask), 0, self.n_symbols, dtype=inputs.dtype) * random_mask

        return masked_inputs 
开发者ID:songlab-cal,项目名称:tape-neurips2019,代码行数:28,代码来源:BeplerModel.py

示例6: softmax_activation

# 需要导入模块: from tensorflow.keras import backend [as 别名]
# 或者: from tensorflow.keras.backend import random_uniform [as 别名]
def softmax_activation(mem):
        """Softmax activation."""

        return k.cast(k.less_equal(k.random_uniform(k.shape(mem)),
                                   k.softmax(mem)), k.floatx()) 
开发者ID:NeuromorphicProcessorProject,项目名称:snn_toolbox,代码行数:7,代码来源:ttfs.py

示例7: call

# 需要导入模块: from tensorflow.keras import backend [as 别名]
# 或者: from tensorflow.keras.backend import random_uniform [as 别名]
def call(self, inputs):
        if self.n_dims == 2:
            rand_flow = K.random_uniform(
                shape=tf.convert_to_tensor(
                    [tf.shape(inputs)[0], tf.shape(inputs)[1], tf.shape(inputs)[2], self.n_dims]),
                minval=-self.flow_amp,
                maxval=self.flow_amp, dtype='float32')
            rand_flow = tf.nn.depthwise_conv2d(rand_flow, self.blur_kernel, strides=[1] * (self.n_dims + 2),
                                               padding='SAME')
        elif self.n_dims == 3:
            rand_flow = K.random_uniform(
                shape=tf.convert_to_tensor(
                    [tf.shape(inputs)[0], tf.shape(inputs)[1], tf.shape(inputs)[2], tf.shape(inputs)[3], self.n_dims]),
                minval=-self.flow_amp,
                maxval=self.flow_amp, dtype='float32')

            # blur it here, then again later?
            rand_flow_list = tf.unstack(rand_flow, num=self.n_dims, axis=-1)
            flow_chans = []
            for c in range(self.n_dims):
                flow_chan = tf.nn.conv3d(tf.expand_dims(rand_flow_list[c], axis=-1), self.blur_kernel,
                                         strides=[1] * (self.n_dims + 2), padding='SAME')
                flow_chans.append(flow_chan[:, :, :, :, 0])
            rand_flow = tf.stack(flow_chans, axis=-1)
        rand_flow = tf.reshape(rand_flow, [-1] + list(self.flow_shape))
        return rand_flow 
开发者ID:xamyzhao,项目名称:brainstorm,代码行数:28,代码来源:networks.py

示例8: init_membrane_potential

# 需要导入模块: from tensorflow.keras import backend [as 别名]
# 或者: from tensorflow.keras.backend import random_uniform [as 别名]
def init_membrane_potential(self, output_shape=None, mode='zero'):
        """Initialize membrane potential.

        Helpful to avoid transient response in the beginning of the simulation.
        Not needed when reset between frames is turned off, e.g. with a video
        data set.

        Parameters
        ----------

        output_shape: Optional[tuple]
            Output shape
        mode: str
            Initialization mode.

            - ``'uniform'``: Random numbers from uniform distribution in
              ``[-thr, thr]``.
            - ``'bias'``: Negative bias.
            - ``'zero'``: Zero (default).

        Returns
        -------

        init_mem: ndarray
            A tensor of ``self.output_shape`` (same as layer).
        """

        if output_shape is None:
            output_shape = self.output_shape

        if mode == 'uniform':
            init_mem = k.random_uniform(output_shape,
                                        -self._v_thresh, self._v_thresh)
        elif mode == 'bias':
            init_mem = np.zeros(output_shape, k.floatx())
            if hasattr(self, 'bias'):
                bias = self.get_weights()[1]
                for i in range(len(bias)):
                    # Todo: This assumes data_format = 'channels_first'
                    init_mem[:, i, Ellipsis] = bias[i]
                self.add_update([(self.bias, np.zeros_like(bias))])
        else:  # mode == 'zero':
            init_mem = np.zeros(output_shape, k.floatx())
        return init_mem 
开发者ID:NeuromorphicProcessorProject,项目名称:snn_toolbox,代码行数:46,代码来源:ttfs.py

示例9: init_membrane_potential

# 需要导入模块: from tensorflow.keras import backend [as 别名]
# 或者: from tensorflow.keras.backend import random_uniform [as 别名]
def init_membrane_potential(self, output_shape=None, mode='zero'):
        """Initialize membrane potential.

        Helpful to avoid transient response in the beginning of the simulation.
        Not needed when reset between frames is turned off, e.g. with a video
        data set.

        Parameters
        ----------

        output_shape: Optional[tuple]
            Output shape
        mode: str
            Initialization mode.

            - ``'uniform'``: Random numbers from uniform distribution in
              ``[-thr, thr]``.
            - ``'bias'``: Negative bias.
            - ``'zero'``: Zero (default).

        Returns
        -------

        init_mem: ndarray
            A tensor of ``self.output_shape`` (same as layer).
        """

        if output_shape is None:
            output_shape = self.output_shape

        if mode == 'uniform':
            init_mem = k.random_uniform(output_shape,
                                        -self._v_thresh, self._v_thresh)
        elif mode == 'bias':
            init_mem = np.zeros(output_shape, k.floatx())
            if hasattr(self, 'b'):
                b = self.get_weights()[1]
                for i in range(len(b)):
                    init_mem[:, i, Ellipsis] = -b[i]
        else:  # mode == 'zero':
            init_mem = np.zeros(output_shape, k.floatx())
        return init_mem 
开发者ID:NeuromorphicProcessorProject,项目名称:snn_toolbox,代码行数:44,代码来源:ttfs_dyn_thresh.py


注:本文中的tensorflow.keras.backend.random_uniform方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。