TensorFlow 1.0+ 张量操作详解:tf.concat、tf.stack 与 tf.reshape 用法对比
本文详解 TensorFlow 1.0 版本后张量操作函数的关键变更。重点解析 tf.concat 参数位置调整、tf.stack 替代 tf.pack 的用法,以及 tf.reshape 中 -1 参数的行列转换技巧,帮助开发者规避版本升级带来的兼容性问题。
TensorFlow 版本升级背景
有一段时间未使用 TensorFlow 进行开发,近期在运行实验时再次遇到了一些潜在问题,主要集中在张量计算层面。自 TensorFlow 升级至 1.0 版本后,其 API 与早期版本不再完全兼容,这可能导致出现各种意想不到的错误。
tf.concat 函数参数变更
1. tf.concat 函数
在 TensorFlow 1.0 之前的版本中,该函数的调用方式为 tf.concat(concat_dim, values, name='concat'),其中第一个参数指定连接的维度,用于将多个向量按指定维度进行拼接。
例如:
t1 = [[1, 2, 3], [4, 5, 6]]
t2 = [[7, 8, 9], [10, 11, 12]]
#按照第0维连接
tf.concat(0, [t1, t2]) ==> [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
#按照第1维连接
tf.concat(1, [t1, t2]) ==> [[1, 2, 3, 7, 8, 9], [4, 5, 6, 10, 11, 12]]
tf.concat 的主要作用是将向量按指定维度连接,同时保持其余维度不变。在 1.0 版本之后,函数的调用方式发生了改变:
t1 = [[1, 2, 3], [4, 5, 6]]
t2 = [[7, 8, 9], [10, 11, 12]]
#按照第0维连接
tf.concat( [t1, t2],0) ==> [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
#按照第1维连接
tf.concat([t1, t2],1) ==> [[1, 2, 3, 7, 8, 9], [4, 5, 6, 10, 11, 12]]
注意参数位置的变动。
tf.stack 函数用法说明
2. tf.stack 函数
用法:stack(values, axis=0, name="stack"):
"""将一组秩为 R 的张量堆叠成一个秩为 R+1 的张量。
x = tf.constant([1, 4])
y = tf.constant([2, 5])
z = tf.constant([3, 6])
tf.stack([x,y,z]) ==> [[1,4],[2,5],[3,6]]
tf.stack([x,y,z],axis=0) ==> [[1,4],[2,5],[3,6]]
tf.stack([x,y,z],axis=1) ==> [[1, 2, 3], [4, 5, 6]]
tf.stack 的功能是将一组 R 维张量转换为 R+1 维张量。需要注意的是,旧版本中的 tf.pack 已更名为 tf.stack。
tf.reshape 形状变换技巧
3. tf.reshape
用法:reshape(tensor, shape, name=None):该函数主要用于改变张量的形状,支持从高维到低维或从低维到高维的转换。
a = tf.Variable(initial_value=[[1,2,3],[4,5,6]]) ==> shape:[2,3]
b = tf.Variable(initial_value=[[[1,2,3],[4,5,6]],[[7,8,9],[1,0,2]]]) ==> shape:[2,2,3]
a_1 = tf.reshape(a,[2,1,1,3]) ==> [[[[1,2,3]]],[[[4,5,6]]]]
a_2 = tf.reshape(a,[2,1,3]) ==> [[[1,2,3]],[[4,5,6]]]
b_1 = tf.reshape(b,[2,2,1,3]) ==> [[[[1,2,3]],[[4,5,6]]],[[[7,8,9]],[[1,0,2]]]]
new_1 = tf.concat([b_1,a_1],1)
new_2 = tf.reshape(tf.concat([b,a_2],1),[2,3,1,3])
"""
new_1:
[[[[1 2 3]]
[[4 5 6]]
[[1 2 3]]]
[[[7 8 9]]
[[1 0 2]]
[[4 5 6]]]]
new_2;
[[[[1 2 3]]
[[4 5 6]]
[[1 2 3]]]
[[[7 8 9]]
[[1 0 2]]
[[4 5 6]]]]
补充知识:关于 TensorFlow 中 reshape(tensor,[1,-1]) 和 reshape(tensor,[-1,1]) 的区别
其用法与 Python 中的 reshape 类似。
import tensorflow as tf
a = [[1,2],[3,4],[5,6]]
tf.reshape(a,[-1,1])
Out[13]: <tf.Tensor 'Reshape_4:0' shape=(6, 1) dtype=int32>
tf.reshape(tf.reshape(a,[-1,1]),[1,-1])
Out[14]: <tf.Tensor 'Reshape_6:0' shape=(1, 6) dtype=int32>
tf.reshape(tensor,[-1,1]) 将张量转换为一维列向量。
tf.reshape(tensor,[1,-1]) 将张量转换为一维行向量。
以上关于 TensorFlow 使用张量时的注意事项,包括 tf.concat、tf.reshape 和 tf.stack 的详解,就是本文分享的全部内容,希望能为大家提供参考。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









