我是一个使用Tensorflow的新手,正在为学校项目使用它。我试图制作一个房屋识别器,我在Excel表格中制作了一些数据,然后将其转换为csv文件,并测试数据是否能被读取。数据确实被读取了,但当我进行矩阵乘法时出现了多个错误,错误信息显示为… “ValueError: Shape must be rank 2 but is rank 0 for ‘MatMul’ (op: ‘MatMul’) with input shapes: [], [1,1]。”非常感谢!
import tensorflow as tfimport osdir_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 weightw3=tf.Variable(tf.zeros([1,1])) #Feature 1's weightb=tf.Variable(tf.zeros([1])) #bias for various featuresx1= 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 tfimport osdir_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 featuresx1= tf.placeholder(tf.float32,[None, 1])y_pred = tf.matmul(x1, w1) + bwith 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)]]})