温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

tensorflow使用张量时应该注意tf.concat,tf.reshape,tf.stack

发布时间:2020-06-23 16:06:42 来源:亿速云 阅读:454 作者:清晨 栏目:开发技术

不懂tensorflow使用张量时应该注意tf.concat,tf.reshape,tf.stack?其实想解决这个问题也不难,下面让小编带着大家一起学习怎么去解决,希望大家阅读完这篇文章后大所收获。

tensorflow升级1.0版本后与以前的版本并不兼容,可能出现各种奇奇怪怪的问题。

1 tf.concat函数

tensorflow1.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]]

位置变了,需要注意。

2 tf.stack函数

用法:stack(values, axis=0, name=”stack”):

“”“Stacks a list of rank-R tensors into one rank-(R+1) tensor.

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

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内容对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,遇到问题就找亿速云,详细的解决方法等着你来学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI