本文整理汇总了Python中tensorflow.float32方法的典型用法代码示例。如果您正苦于以下问题:Python tensorflow.float32方法的具体用法?Python tensorflow.float32怎么用?Python tensorflow.float32使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tensorflow
的用法示例。
在下文中一共展示了tensorflow.float32方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: stackedRNN
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import float32 [as 别名]
def stackedRNN(self, x, dropout, scope, embedding_size, sequence_length, hidden_units):
n_hidden=hidden_units
n_layers=3
# Prepare data shape to match `static_rnn` function requirements
x = tf.unstack(tf.transpose(x, perm=[1, 0, 2]))
# print(x)
# Define lstm cells with tensorflow
# Forward direction cell
with tf.name_scope("fw"+scope),tf.variable_scope("fw"+scope):
stacked_rnn_fw = []
for _ in range(n_layers):
fw_cell = tf.nn.rnn_cell.BasicLSTMCell(n_hidden, forget_bias=1.0, state_is_tuple=True)
lstm_fw_cell = tf.contrib.rnn.DropoutWrapper(fw_cell,output_keep_prob=dropout)
stacked_rnn_fw.append(lstm_fw_cell)
lstm_fw_cell_m = tf.nn.rnn_cell.MultiRNNCell(cells=stacked_rnn_fw, state_is_tuple=True)
outputs, _ = tf.nn.static_rnn(lstm_fw_cell_m, x, dtype=tf.float32)
return outputs[-1]
示例2: wrap_variable
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import float32 [as 别名]
def wrap_variable(self, var):
"""wrap layer.w into variables"""
val = self.lay.w.get(var, None)
if val is None:
shape = self.lay.wshape[var]
args = [0., 1e-2, shape]
if 'moving_mean' in var:
val = np.zeros(shape)
elif 'moving_variance' in var:
val = np.ones(shape)
else:
val = np.random.normal(*args)
self.lay.w[var] = val.astype(np.float32)
self.act = 'Init '
if not self.var: return
val = self.lay.w[var]
self.lay.w[var] = tf.constant_initializer(val)
if var in self._SLIM: return
with tf.variable_scope(self.scope):
self.lay.w[var] = tf.get_variable(var,
shape = self.lay.wshape[var],
dtype = tf.float32,
initializer = self.lay.w[var])
示例3: call
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import float32 [as 别名]
def call(self, x):
if (self.size == None) or (self.mode == 'sum'):
self.size = int(x.shape[-1])
position_j = 1. / \
K.pow(10000., 2 * K.arange(self.size / 2, dtype='float32') / self.size)
position_j = K.expand_dims(position_j, 0)
position_i = tf.cumsum(K.ones_like(x[:, :, 0]), 1) - 1
position_i = K.expand_dims(position_i, 2)
position_ij = K.dot(position_i, position_j)
outputs = K.concatenate(
[K.cos(position_ij), K.sin(position_ij)], 2)
if self.mode == 'sum':
if self.scale:
outputs = outputs * outputs ** 0.5
return x + outputs
elif self.mode == 'concat':
return K.concatenate([outputs, x], 2)
示例4: _build_input
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import float32 [as 别名]
def _build_input(self):
self.tails = tf.placeholder(tf.int32, [None])
self.heads = tf.placeholder(tf.int32, [None])
self.targets = tf.one_hot(indices=self.heads, depth=self.num_entity)
if not self.query_is_language:
self.queries = tf.placeholder(tf.int32, [None, self.num_step])
self.query_embedding_params = tf.Variable(self._random_uniform_unit(
self.num_query + 1, # <END> token
self.query_embed_size),
dtype=tf.float32)
rnn_inputs = tf.nn.embedding_lookup(self.query_embedding_params,
self.queries)
else:
self.queries = tf.placeholder(tf.int32, [None, self.num_step, self.num_word])
self.vocab_embedding_params = tf.Variable(self._random_uniform_unit(
self.num_vocab + 1, # <END> token
self.vocab_embed_size),
dtype=tf.float32)
embedded_query = tf.nn.embedding_lookup(self.vocab_embedding_params,
self.queries)
rnn_inputs = tf.reduce_mean(embedded_query, axis=2)
return rnn_inputs
示例5: noise_input_fn
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import float32 [as 别名]
def noise_input_fn(params):
"""Input function for generating samples for PREDICT mode.
Generates a single Tensor of fixed random noise. Use tf.data.Dataset to
signal to the estimator when to terminate the generator returned by
predict().
Args:
params: param `dict` passed by TPUEstimator.
Returns:
1-element `dict` containing the randomly generated noise.
"""
# random noise
np.random.seed(0)
noise_dataset = tf.data.Dataset.from_tensors(tf.constant(
np.random.randn(params['batch_size'], FLAGS.noise_dim), dtype=tf.float32))
noise = noise_dataset.make_one_shot_iterator().get_next()
return {'random_noise': noise}, None
示例6: _mapper
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import float32 [as 别名]
def _mapper(example_proto):
features = {
'samples': tf.FixedLenSequenceFeature([1], tf.float32, allow_missing=True),
'label': tf.FixedLenSequenceFeature([], tf.string, allow_missing=True)
}
example = tf.parse_single_example(example_proto, features)
wav = example['samples'][:, 0]
wav = wav[:16384]
wav_len = tf.shape(wav)[0]
wav = tf.pad(wav, [[0, 16384 - wav_len]])
label = tf.reduce_join(example['label'], 0)
return wav, label
示例7: autosummary
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import float32 [as 别名]
def autosummary(name, value):
id = name.replace('/', '_')
if is_tf_expression(value):
with tf.name_scope('summary_' + id), tf.device(value.device):
update_op = _create_autosummary_var(name, value)
with tf.control_dependencies([update_op]):
return tf.identity(value)
else: # python scalar or numpy array
if name not in _autosummary_immediate:
with absolute_name_scope('Autosummary/' + id), tf.device(None), tf.control_dependencies(None):
update_value = tf.placeholder(tf.float32)
update_op = _create_autosummary_var(name, update_value)
_autosummary_immediate[name] = update_op, update_value
update_op, update_value = _autosummary_immediate[name]
run(update_op, {update_value: np.float32(value)})
return value
# Create the necessary ops to include autosummaries in TensorBoard report.
# Note: This should be done only once per graph.
示例8: _create_autosummary_var
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import float32 [as 别名]
def _create_autosummary_var(name, value_expr):
assert not _autosummary_finalized
v = tf.cast(value_expr, tf.float32)
if v.shape.ndims is 0:
v = [v, np.float32(1.0)]
elif v.shape.ndims is 1:
v = [tf.reduce_sum(v), tf.cast(tf.shape(v)[0], tf.float32)]
else:
v = [tf.reduce_sum(v), tf.reduce_prod(tf.cast(tf.shape(v), tf.float32))]
v = tf.cond(tf.is_finite(v[0]), lambda: tf.stack(v), lambda: tf.zeros(2))
with tf.control_dependencies(None):
var = tf.Variable(tf.zeros(2)) # [numerator, denominator]
update_op = tf.cond(tf.is_variable_initialized(var), lambda: tf.assign_add(var, v), lambda: tf.assign(var, v))
if name in _autosummary_vars:
_autosummary_vars[name].append(var)
else:
_autosummary_vars[name] = [var]
return update_op
#----------------------------------------------------------------------------
# Call filewriter.add_summary() with all summaries in the default graph,
# automatically finalizing and merging them on the first call.
示例9: minibatch_stddev_layer
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import float32 [as 别名]
def minibatch_stddev_layer(x, group_size=4):
with tf.variable_scope('MinibatchStddev'):
group_size = tf.minimum(group_size, tf.shape(x)[0]) # Minibatch must be divisible by (or smaller than) group_size.
s = x.shape # [NCHW] Input shape.
y = tf.reshape(x, [group_size, -1, s[1], s[2], s[3]]) # [GMCHW] Split minibatch into M groups of size G.
y = tf.cast(y, tf.float32) # [GMCHW] Cast to FP32.
y -= tf.reduce_mean(y, axis=0, keep_dims=True) # [GMCHW] Subtract mean over group.
y = tf.reduce_mean(tf.square(y), axis=0) # [MCHW] Calc variance over group.
y = tf.sqrt(y + 1e-8) # [MCHW] Calc stddev over group.
y = tf.reduce_mean(y, axis=[1,2,3], keep_dims=True) # [M111] Take average over fmaps and pixels.
y = tf.cast(y, x.dtype) # [M111] Cast back to original data type.
y = tf.tile(y, [group_size, 1, s[2], s[3]]) # [N1HW] Replicate over group and pixels.
return tf.concat([x, y], axis=1) # [NCHW] Append as new fmap.
#----------------------------------------------------------------------------
# Generator network used in the paper.
示例10: __init__
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import float32 [as 别名]
def __init__(self, resolution=1024, num_channels=3, dtype='uint8', dynamic_range=[0,255], label_size=0, label_dtype='float32'):
self.resolution = resolution
self.resolution_log2 = int(np.log2(resolution))
self.shape = [num_channels, resolution, resolution]
self.dtype = dtype
self.dynamic_range = dynamic_range
self.label_size = label_size
self.label_dtype = label_dtype
self._tf_minibatch_var = None
self._tf_lod_var = None
self._tf_minibatch_np = None
self._tf_labels_np = None
assert self.resolution == 2 ** self.resolution_log2
with tf.name_scope('Dataset'):
self._tf_minibatch_var = tf.Variable(np.int32(0), name='minibatch_var')
self._tf_lod_var = tf.Variable(np.int32(0), name='lod_var')
示例11: validate_on_lfw
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import float32 [as 别名]
def validate_on_lfw(model, lfw_160_path):
# Read the file containing the pairs used for testing
pairs = lfw.read_pairs('validation-LFW-pairs.txt')
# Get the paths for the corresponding images
paths, actual_issame = lfw.get_paths(lfw_160_path, pairs)
num_pairs = len(actual_issame)
all_embeddings = np.zeros((num_pairs * 2, 512), dtype='float32')
for k in tqdm.trange(num_pairs):
img1 = cv2.imread(paths[k * 2], cv2.IMREAD_COLOR)[:, :, ::-1]
img2 = cv2.imread(paths[k * 2 + 1], cv2.IMREAD_COLOR)[:, :, ::-1]
batch = np.stack([img1, img2], axis=0)
embeddings = model.eval_embeddings(batch)
all_embeddings[k * 2: k * 2 + 2, :] = embeddings
tpr, fpr, accuracy, val, val_std, far = lfw.evaluate(
all_embeddings, actual_issame, distance_metric=1, subtract_mean=True)
print('Accuracy: %2.5f+-%2.5f' % (np.mean(accuracy), np.std(accuracy)))
print('Validation rate: %2.5f+-%2.5f @ FAR=%2.5f' % (val, val_std, far))
auc = metrics.auc(fpr, tpr)
print('Area Under Curve (AUC): %1.3f' % auc)
eer = brentq(lambda x: 1. - x - interpolate.interp1d(fpr, tpr)(x), 0., 1.)
print('Equal Error Rate (EER): %1.3f' % eer)
示例12: test_generate_np_caches_graph_computation_for_eps_clip_or_xi
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import float32 [as 别名]
def test_generate_np_caches_graph_computation_for_eps_clip_or_xi(self):
x_val = np.random.rand(1, 2)
x_val = np.array(x_val, dtype=np.float32)
self.attack.generate_np(x_val, eps=.3, num_iterations=10,
clip_max=-5.0, clip_min=-5.0,
xi=1e-6)
old_grads = tf.gradients
def fn(*x, **y):
raise RuntimeError()
tf.gradients = fn
self.attack.generate_np(x_val, eps=.2, num_iterations=10,
clip_max=-4.0, clip_min=-4.0,
xi=1e-5)
tf.gradients = old_grads
示例13: test_attack_strength
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import float32 [as 别名]
def test_attack_strength(self):
"""
If clipping is not done at each iteration (not passing clip_min and
clip_max to fgm), this attack fails by
np.mean(orig_labels == new_labels) == .39.
"""
x_val = np.random.rand(100, 2)
x_val = np.array(x_val, dtype=np.float32)
x_adv = self.attack.generate_np(x_val, eps=1.0, ord=np.inf,
clip_min=0.5, clip_max=0.7,
nb_iter=5)
orig_labs = np.argmax(self.sess.run(self.model(x_val)), axis=1)
new_labs = np.argmax(self.sess.run(self.model(x_adv)), axis=1)
self.assertTrue(np.mean(orig_labs == new_labs) < 0.1)
示例14: test_generate_np_targeted_gives_adversarial_example
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import float32 [as 别名]
def test_generate_np_targeted_gives_adversarial_example(self):
x_val = np.random.rand(100, 2)
x_val = np.array(x_val, dtype=np.float32)
feed_labs = np.zeros((100, 2))
feed_labs[np.arange(100), np.random.randint(0, 1, 100)] = 1
x_adv = self.attack.generate_np(x_val, max_iterations=100,
binary_search_steps=3,
initial_const=1,
clip_min=-5, clip_max=5,
batch_size=100, y_target=feed_labs)
new_labs = np.argmax(self.sess.run(self.model(x_adv)), axis=1)
self.assertTrue(np.mean(np.argmax(feed_labs, axis=1) == new_labs)
> 0.9)
示例15: test_generate_gives_adversarial_example
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import float32 [as 别名]
def test_generate_gives_adversarial_example(self):
x_val = np.random.rand(100, 2)
x_val = np.array(x_val, dtype=np.float32)
orig_labs = np.argmax(self.sess.run(self.model(x_val)), axis=1)
feed_labs = np.zeros((100, 2))
feed_labs[np.arange(100), orig_labs] = 1
x = tf.placeholder(tf.float32, x_val.shape)
y = tf.placeholder(tf.float32, feed_labs.shape)
x_adv_p = self.attack.generate(x, max_iterations=100,
binary_search_steps=3,
initial_const=1,
clip_min=-5, clip_max=5,
batch_size=100, y=y)
self.assertEqual(x_val.shape, x_adv_p.shape)
x_adv = self.sess.run(x_adv_p, {x: x_val, y: feed_labs})
new_labs = np.argmax(self.sess.run(self.model(x_adv)), axis=1)
self.assertTrue(np.mean(orig_labs == new_labs) < 0.1)