gpt4 book ai didi

python - TensorFlow多元线性回归占位符和矩阵乘法误差

转载 作者:行者123 更新时间:2023-12-01 07:47:27 25 4
gpt4 key购买 nike

我正在使用 auto-mpg.data。我遇到了这个问题:

回溯(最近一次调用最后一次): 文件“C:/PythonProjects/test5.py”,第 60 行,位于 _, c = sess.run([optimizer, loss], feed_dict={X: xTrain, Y: yTrain}) # 获取损失值 文件“C:\Python3\lib\site-packages\tensorflow\python\client\session.py”,第 929 行,运行中 运行元数据指针) 文件“C:\Python3\lib\site-packages\tensorflow\python\client\session.py”,第 1128 行,在 _run 中 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)

最佳答案

看起来你的 yTrain 是排名 2 ( [352,1] ),但你试图用它提供的占位符是一个标量。尝试将 Y 更改为

Y = tf.placeholder(tf.float32, [None,1])

关于python - TensorFlow多元线性回归占位符和矩阵乘法误差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56398313/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com