本文整理汇总了Python中tensorflow.transpose方法的典型用法代码示例。如果您正苦于以下问题:Python tensorflow.transpose方法的具体用法?Python tensorflow.transpose怎么用?Python tensorflow.transpose使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类tensorflow
的用法示例。
在下文中一共展示了tensorflow.transpose方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: train_lr_rfeinman
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import transpose [as 别名]
def train_lr_rfeinman(densities_pos, densities_neg, uncerts_pos, uncerts_neg):
"""
TODO
:param densities_pos:
:param densities_neg:
:param uncerts_pos:
:param uncerts_neg:
:return:
"""
values_neg = np.concatenate(
(densities_neg.reshape((1, -1)),
uncerts_neg.reshape((1, -1))),
axis=0).transpose([1, 0])
values_pos = np.concatenate(
(densities_pos.reshape((1, -1)),
uncerts_pos.reshape((1, -1))),
axis=0).transpose([1, 0])
values = np.concatenate((values_neg, values_pos))
labels = np.concatenate(
(np.zeros_like(densities_neg), np.ones_like(densities_pos)))
lr = LogisticRegressionCV(n_jobs=-1).fit(values, labels)
return values, labels, lr
示例2: _build_stft_feature
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import transpose [as 别名]
def _build_stft_feature(self):
""" Compute STFT of waveform and slice the STFT in segment
with the right length to feed the network.
"""
stft_name = self.stft_name
spec_name = self.spectrogram_name
if stft_name not in self._features:
stft_feature = tf.transpose(
stft(
tf.transpose(self._features['waveform']),
self._frame_length,
self._frame_step,
window_fn=lambda frame_length, dtype: (
hann_window(frame_length, periodic=True, dtype=dtype)),
pad_end=True),
perm=[1, 2, 0])
self._features[f'{self._mix_name}_stft'] = stft_feature
if spec_name not in self._features:
self._features[spec_name] = tf.abs(
pad_and_partition(self._features[stft_name], self._T))[:, :, :self._F, :]
示例3: _inverse_stft
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import transpose [as 别名]
def _inverse_stft(self, stft_t, time_crop=None):
""" Inverse and reshape the given STFT
:param stft_t: input STFT
:returns: inverse STFT (waveform)
"""
inversed = inverse_stft(
tf.transpose(stft_t, perm=[2, 0, 1]),
self._frame_length,
self._frame_step,
window_fn=lambda frame_length, dtype: (
hann_window(frame_length, periodic=True, dtype=dtype))
) * self.WINDOW_COMPENSATION_FACTOR
reshaped = tf.transpose(inversed)
if time_crop is None:
time_crop = tf.shape(self._features['waveform'])[0]
return reshaped[:time_crop, :]
示例4: images_to_sequence
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import transpose [as 别名]
def images_to_sequence(tensor):
"""Convert a batch of images into a batch of sequences.
Args:
tensor: a (num_images, height, width, depth) tensor
Returns:
(width, num_images*height, depth) sequence tensor
"""
transposed = tf.transpose(tensor, [2, 0, 1, 3])
shapeT = tf.shape(transposed)
shapeL = transposed.get_shape().as_list()
# Calculate the ouput size of the upsampled tensor
n_shape = tf.stack([
shapeT[0],
shapeT[1]*shapeT[2],
shapeL[3]
])
reshaped = tf.reshape(transposed, n_shape)
return reshaped
示例5: sequence_to_images
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import transpose [as 别名]
def sequence_to_images(tensor, num_batches):
"""Convert a batch of sequences into a batch of images.
Args:
tensor: (num_steps, num_batchesRNN, depth) sequence tensor
num_batches: the number of image batches
Returns:
(num_batches, height, width, depth) tensor
"""
shapeT = tf.shape(tensor)
shapeL = tensor.get_shape().as_list()
# Calculate the ouput size of the upsampled tensor
height = tf.to_int32(shapeT[1] / num_batches)
n_shape = tf.stack([
shapeT[0],
num_batches,
height,
shapeL[2]
])
reshaped = tf.reshape(tensor, n_shape)
return tf.transpose(reshaped, [1, 2, 0, 3])
示例6: decode_topk
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import transpose [as 别名]
def decode_topk(self, sess, latest_tokens, enc_top_states, dec_init_states):
"""Return the topK results and new decoder states."""
feed = {
self._enc_top_states: enc_top_states,
self._dec_in_state:
np.squeeze(np.array(dec_init_states)),
self._abstracts:
np.transpose(np.array([latest_tokens])),
self._abstract_lens: np.ones([len(dec_init_states)], np.int32)}
results = sess.run(
[self._topk_ids, self._topk_log_probs, self._dec_out_state],
feed_dict=feed)
ids, probs, states = results[0], results[1], results[2]
new_states = [s for s in states]
return ids, probs, new_states
示例7: unsqueeze_2x2
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import transpose [as 别名]
def unsqueeze_2x2(input_):
"""Unsqueezing operation: reshape to convert channels into space."""
if isinstance(input_, (float, int)):
return input_
shape = input_.get_shape().as_list()
batch_size = shape[0]
height = shape[1]
width = shape[2]
channels = shape[3]
if channels % 4 != 0:
raise ValueError("Number of channels not divisible by 4.")
res = tf.reshape(input_, [batch_size, height, width, channels // 4, 2, 2])
res = tf.transpose(res, [0, 1, 4, 2, 5, 3])
res = tf.reshape(res, [batch_size, 2 * height, 2 * width, channels // 4])
return res
# batch norm
示例8: compute_first_or_last
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import transpose [as 别名]
def compute_first_or_last(self, select, first=True):
#perform first ot last operation on row select with probabilistic row selection
answer = tf.zeros_like(select)
running_sum = tf.zeros([self.batch_size, 1], self.data_type)
for i in range(self.max_elements):
if (first):
current = tf.slice(select, [0, i], [self.batch_size, 1])
else:
current = tf.slice(select, [0, self.max_elements - 1 - i],
[self.batch_size, 1])
curr_prob = current * (1 - running_sum)
curr_prob = curr_prob * tf.cast(curr_prob >= 0.0, self.data_type)
running_sum += curr_prob
temp_ans = []
curr_prob = tf.expand_dims(tf.reshape(curr_prob, [self.batch_size]), 0)
for i_ans in range(self.max_elements):
if (not (first) and i_ans == self.max_elements - 1 - i):
temp_ans.append(curr_prob)
elif (first and i_ans == i):
temp_ans.append(curr_prob)
else:
temp_ans.append(tf.zeros_like(curr_prob))
temp_ans = tf.transpose(tf.concat(axis=0, values=temp_ans))
answer += temp_ans
return answer
示例9: convert_network_state_tensorarray
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import transpose [as 别名]
def convert_network_state_tensorarray(tensorarray):
"""Converts a source TensorArray to a source Tensor.
Performs a permutation between the steps * [stride, D] shape of a
source TensorArray and the (flattened) [stride * steps, D] shape of
a source Tensor.
The TensorArrays used during recurrence have an additional zeroth step that
needs to be removed.
Args:
tensorarray: TensorArray object to be converted.
Returns:
Tensor object after conversion.
"""
tensor = tensorarray.stack() # Results in a [steps, stride, D] tensor.
tensor = tf.slice(tensor, [1, 0, 0], [-1, -1, -1]) # Lop off the 0th step.
tensor = tf.transpose(tensor, [1, 0, 2]) # Switch steps and stride.
return tf.reshape(tensor, [-1, tf.shape(tensor)[2]])
示例10: rotate_dimensions
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import transpose [as 别名]
def rotate_dimensions(num_dims, src_dim, dest_dim):
"""Returns a list of dimension indices that will rotate src_dim to dest_dim.
src_dim is moved to dest_dim, with all intervening dimensions shifted towards
the hole left by src_dim. Eg:
num_dims = 4, src_dim=3, dest_dim=1
Returned list=[0, 3, 1, 2]
For a tensor with dims=[5, 4, 3, 2] a transpose would yield [5, 2, 4, 3].
Args:
num_dims: The number of dimensions to handle.
src_dim: The dimension to move.
dest_dim: The dimension to move src_dim to.
Returns:
A list of rotated dimension indices.
"""
# List of dimensions for transpose.
dim_list = range(num_dims)
# Shuffle src_dim to dest_dim by swapping to shuffle up the other dims.
step = 1 if dest_dim > src_dim else -1
for x in xrange(src_dim, dest_dim, step):
dim_list[x], dim_list[x + step] = dim_list[x + step], dim_list[x]
return dim_list
示例11: intersection
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import transpose [as 别名]
def intersection(boxlist1, boxlist2, scope=None):
"""Compute pairwise intersection areas between boxes.
Args:
boxlist1: BoxList holding N boxes
boxlist2: BoxList holding M boxes
scope: name scope.
Returns:
a tensor with shape [N, M] representing pairwise intersections
"""
with tf.name_scope(scope, 'Intersection'):
y_min1, x_min1, y_max1, x_max1 = tf.split(
value=boxlist1.get(), num_or_size_splits=4, axis=1)
y_min2, x_min2, y_max2, x_max2 = tf.split(
value=boxlist2.get(), num_or_size_splits=4, axis=1)
all_pairs_min_ymax = tf.minimum(y_max1, tf.transpose(y_max2))
all_pairs_max_ymin = tf.maximum(y_min1, tf.transpose(y_min2))
intersect_heights = tf.maximum(0.0, all_pairs_min_ymax - all_pairs_max_ymin)
all_pairs_min_xmax = tf.minimum(x_max1, tf.transpose(x_max2))
all_pairs_max_xmin = tf.maximum(x_min1, tf.transpose(x_min2))
intersect_widths = tf.maximum(0.0, all_pairs_min_xmax - all_pairs_max_xmin)
return intersect_heights * intersect_widths
示例12: __init__
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import transpose [as 别名]
def __init__(self, num_experts, gates):
"""Create a SparseDispatcher.
Args:
num_experts: an integer.
gates: a `Tensor` of shape `[batch_size, num_experts]`.
Returns:
a SparseDispatcher
"""
self._gates = gates
self._num_experts = num_experts
where = tf.to_int32(tf.where(tf.transpose(gates) > 0))
self._expert_index, self._batch_index = tf.unstack(where, num=2, axis=1)
self._part_sizes_tensor = tf.reduce_sum(tf.to_int32(gates > 0), [0])
self._nonzero_gates = tf.gather(
tf.reshape(self._gates, [-1]),
self._batch_index * num_experts + self._expert_index)
示例13: neural_gpu_body
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import transpose [as 别名]
def neural_gpu_body(inputs, hparams, name=None):
"""The core Neural GPU."""
with tf.variable_scope(name, "neural_gpu"):
def step(state, inp): # pylint: disable=missing-docstring
x = tf.nn.dropout(state, 1.0 - hparams.dropout)
for layer in range(hparams.num_hidden_layers):
x = common_layers.conv_gru(
x, (hparams.kernel_height, hparams.kernel_width),
hparams.hidden_size,
name="cgru_%d" % layer)
# Padding input is zeroed-out in the modality, we check this by summing.
padding_inp = tf.less(tf.reduce_sum(tf.abs(inp), axis=[1, 2]), 0.00001)
new_state = tf.where(padding_inp, state, x) # No-op where inp is padding.
return new_state
return tf.foldl(
step,
tf.transpose(inputs, [1, 0, 2, 3]),
initializer=inputs,
parallel_iterations=1,
swap_memory=True)
示例14: vq_nearest_neighbor
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import transpose [as 别名]
def vq_nearest_neighbor(x, hparams):
"""Find the nearest element in means to elements in x."""
bottleneck_size = 2**hparams.bottleneck_bits
means = hparams.means
x_norm_sq = tf.reduce_sum(tf.square(x), axis=-1, keepdims=True)
means_norm_sq = tf.reduce_sum(tf.square(means), axis=-1, keepdims=True)
scalar_prod = tf.matmul(x, means, transpose_b=True)
dist = x_norm_sq + tf.transpose(means_norm_sq) - 2 * scalar_prod
if hparams.bottleneck_kind == "em":
x_means_idx = tf.multinomial(-dist, num_samples=hparams.num_samples)
x_means_hot = tf.one_hot(
x_means_idx, depth=bottleneck_size)
x_means_hot = tf.reduce_mean(x_means_hot, axis=1)
else:
x_means_idx = tf.argmax(-dist, axis=-1)
x_means_hot = tf.one_hot(x_means_idx, depth=bottleneck_size)
x_means = tf.matmul(x_means_hot, means)
e_loss = tf.reduce_mean(tf.square(x - tf.stop_gradient(x_means)))
return x_means_hot, e_loss
示例15: rank_loss
# 需要导入模块: import tensorflow [as 别名]
# 或者: from tensorflow import transpose [as 别名]
def rank_loss(sentence_emb, image_emb, margin=0.2):
"""Experimental rank loss, thanks to kkurach@ for the code."""
with tf.name_scope("rank_loss"):
# Normalize first as this is assumed in cosine similarity later.
sentence_emb = tf.nn.l2_normalize(sentence_emb, 1)
image_emb = tf.nn.l2_normalize(image_emb, 1)
# Both sentence_emb and image_emb have size [batch, depth].
scores = tf.matmul(image_emb, tf.transpose(sentence_emb)) # [batch, batch]
diagonal = tf.diag_part(scores) # [batch]
cost_s = tf.maximum(0.0, margin - diagonal + scores) # [batch, batch]
cost_im = tf.maximum(
0.0, margin - tf.reshape(diagonal, [-1, 1]) + scores) # [batch, batch]
# Clear diagonals.
batch_size = tf.shape(sentence_emb)[0]
empty_diagonal_mat = tf.ones_like(cost_s) - tf.eye(batch_size)
cost_s *= empty_diagonal_mat
cost_im *= empty_diagonal_mat
return tf.reduce_mean(cost_s) + tf.reduce_mean(cost_im)