本文整理汇总了Python中tensorflow.keras.backend.zeros方法的典型用法代码示例。如果您正苦于以下问题:Python backend.zeros方法的具体用法?Python backend.zeros怎么用?Python backend.zeros使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tensorflow.keras.backend
的用法示例。
在下文中一共展示了backend.zeros方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: build
# 需要导入模块: from tensorflow.keras import backend [as 别名]
# 或者: from tensorflow.keras.backend import zeros [as 别名]
def build(self, input_shape):
# Generate the nb_affine weights and biases
num_deg = 2 * self.max_degree + (1 - self.min_degree)
self.W_list = [
self.add_weight(
name='kernel',
shape=(int(input_shape[0][-1]), self.out_channel),
initializer='glorot_uniform',
trainable=True) for k in range(num_deg)
]
self.b_list = [
self.add_weight(
name='bias',
shape=(self.out_channel,),
initializer='zeros',
trainable=True) for k in range(num_deg)
]
self.built = True
示例2: __init__
# 需要导入模块: from tensorflow.keras import backend [as 别名]
# 或者: from tensorflow.keras.backend import zeros [as 别名]
def __init__(self,
activation_fn='relu',
biases_initializer='zeros',
weights_initializer=None,
**kwargs):
"""
Parameters
----------
activation_fn: object
the Tensorflow activation function to apply to the output
biases_initializer: callable object
the initializer for bias values. This may be None, in which case the layer
will not include biases.
weights_initializer: callable object
the initializer for weight values
"""
super(Highway, self).__init__(**kwargs)
self.activation_fn = activation_fn
self.biases_initializer = biases_initializer
self.weights_initializer = weights_initializer
示例3: _single_batch_trf
# 需要导入模块: from tensorflow.keras import backend [as 别名]
# 或者: from tensorflow.keras.backend import zeros [as 别名]
def _single_batch_trf(self, vol):
# vol should be vol_shape + [nb_features]
# self.trf should be vol_shape + [nb_features] + [ndims]
vol_shape = vol.shape.as_list()
nb_input_dims = vol_shape[-1]
# this is inefficient...
new_vols = [None] * self.output_features
for j in range(self.output_features):
new_vols[j] = tf.zeros(vol_shape[:-1], dtype=tf.float32)
for i in range(nb_input_dims):
trf_vol = transform(vol[..., i], self.trf[..., i, j, :] * self.trf_mult, interp_method=self.interp_method)
trf_vol = tf.reshape(trf_vol, vol_shape[:-1])
new_vols[j] += trf_vol * self.mult[..., i, j]
if self.use_bias:
new_vols[j] += self.bias[..., j]
return tf.stack(new_vols, -1)
示例4: build
# 需要导入模块: from tensorflow.keras import backend [as 别名]
# 或者: from tensorflow.keras.backend import zeros [as 别名]
def build(self, input_shape):
# Create mean and count
# These are weights because just maintaining variables don't get saved with the model, and we'd like
# to have these numbers saved when we save the model.
# But we need to make sure that the weights are untrainable.
self.mean = self.add_weight(name='mean',
shape=input_shape[1:],
initializer='zeros',
trainable=False)
self.count = self.add_weight(name='count',
shape=[1],
initializer='zeros',
trainable=False)
# self.mean = K.zeros(input_shape[1:], name='mean')
# self.count = K.variable(0.0, name='count')
super(MeanStream, self).build(input_shape) # Be sure to call this somewhere!
示例5: reset_spikevars
# 需要导入模块: from tensorflow.keras import backend [as 别名]
# 或者: from tensorflow.keras.backend import zeros [as 别名]
def reset_spikevars(self, sample_idx):
"""
Reset variables present in spiking layers. Can be turned off for
instance when a video sequence is tested.
"""
mod = self.config.getint('simulation', 'reset_between_nth_sample')
mod = mod if mod else sample_idx + 1
do_reset = sample_idx % mod == 0
if do_reset:
k.set_value(self.mem, self.init_membrane_potential())
k.set_value(self.time, np.float32(self.dt))
zeros_output_shape = np.zeros(self.output_shape, k.floatx())
if self.tau_refrac > 0:
k.set_value(self.refrac_until, zeros_output_shape)
if self.spiketrain is not None:
k.set_value(self.spiketrain, zeros_output_shape)
k.set_value(self.last_spiketimes, zeros_output_shape - 1)
示例6: init_neurons
# 需要导入模块: from tensorflow.keras import backend [as 别名]
# 或者: from tensorflow.keras.backend import zeros [as 别名]
def init_neurons(self, input_shape):
"""Init layer neurons."""
from snntoolbox.bin.utils import get_log_keys, get_plot_keys
output_shape = self.compute_output_shape(input_shape)
self.v_thresh = k.variable(self._v_thresh)
self.mem = k.variable(self.init_membrane_potential(output_shape))
self.time = k.variable(self.dt)
# To save memory and computations, allocate only where needed:
if self.tau_refrac > 0:
self.refrac_until = k.zeros(output_shape)
if any({'spiketrains', 'spikerates', 'correlation', 'spikecounts',
'hist_spikerates_activations', 'operations',
'synaptic_operations_b_t', 'neuron_operations_b_t',
'spiketrains_n_b_l_t'} & (get_plot_keys(self.config) |
get_log_keys(self.config))):
self.spiketrain = k.zeros(output_shape)
self.last_spiketimes = k.variable(-np.ones(output_shape))
示例7: reset_spikevars
# 需要导入模块: from tensorflow.keras import backend [as 别名]
# 或者: from tensorflow.keras.backend import zeros [as 别名]
def reset_spikevars(self, sample_idx):
"""
Reset variables present in spiking layers. Can be turned off for
instance when a video sequence is tested.
"""
mod = self.config.getint('simulation', 'reset_between_nth_sample')
mod = mod if mod else sample_idx + 1
do_reset = sample_idx % mod == 0
if do_reset:
k.set_value(self.mem, self.init_membrane_potential())
k.set_value(self.time, np.float32(self.dt))
zeros_output_shape = np.zeros(self.output_shape, k.floatx())
if self.tau_refrac > 0:
k.set_value(self.refrac_until, zeros_output_shape)
if self.spiketrain is not None:
k.set_value(self.spiketrain, zeros_output_shape)
k.set_value(self.last_spiketimes, zeros_output_shape - 1)
k.set_value(self.v_thresh, zeros_output_shape + self._v_thresh)
k.set_value(self.prospective_spikes, zeros_output_shape)
k.set_value(self.missing_impulse, zeros_output_shape)
示例8: reset_spikevars
# 需要导入模块: from tensorflow.keras import backend [as 别名]
# 或者: from tensorflow.keras.backend import zeros [as 别名]
def reset_spikevars(self, sample_idx):
"""
Reset variables present in spiking layers. Can be turned off for
instance when a video sequence is tested.
"""
mod = self.config.getint('simulation', 'reset_between_nth_sample')
mod = mod if mod else sample_idx + 1
do_reset = sample_idx % mod == 0
if do_reset:
k.set_value(self.mem, self.init_membrane_potential())
k.set_value(self.time, np.float32(self.dt))
zeros_output_shape = np.zeros(self.output_shape, k.floatx())
if self.spiketrain is not None:
k.set_value(self.spiketrain, zeros_output_shape)
k.set_value(self.last_spiketimes, zeros_output_shape - 1)
示例9: rel_to_abs
# 需要导入模块: from tensorflow.keras import backend [as 别名]
# 或者: from tensorflow.keras.backend import zeros [as 别名]
def rel_to_abs(self, x):
shape = K.shape(x)
shape = [shape[i] for i in range(3)]
B, Nh, L, = shape
col_pad = K.zeros(K.stack([B, Nh, L, 1]))
x = K.concatenate([x, col_pad], axis=3)
flat_x = K.reshape(x, [B, Nh, L * 2 * L])
flat_pad = K.zeros(K.stack([B, Nh, L - 1]))
flat_x_padded = K.concatenate([flat_x, flat_pad], axis=2)
final_x = K.reshape(flat_x_padded, [B, Nh, L + 1, 2 * L - 1])
final_x = final_x[:, :, :L, L - 1:]
return final_x
示例10: call
# 需要导入模块: from tensorflow.keras import backend [as 别名]
# 或者: from tensorflow.keras.backend import zeros [as 别名]
def call(self, inputs):
atom_features = inputs[0]
deg_slice = inputs[1]
deg_adj_lists = inputs[3:]
# Perform the mol gather
# atom_features = graph_pool(atom_features, deg_adj_lists, deg_slice,
# self.max_degree, self.min_degree)
deg_maxed = (self.max_degree + 1 - self.min_degree) * [None]
# Tensorflow correctly processes empty lists when using concat
split_features = tf.split(atom_features, deg_slice[:, 1])
for deg in range(1, self.max_degree + 1):
# Get self atoms
self_atoms = split_features[deg - self.min_degree]
if deg_adj_lists[deg - 1].shape[0] == 0:
# There are no neighbors of this degree, so just create an empty tensor directly.
maxed_atoms = tf.zeros((0, self_atoms.shape[-1]))
else:
# Expand dims
self_atoms = tf.expand_dims(self_atoms, 1)
# always deg-1 for deg_adj_lists
gathered_atoms = tf.gather(atom_features, deg_adj_lists[deg - 1])
gathered_atoms = tf.concat(axis=1, values=[self_atoms, gathered_atoms])
maxed_atoms = tf.reduce_max(gathered_atoms, 1)
deg_maxed[deg - self.min_degree] = maxed_atoms
if self.min_degree == 0:
self_atoms = split_features[0]
deg_maxed[0] = self_atoms
return tf.concat(axis=0, values=deg_maxed)
示例11: get_initial_states
# 需要导入模块: from tensorflow.keras import backend [as 别名]
# 或者: from tensorflow.keras.backend import zeros [as 别名]
def get_initial_states(self, input_shape):
return [backend.zeros(input_shape), backend.zeros(input_shape)]
示例12: __init__
# 需要导入模块: from tensorflow.keras import backend [as 别名]
# 或者: from tensorflow.keras.backend import zeros [as 别名]
def __init__(self, filters,
kernel_size,
strides=(1, 1, 1),
padding='valid',
data_format=None,
activation=None,
use_bias=True,
kernel_initializer='glorot_uniform',
bias_initializer='zeros',
kernel_regularizer=None,
bias_regularizer=None,
activity_regularizer=None,
kernel_constraint=None,
bias_constraint=None,
**kwargs):
super(LocallyConnected3D, self).__init__(**kwargs)
self.filters = filters
self.kernel_size = conv_utils.normalize_tuple(
kernel_size, 3, 'kernel_size')
self.strides = conv_utils.normalize_tuple(strides, 3, 'strides')
self.padding = conv_utils.normalize_padding(padding)
if self.padding != 'valid':
raise ValueError('Invalid border mode for LocallyConnected3D '
'(only "valid" is supported): ' + padding)
self.data_format = conv_utils.normalize_data_format(data_format)
self.activation = activations.get(activation)
self.use_bias = use_bias
self.kernel_initializer = initializers.get(kernel_initializer)
self.bias_initializer = initializers.get(bias_initializer)
self.kernel_regularizer = regularizers.get(kernel_regularizer)
self.bias_regularizer = regularizers.get(bias_regularizer)
self.activity_regularizer = regularizers.get(activity_regularizer)
self.kernel_constraint = constraints.get(kernel_constraint)
self.bias_constraint = constraints.get(bias_constraint)
self.input_spec = InputSpec(ndim=5)
示例13: init_neurons
# 需要导入模块: from tensorflow.keras import backend [as 别名]
# 或者: from tensorflow.keras.backend import zeros [as 别名]
def init_neurons(self, input_shape):
"""Init layer neurons."""
from snntoolbox.bin.utils import get_log_keys, get_plot_keys
output_shape = self.compute_output_shape(input_shape)
self.mem = k.variable(self.init_membrane_potential(output_shape))
self.time = k.variable(self.dt)
if any({'spiketrains', 'spikerates', 'correlation', 'spikecounts',
'hist_spikerates_activations', 'operations',
'synaptic_operations_b_t', 'neuron_operations_b_t',
'spiketrains_n_b_l_t'} & (get_plot_keys(self.config) |
get_log_keys(self.config))):
self.spiketrain = k.zeros(output_shape)
self.last_spiketimes = k.variable(-np.ones(output_shape))
示例14: init_membrane_potential
# 需要导入模块: from tensorflow.keras import backend [as 别名]
# 或者: from tensorflow.keras.backend import zeros [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
示例15: init_membrane_potential
# 需要导入模块: from tensorflow.keras import backend [as 别名]
# 或者: from tensorflow.keras.backend import zeros [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