[英]Feeding data - ValueError: Dimensions must be equal
我正在使用張量流訓練線性回歸模型。 您可以在此處找到數據。 這是我的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
您可以在此處找到類似的示例代碼。 我的代碼中的差異是關於tf.placeholder
的饋送tf.placeholder
。
具體來說,我不想像示例代碼一樣 逐行提供數據。 我想一次喂所有東西。 因此,我的代碼將如下所示
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”(op:“ Mul”),尺寸應為0和42。
- 是否可以一次提供所有數據?
是的,我們可以提供一個批處理(如果沒有內存限制,該批處理可以是整個數據)。
- 如果是這樣,你們可以建議我解決這個問題嗎?
定義接受一批輸入而不是單個輸入的占位符:
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) })
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.