在十个拉链和重塑

2024-04-26 07:58:54 发布

您现在位置:Python中文网/ 问答频道 /正文

问题:

假设我有两个张量,ab。两者形状相同:[?, 10, 4096]。你知道吗

我该如何压缩这两个,使得到的张量的形状为[?,20,4096],但也使得a的第i个元素正好位于b的第i个元素之前。你知道吗

列表示例:

a = [1, 3, 5]
b = [2, 4, 6]

现在我想要一个看起来像[1, 2, 3, 4, 5, 6]的张量,而不是[1, 3, 5, 2, 4, 6],如果我把这两个用在tf.stack,然后用tf.reshape,对吗?。你知道吗

或者一个更一般的问题是,你怎么知道tf.reshape以什么顺序重塑张量?你知道吗


Tags: 元素示例列表顺序stacktf形状重塑
1条回答
网友
1楼 · 发布于 2024-04-26 07:58:54

首先看起来,堆叠然后再重塑可以完成以下工作:

import tensorflow as tf
a = tf.constant([1, 3, 5])
b = tf.constant([2, 4, 6])
c = tf.stack([a, b], axis = 1)
d = tf.reshape(c, (-1,)) 
with tf.Session() as sess:    
     print(sess.run(c))  # [[1 2],[3 4],[5 6]]
     print(sess.run(d))  # [1 2 3 4 5 6]

为了回答第二个问题,TensorFlow reshape操作使用与numpy默认顺序相同的顺序,即C顺序,引用here

Read the elements of a using this index order, and place the elements into the reshaped array using this index order. ‘C’ means to read / write the elements using C-like index order, with the last axis index changing fastest, back to the first axis index changing slowest.

import numpy as np
a = np.array([1, 3, 5])
b = np.array([2, 4, 6])
c = np.stack([a, b], axis=1)
c.reshape((-1,), order='C')  # array([1, 2, 3, 4, 5, 6])

相关问题 更多 >