TensorFlow“ InvalidArgumentError”用于通过feed_dict馈入占位符的值

时间:2019-05-20 11:12:46

标签: python tensorflow

我正在研究TensorFlow的示例问题(特别是与占位符一起使用),并且当我相当有把握地知道是什么时,我不明白为什么会收到(看起来是)形状/类型错误他们应该是。

我尝试使用X_batch和y_batch中的各种浮点类型,尝试将大小从“无”(未指定)更改为将要传递的大小(100),但没有一个起作用

import tensorflow as tf
import numpy as np
from sklearn.datasets import fetch_california_housing

def fetch_batch(epoch, batch_index, batch_size, X, y):

    np.random.seed(epoch * batch_index)
    indices = np.random.randint(m, size=batch_size)
    X_batch = X[indices]
    y_batch = y[indices]
    return X_batch.astype('float32'), y_batch.astype('float32')

if __name__ == "__main__":

    housing = fetch_california_housing()

    m, n = housing.data.shape

    # standardizing input data
    standardized_housing = (housing.data - np.mean(housing.data)) / np.std(housing.data)

    std_housing_bias = np.c_[np.ones((m, 1)), standardized_housing]

    # using the size "n+1" to account for the bias term
    X = tf.placeholder(tf.float32, shape=(None, n+1), name='X')
    y = tf.placeholder(tf.float32, shape=(None, 1), name='y')

    theta = tf.Variable(tf.random_uniform([n + 1, 1], -1, 1), dtype=tf.float32, name='theta')

    y_pred = tf.matmul(X, theta, name='predictions')

    error = y_pred - y

    mse = tf.reduce_mean(tf.square(error), name='mse')

    n_epochs = 1000
    learning_rate = 0.01
    batch_size = 100
    n_batches = int(np.ceil(m / batch_size))

    # using the Gradient Descent Optimizer class from tensorflow's optimizer selection
    optimizer = tf.train.GradientDescentOptimizer(learning_rate=learning_rate)

    training_op = optimizer.minimize(mse)

    # creates a node in the computational graph that initializes all variables when it is run
    init = tf.global_variables_initializer()

    with tf.Session() as sess:
        sess.run(init)

        for epoch in range(n_epochs):
            for batch_index in range(n_batches):
                X_batch, y_batch = fetch_batch(epoch, batch_index, batch_size, std_housing_bias, \
                                housing.target.reshape(-1, 1))

                print(X_batch.shape, X_batch.dtype, y_batch.shape, y_batch.dtype)
                sess.run(training_op, feed_dict={X: X_batch, y: y_batch})

                if epoch % 100 == 0:
                    print(f"Epoch {epoch} MSE = {mse.eval()}")


        best_theta = theta.eval()

    print("Mini Batch Gradient Descent Beta Estimates")
    print(best_theta)

我得到的错误是:

InvalidArgumentError: You must feed a value for placeholder tensor 'X' with dtype float and shape [?,9]
     [[node X (defined at /Users/marshallmcquillen/Scripts/lab.py:25) ]]

我抛出了一个打印X_batch和y_batch属性的打印语句,这些是我期望的,但仍然无法使用。

1 个答案:

答案 0 :(得分:2)

您要评估的mse也取决于占位符Xy,因此您还需要提供feed_dict。您可以通过将行更改为

来修复它
if epoch % 100 == 0:
  print(f"Epoch {epoch} MSE = {mse.eval(feed_dict={X: X_batch, y: y_batch})}")

但是由于您正在尝试评估模型,因此使用测试数据集是合理的。所以理想情况是

if epoch % 100 == 0:
  print(f"Epoch {epoch} MSE = {mse.eval(feed_dict={X: X_test, y: y_test})}")