我正在使用auto-mpg.data。我遇到了这个问题:
回溯(最近通话最近): 在第60行的文件“ C:/PythonProjects/test5.py” _,c = sess.run([优化器,损失],feed_dict = {X:xTrain,Y:yTrain})#获取损失值 运行中的文件“ C:\ Python3 \ lib \ site-packages \ tensorflow \ python \ client \ session.py”,第929行 run_metadata_ptr) _run中的文件“ C:\ Python3 \ lib \ site-packages \ tensorflow \ python \ client \ session.py”,行1128 str(subfeed_t.get_shape())))
ValueError:无法为形状为((,,)'的张量'Placeholder_1:0'输入形状(352,1)的值
我尝试为Xtrain,Xtest,Ytrain,Ytest创建单独的占位符,但是我认为这也不是正确的方法。
如何为测试/训练数据使用相同的X和Y占位符?
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
filename = "auto-mpg.data"
column_names = ['mpg', 'cylinders', 'displacement', 'horsepower', 'weight', 'acceleration', 'year', 'origin', 'name']
df = pd.read_csv(filename, delim_whitespace=True, header=None, na_values = "?", names=column_names)
df = df.drop('name', axis=1)
df = df.dropna()
# Ont-hot encoding for category data
origin = df.pop('origin')
df['USA'] = (origin == 1)*1.0
df['Europe'] = (origin == 2)*1.0
df['Japan'] = (origin == 3)*1.0
df = df.drop(['year'], axis=1)
x_data = df.drop('mpg', axis=1)
y_data = df[['mpg']] # Continuous target variable : mpg
print(df.shape)
# Test/Train split of 90%/10%
xTrain, xTest, yTrain, yTest = train_test_split(x_data, y_data, test_size=0.1, random_state=0)
print(xTrain.shape) # 352x8
print(xTest.shape) # 40x8
print(yTrain.shape) # 352x1
print(yTest.shape) #40x1
def LinearRegression():
y_pred = tf.add(tf.matmul(X, W), b)
loss = tf.reduce_mean(tf.square(y_pred - Y))
return loss
# Xtrain = tf.placeholder(tf.float32, [352,8])
# Ytrain = tf.placeholder(tf.float32, [352,1])
# Xtest = tf.placeholder(tf.float32, [40,8])
# Ytest = tf.placeholder(tf.float32, [40,1])
numFeatures = xTrain.shape[1]
X = tf.placeholder(tf.float32, [None,numFeatures])
Y = tf.placeholder(tf.float32, [None])
W = tf.get_variable(name='Weight', dtype=tf.float32, shape=([8,1]), initializer=tf.zeros_initializer())
b = tf.get_variable(name='Bias', dtype=tf.float32, shape=([1]), initializer=tf.zeros_initializer())
loss=LinearRegression()
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.0000001).minimize(loss)
epochs = 1000
display_step = 100 # Display every 10s output
with tf.Session() as sess:
init = tf.global_variables_initializer()
sess.run(init)
for e in range(epochs):
_, c = sess.run([optimizer, loss], feed_dict={X: xTrain, Y: yTrain}) # Get loss value
if (e + 1) % display_step == 0:
print('Epoch #:', '%d' % (e + 1), 'Loss =', '{:.9f}'.format(c), 'W =', sess.run(W), 'b =', sess.run(b))
print("Training completed...")
training_cost = sess.run(loss, feed_dict={X: xTrain, Y: yTrain})
weight = sess.run(W)
bias = sess.run(b)
print("Training cost=", training_cost, '; ' "W =", weight, '; ' "b =", bias)
print("Testing result...")
test_loss = LinearRegression() # Same function as above
testing_cost = sess.run(test_loss, feed_dict={X: xTest, Y: yTest})
print("Testing cost:", testing_cost)
print("Absolute mean square loss difference:", abs(training_cost - testing_cost))
fitted_prediction = sess.run(W) * xTest + sess.run(b)
print('fitted_prediction = ',fitted_prediction)
答案 0 :(得分:1)
您的yTrain似乎排名2([352,1]),但您尝试与其一起使用的占位符是标量。尝试将Y更改为
Y = tf.placeholder(tf.float32, [None,1])