矩阵乘法不起作用 - Tensorflow
问题描述:
我在使用tensorflow并且正在用于学校项目。在这里,我试图创建一个房屋标识符,我在一张Excel表格上创建了一些数据,将其转换为一个csv文件,然后测试数据是否会被读取。数据被读取,但是当我进行矩阵乘法并且说...时,它会产生多个错误。“ValueError:形状必须是等级2,但是'MatMul'(op:'MatMul')的等级为0,输入形状为:[] ,[1,1]。“非常感谢!矩阵乘法不起作用 - Tensorflow
import tensorflow as tf
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
filename = dir_path+ "\House Price Data .csv"
w1=tf.Variable(tf.zeros([1,1]))
w2=tf.Variable(tf.zeros([1,1])) #Feature 1's weight
w3=tf.Variable(tf.zeros([1,1])) #Feature 1's weight
b=tf.Variable(tf.zeros([1])) #bias for various features
x1= tf.placeholder(tf.float32,[None, 1])
x2= tf.placeholder(tf.float32,[None, 1])
x3= tf.placeholder(tf.float32,[None, 1])
Y= tf.placeholder(tf.float32,[None, 1])
y_=tf.placeholder(tf.float32,[None,1])
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
with open(filename) as inf:
# Skip header
next(inf)
for line in inf:
# Read data, using python, into our features
housenumber, x1, x2, x3, y_ = line.strip().split(",")
x1 = float(x1)
product = tf.matmul(x1, w1)
y = product + b
答
@Aaron是对的,你从csv文件加载数据时覆盖变量。
您需要将加载的值保存到一个单独的变量中,例如_x1
而不是x1
,然后使用feed_dict将值提供给占位符。并且因为x1
的形状为[None,1]
,所以需要将字符串标量_x1
转换为具有相同形状的浮动,在这种情况下为[1,1]
。
import tensorflow as tf
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
filename = dir_path+ "\House Price Data .csv"
w1=tf.Variable(tf.zeros([1,1]))
b=tf.Variable(tf.zeros([1])) #bias for various features
x1= tf.placeholder(tf.float32,[None, 1])
y_pred = tf.matmul(x1, w1) + b
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
with open(filename) as inf:
# Skip header
next(inf)
for line in inf:
# Read data, using python, into our features
housenumber, _x1, _x2, _x3, _y_ = line.strip().split(",")
sess.run(y_pred, feed_dict={x1:[[float(_x1)]]})
它看起来像你正在覆盖x1变量。 – Aaron
来自csv文件的输入是我想要的x1 vatiable。非常感谢你的帮助! – anonymous
我在调试时将x1用作测试示例 – anonymous