如何将1D Tensorflow Tensor重塑为4级4D张量

时间:2017-04-11 04:46:19

标签: python machine-learning tensorflow

我有一个代表图像的Tensorflow Tensor。我最初有(2,2,3)形状的RGB图像,但是当数据到达我的模型时,它已经被标准化,转换为灰度,并且被展平。

我正在尝试重建图像,以便我可以在其上运行一些卷积。我尝试重塑它,挤压它,然后用几种不同的方式扩展它,但是我不能把它变成conv2d的4D数组。

以下是我正在使用的代码。

import tensorflow as tf

# This was originally a 2x2 RGB image which was converted to grayscale and flattened
tf_1d_input = tf.Variable([0.1, 1.0, 2.0, 3.0]) 
tf_4d_reshape = tf.reshape(tf_1d_input, [1, 2, 2, 1])
tf_conv_layer = tf.nn.conv2d(tf_4d_reshape, (3,3), [1, 1, 1, 1], 'SAME')

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    print(tf.rank(tf_4d_reshape))
    sess.run(tf_conv_layer)
# ValueError: Shape must be rank 4 but is rank 1 for 'Conv2D' (op: 'Conv2D') with input shapes: [1,2,2,1], [2]. 

是否有一个我失踪的步骤,或者我根本不明白重塑的内容/什么是conv2d所期望的。

1 个答案:

答案 0 :(得分:0)

在tensorflow中,conv2d的过滤器参数必须是与卷积权重相对应的张量,而不是卷积大小。

tf_1d_input = tf.Variable([0.1, 1.0, 2.0, 3.0]) 
tf_4d_reshape = tf.reshape(tf_1d_input, [1, 2, 2, 1])
w = tf.zeros([3, 3, 1, 10])
tf_conv_layer = tf.nn.conv2d(tf_4d_reshape, w, [1, 1, 1, 1], 'SAME') # no error anymore

当然上面的例子有效但没有用。您将在tf教程中找到有关如何使用初始化器初始化权重的更具体示例,例如MNIST上的这个。