【问题标题】:Feeding data - ValueError: Dimensions must be equal馈送数据 - ValueError:尺寸必须相等
【发布时间】:2018-05-24 00:34:46
【问题描述】:

我正在使用 tensorflow 来训练线性回归模型。您可以在here 找到数据。 这是我的load_data() 函数

def load_data():
    book = xlrd.open_workbook(DATA_DIR, encoding_override="utf-8")
    sheet = book.sheet_by_index(0)
    data = np.asarray([sheet.row_values(i) for i in range(1, sheet.nrows)])
    n_samples = len(data)

    return data, n_samples

您可以在here 找到类似的示例代码。我的代码的不同之处在于喂食tf.placeholder的方式。

具体来说,我逐行提供类似于sample code的数据。我想一次喂饱所有东西。所以,我的代码看起来像这样

print('Load data')
train_data, n_samples = load_data()

print('Define placeholders')
features = [tf.placeholder(tf.float32, shape=(), name='sample_' + str(i))
            for i in range(n_samples)]
labels = [tf.placeholder(tf.float32, shape=(), name='label_' + str(i))
          for i in range(n_samples)]

print('Define variables')
w = tf.Variable(tf.zeros(0.0, tf.float32))
b = tf.Variable(tf.zeros(0.0, tf.float32))

print('Define hypothesis function')
pred_labels = w * features + b

print('Define loss function')
loss = tf.square(labels - pred_label, name='loss')

print('Define optimizer function')
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.0001).minimize(loss)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    saver = tf.train.Saver(tf.trainable_variables())
    feed_dict = fill_feed_dict(train_data, features, labels)

    for i in range(100):
        __, loss_value = sess.run([optimizer, loss], feed_dict)
        print('Epoch {} has loss value {}'.format(i, loss_value))
        if i == 99:
            saver.save(sess, CKPT_DIR)

fill_feed_dict() 这样的

def fill_feed_dict(data, features, labels):
    feed_dict = {}

    for i in range(len(features)):
        feed_dict[features[i]] = data[i, 0]
        feed_dict[labels[i]] = data[i, 1]

    return feed_dict

但是执行的时候出现如下错误

ValueError:尺寸必须相等,但对于输入形状为 [0]、[42] 的“mul”(操作:“Mul”)为 0 和 42。

  1. 是否可以一次提供所有数据?
  2. 如果是这样,你们能建议我解决这个问题吗?

【问题讨论】:

    标签: python tensorflow


    【解决方案1】:
    1. 是否可以一次提供所有数据?

    是的,我们可以喂一个批次(如果没有内存限制,批次可以是整个数据)。

    1. 如果是这样,你们能建议我解决这个问题吗?

    定义接受一批输入而不是单个输入的占位符:

    X = tf.placeholder(tf.float32, shape=[None,1], name='X')
    Y = tf.placeholder(tf.float32, shape=[None,1],name='Y')
    

    你的代码应该是:

    w = tf.Variable(0.0, name='weights')
    b = tf.Variable(0.0, name='bias')
    
    Y_predicted = X * w + b 
    loss = tf.reduce_mean(tf.square(Y - Y_predicted, name='loss'))
    optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.001).minimize(loss)
    
    with tf.Session() as sess:
    
       sess.run(tf.global_variables_initializer()) 
    
       #train the model
       for i in range(50): # train the model 100 epochs
          #Session runs train_op and fetch values of loss
          _, l = sess.run([optimizer, loss], feed_dict={X: feed input of size (batch,1), Y: Output of size (batch,1) }) 
    

    【讨论】:

    • shape=(None, 1)shape=[None, 1] 有什么区别吗?我刚刚尝试了两者,仍然得到相同的预期结果。
    • 是的,它可以表示为列表或元组。
    猜你喜欢
    • 2017-07-18
    • 2021-11-08
    • 1970-01-01
    • 2021-08-29
    • 2019-10-11
    • 1970-01-01
    • 2021-08-18
    • 2018-02-11
    • 2022-07-23
    相关资源
    最近更新 更多