区别:
这两个主要是适用场合的区别,前者用于更新图中某个tensor的shape,而后者则往往用于动态地创建一个新的tensor
set_shape的典型用法如下:
import tensorflow as tf
x1 = tf.placeholder(tf.int32)
x1.set_shape([2,2])
print(x1.get_shape())
sess = tf.Session()
#print(sess.run(tf.shape(x1), feed_dict={x1:[0,1,2,3]}))
print(sess.run(tf.shape(x1), feed_dict={x1:[[0,1],[2,3]]}))
输出:
(2, 2)
[2 2]
这代表了图中最开始没有shape的x1在使用了set_shape后,它的图中的信息已经改变了,如果取消掉注释就会报错,因为我们传入了和图不符合的参数。
reshape的典型用法则是这样:
import tensorflow as tf
x1 = tf.placeholder(tf.int32)
x2 = tf.reshape(x1, [2,2])
print(x1.get_shape())
sess = tf.Session()
print(sess.run(tf.shape(x2), feed_dict={x1:[0,1,2,3]}))
print(sess.run(tf.shape(x2), feed_dict={x1:[[0,1],[2,3]]}))
输出:
(2,2)
[2,2]
[2,2]
即它并不是想改变图,而只是想创造一个新的tensor以供我们使用。
但是reshape能否和set_shape有着相同的用法,即用来改变图?我们试着修改上面的代码:
import tensorflow as tf
x1 = tf.placeholder(tf.int32)
x1 = tf.reshape(x1, [2,2]) # use tf.reshape()
print(tf.shape(x1))
sess = tf.Session()
#print(sess.run(tf.shape(x1), feed_dict={x1:[0,1,2,3]}))
print(sess.run(tf.shape(x1), feed_dict={x1:[[0,1],[2,3]]}))
经测试,reshape后x1的shape也发生了变化,注释不取消仍然会有报错现象。
那么set_shape和reshape的用法是否完全一样呢?还是有一定差别的。
reshape可以改变原有tensor的shape,而set_shape只能更新信息没办法直接改变值,可以参考下面的程序:
import tensorflow as tf
x1 = tf.Variable([[0, 1], [2, 3]])
print(x1.get_shape())
x1 = tf.reshape(x1, [4, 1]) # if we use x1.set_shape([4, 1]),the program cannot run
print(x1.get_shape())
转载自:https://blog.csdn.net/weixin_40395922/article/details/81708532