【问题标题】:AttributeError: 'Tensor' object has no attribute 'reshape'AttributeError:“张量”对象没有“重塑”属性
【发布时间】:2018-06-20 21:20:24
【问题描述】:

我想编写一个去噪自动编码器,为了可视化目的,我还想打印出损坏的图像。

这是我要显示损坏图像的测试部分:

def corrupt(x):
    noise = tf.random_normal(shape=tf.shape(x), mean=0.0, stddev=0.2, dtype=tf.float32) 
    return x + noise

# Testing
# Encode and decode images from test set and visualize their reconstruction
n = 10
canvas_orig = np.empty((28, 28 * n))
canvas_corrupt = np.empty((28, 28 * n))
canvas_recon = np.empty((28, 28 * n))

# MNIST test set
batch_x, _ = mnist.test.next_batch(n)

# Encode and decode the digit image and determine the test loss
g, l = sess.run([Y, loss], feed_dict={X: batch_x})

# Draw the generated digits
for i in range(n):
    # Original images
    canvas_orig[0: 28, i * 28: (i + 1) * 28] = batch_x[i].reshape([28, 28])

    # Corrupted images
    canvas_corrupt[0: 28, i * 28: (i + 1) * 28] = corrupt(batch_x[i]).reshape([28, 28]) 

    # Reconstructed images
    canvas_recon[0: 28, i * 28: (i + 1) * 28] = g[i].reshape([28, 28])    

print("Original Images")     
plt.figure(figsize=(n, 1))
plt.imshow(canvas_orig, origin="upper", cmap="gray")
plt.show()

print("Corrupted Images")     
plt.figure(figsize=(n, 1))
plt.imshow(canvas_corrupt, origin="upper", cmap="gray")
plt.show()

print("Reconstructed Images")
plt.figure(figsize=(n, 1))
plt.imshow(canvas_recon, origin="upper", cmap="gray")
plt.show()

错误发生在以下行:

canvas_corrupt[0: 28, i * 28: (i + 1) * 28] = corrupt(batch_x[i]).reshape([28, 28])

我真的不明白为什么它不起作用,因为它上面和下面的语句看起来非常相似并且可以完美运行。 而事实上,“重塑”是一个函数而不是一个属性,这让我很困惑。

【问题讨论】:

    标签: python numpy tensorflow neural-network autoencoder


    【解决方案1】:

    区别在于batch_x[i] 是一个numpy 数组(它有一个reshape 方法),而corrupt(...) 的结果是一个Tensor 对象。从 tf 1.5 开始,它没有 reshape 方法。这不会抛出错误:tf.reshape(corrupt(batch_x[i]), [28, 28]))

    但由于您的目标是可视化该值,因此您最好避免混淆 tensorflow 和 numpy 操作,并仅将 corrupt 重写为 numpy

    def corrupt(x):
        noise = np.random.normal(size=x.shape, loc=0.0, scale=0.2)
        return x + noise
    

    【讨论】:

    • 谢谢,这对我帮助很大。就像你说的,现在我只是用numpynp.random.normal(0, 0.2, 784)产生噪音,所以reshape()函数就没有问题了。
    猜你喜欢
    • 1970-01-01
    • 2018-06-06
    • 2019-05-12
    • 2020-10-22
    • 2019-02-20
    • 2017-12-06
    • 2018-07-02
    相关资源
    最近更新 更多