Tensorflow:feed_dict{} 的错误形状

Tensorflow: wrong shape of feed_dict{}

第一次遇到这样的问题。

错误是关于 feed_dict={tfkids: kids, tfkids_fit: kids_fit},似乎需要重塑 kids_fit

谁能帮我解决这个问题?

import tensorflow as tf
from tensorflow.contrib.distributions import Normal
import numpy as np
import matplotlib.pyplot as plt

DNA_SIZE = 1
POP_SIZE = 10
LR = 0.1
N_GENERATION = 50

def F(x):
    return x**2

def get_fitness(value):
    return -value

mean = tf.Variable(tf.constant(13.), dtype=tf.float32)
sigma = tf.Variable(tf.constant(5.), dtype=tf.float32)
N_dist = Normal(loc=mean, scale=sigma)
make_kids = N_dist.sample([POP_SIZE])

tfkids = tf.placeholder(tf.float32, [POP_SIZE, DNA_SIZE])
tfkids_fit = tf.placeholder(tf.float32, [POP_SIZE])
loss = -tf.reduce_mean(N_dist.log_prob(tfkids) * tfkids_fit)
train_op = tf.train.GradientDescentOptimizer(LR).minimize(loss)

x = np.linspace(-20, 20, 100)
plt.plot(x, F(x))

sess = tf.Session()
init = tf.global_variables_initializer()
sess.run(init)

plt.ion()
for g in range(N_GENERATION):
    kids = sess.run(make_kids)
    kids_fit = get_fitness(F(kids))
    sess.run(train_op, feed_dict={tfkids: kids, tfkids_fit: kids_fit})

    if "plot_points" in globals():
        plot_points.remove()

    plot_points = plt.scatter(kids, F(kids), s=30)
    plt.pause(0.05)

plt.ioff()
plt.show()

这会在尝试测试代码时出错。

ValueError: Cannot feed value of shape (10,) for Tensor 'Placeholder:0', which has shape '(10, 1)'

您可以重塑儿童张量。

kids = sess.run(make_kids)
kids = tf.reshape(kids,(None,1))
kids_fit = get_fitness(F(kids))
sess.run(train_op, feed_dict={tfkids: kids, tfkids_fit: kids_fit})

你的Placeholder:0tfkids = tf.placeholder(tf.float32, [POP_SIZE, DNA_SIZE])

如你所见,tfkids形状是[POP_SIZE, DNA_SIZE] = (10, 1)

您的 kids 变量的形状 = (10).

虽然两个形状都包含 10 个值,但第一个有 2 个维度,而第二个是 1 个维度。

因此,您必须以这种方式扩展 kids 变量的维度,以便与 tfkids 兼容:

sess.run(train_op, feed_dict={tfkids: np.expand_dims(kids, axis=1), tfkids_fit: kids_fit})

np.expand_dims 允许您向 kids 形状添加一维维度

问题: 当您声明 tfkids 变量时,您将其形状指定为 [POP_SIZE, DNA_SIZE],即 (10, 1)。但是,当您在训练期间将真实数据输入占位符时,您传递的是 (10,) 形状的数据。

解法: 因此,您必须将训练数据重塑为 (10, 1) 才能将其提供给变量。有几种方法可以重塑数据。您可以使用 numpy 库的 reshape 函数。在为您提供训练数据之前执行以下操作。

kids = np.reshape(kids, [-1, 1])

希望对您有所帮助!