【问题标题】:tf.reshape is not working in the cases where you are adding an extra dimensiontf.reshape 在添加额外维度的情况下不起作用
【发布时间】:2018-12-22 21:10:05
【问题描述】:

根据 tensorflow 网站,tf.reshape 将某个形状的张量映射到另一个形状的张量。我想将大小为 [600, 64] 的张量映射到大小为 [-1, 8, 8, 1] 的张量(其中 -1 位置的维度为 600)。但这似乎不起作用。

我在 python 3.6 的 tensorflow 上运行它,虽然它会重塑为 [-1, 8, 8] 之类的东西,但它不会重塑为 [-1, 8, 8, 1]

import tensorflow as tf
import numpy as np
from sklearn import datasets
from sklearn.preprocessing import LabelBinarizer

# preprocessing method needed
    def flatten(array):
        temp = []
        for j in array:
            temp.extend(j)
        return temp

# preprocess the data
digits = datasets.load_digits()
images = digits.images
images = [flatten(i) for i in images]
labels = digits.target
labels = LabelBinarizer().fit_transform(labels)

# the stats needed
width = 8
height = 8
alpha = 0.1
num_labels = 10
kernel_length = 3
batch_size = 10
channels = 1

# the tensorflow placeholders and reshaping
X = tf.placeholder(tf.float32, shape = [None, width * height * channels])

# AND NOW HERE IS WHERE THE ERROR STARTS
y_true = tf.placeholder(tf.float32, shape = [None, num_labels])
X = tf.reshape(X, [-1, 8, 8, 1])

# the convolutional model
conv1 = tf.layers.conv2d(X, filters = 32, kernel_size = [kernel_length,  kernel_length])
conv2 = tf.layers.conv2d(conv1, filters = 64, kernel_size = [2, 2])
flatten = tf.reshape(X, [-1, 1])
dense1 = tf.layers.dense(flatten, units=50, activation = tf.nn.relu)
y_pred = tf.layers.dense(dense1, units=num_labels, activation = tf.nn.softmax)

# the loss and training functions
loss = tf.losses.mean_squared_error(labels=y_true, predictions=y_pred)
train = tf.train.GradientDescentOptimizer(alpha).minimize(loss)

# initializing the variables and the tf.session
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)

# running the session
for i in range(batch_size):
    _, lossVal = sess.run((train, loss), feed_dict = {X:images[:600], y_true: labels[:600]})
    print(lossVal)

我不断收到此错误: ValueError:无法为张量“重塑:0”提供形状(600、64)的值,其形状为“(?、8、8、1)” 而且我觉得不应该是这样,因为 8 * 8 * 1 确实等于 64。

【问题讨论】:

    标签: python tensorflow


    【解决方案1】:

    images[:600] 的形状为(600, 64),与占位符预期形状不对应,(None, 8, 8, 1)

    重塑您的数据或更改占位符的形状。

    请注意,您最初将占位符形状定义为 (None, 64) 的事实是无关紧要的,因为您稍后会对其进行重新调整。

    【讨论】:

    • 您能否详细说明以下声明:“请注意,您最初将占位符形状定义为 (None, 64) 的事实是无关紧要的,因为您稍后会对其进行重新整形。”这是否意味着 tensorflow 将期望输入具有 (None, 8, 8, 1) 维度,即使我们说输入应该是 (None, 64) 仅仅是因为 tensorflow 考虑了重塑(在创建计算图期间) 然后请求符合该要求的尺寸?
    • 没错。当您使用feed_dict={X:...} 时,X 是形状(None, 8, 8, 1) 的占位符。如果您希望输入形状数组 (600, 64) 并将其重塑为 (None, 8, 8, 1),请不要用 X = tf.reshape(...) 覆盖 X,而是使用类似 X_reshape = tf.reshape(...) 的东西。
    猜你喜欢
    • 2022-07-01
    • 2022-01-08
    • 2019-11-19
    • 2022-12-10
    • 2012-09-06
    • 2019-10-01
    • 2019-12-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多