请记住,我对tf非常陌生。
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_boston
np.set_printoptions(suppress=True)
boston = load_boston()
m = boston.data.shape[0] - 1
bt_unfixed = np.transpose(boston.data)
bt = np.insert(bt_unfixed, 0, 1)
Y = tf.placeholder(tf.float64)
X = tf.placeholder(tf.float64, [None, 13])
print X.shape
W = tf.Variable(np.transpose(np.array([0.00,0,0,0,0,0,0,0,0,0,0,0,0]).flatten()), name='weights')
b = tf.Variable(0.5, name='bias')
hypothesis = tf.add(tf.matmul(X, W), tf.cast(b, tf.float64))
loss = tf.reduce_sum(tf.square(hypothesis - Y)) / (2 * m)
optimizer = tf.train.GradientDescentOptimizer(0.01)
train_op = optimizer.minimize(loss)
with tf.Session() as sess:
sess.run(tf.initialize_all_variables())
for i in range(0, 1200):
for (x, y) in zip(boston.data, boston.target.data):
sess.run(train_op, feed_dict={X:x, Y:y})
print "Done!\n"
print "Running test...\n"
t = sess.run(cost, feed_dict={X:boston.data[504], Y:boston.target.data[504]})
print "loss =" + str(t) + "Real value" + str(boston.target.data[504]) + "Pred " +str(sess.run(hypothesis, feed_dict={X:boston.data[504]}))
请随时更正我的代码中的任何其他错误!
当我定义假设时会抛出错误,我需要转置我的向量以将它们相乘,但它不起作用。
Traceback (most recent call last):
File "multihouse.py", line 20, in <module>
hypothesis = tf.add(tf.matmul(X, W), tf.cast(b, tf.float64))
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/math_ops.py", line 1398, in matmul
name=name)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/gen_math_ops.py", line 1348, in _mat_mul
transpose_b=transpose_b, name=name)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/op_def_library.py", line 749, in apply_op
op_def=op_def)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 2382, in create_op
set_shapes_for_outputs(ret)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 1783, in set_shapes_for_outputs
shapes = shape_func(op)
File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/common_shapes.py", line 596, in call_cpp_shape_fn
raise ValueError(err.message)
ValueError: Shape must be rank 2 but is rank 1
答案 0 :(得分:0)
问题是没有像numpy中的矢量转置这样的东西。你必须定义一个具有一个平凡维度的矩阵来处理这些事情,例如
np.array([0.00,0,0,0,0,0,0,0,0,0,0,0,0]) # this cannot be transposed
np.array([[0.00,0,0,0,0,0,0,0,0,0,0,0,0]]) # this can
就像在这个例子中一样
>>> import numpy as np
>>> np.transpose(np.array([1,1,1]))
array([1, 1, 1])
>>> np.transpose(np.array([[1,1,1]]))
array([[1],
[1],
[1]])
一旦你解决了这个问题,你的假设就会被正确定义(现在你试图将矩阵与一个向量相乘,而这个向量在TF中没有定义)。