2016-05-17 70 views
4

我是机器学习和张量流的初学者。在第一步尝试tensorflow,我尝试了一个简单的多元线性回归。但是,这个模型似乎停留在当地的最低水平。这是我的代码。关于简单线性回归的Tensorflow

import numpy as np 
import tensorflow as tf 
import matplotlib.pyplot as plt 

def weight_variable(shape): 
    initial = tf.truncated_normal(shape, stddev=1) 
    return tf.Variable(initial) 

# dataset 
xx = np.random.randint(0,1000,[1000,3])/1000. 
yy = xx[:,0] * 2 + xx[:,1] * 1.4 + xx[:,2] * 3 

# model 
x = tf.placeholder(tf.float32, shape=[None, 3]) 
y_ = tf.placeholder(tf.float32, shape=[None]) 
W1 = weight_variable([3, 1]) 
y = tf.matmul(x, W1) 

# training and cost function 
cost_function = tf.reduce_mean(tf.square(y - y_)) 
train_function = tf.train.AdamOptimizer(1e-2).minimize(cost_function) 

# create a session 
sess = tf.Session() 

# train 
sess.run(tf.initialize_all_variables()) 
for i in range(10000): 
    sess.run(train_function, feed_dict={x:xx, y_:yy}) 
    if i % 1000 == 0: 
     print(sess.run(cost_function, feed_dict={x:xx, y_:yy})) 

的输出是:

14.8449 
2.20154 
2.18375 
2.18366 
2.18366 
2.18366 
2.18366 
2.18366 
2.18366 

输出值(YY)是范围从0到6,所以具有均方误差2.18是相当大的,知道没有噪声添加到数据集。 我也尝试了学习率为0.1和1e-2的GradientDescentOptimizer,但它并没有提高效果。

我的实施有什么问题吗?

+0

我没有看到error_function de在你的代码中罚款。这与cost_functions相同吗?你尝试降低你的学习率吗? – shekkizh

+0

对不起,我的意思是'cost_function'。我修好了。感谢您的评论。 – Firman

回答

5

这是因为yy_形状不一样。 y是形状(1000,1)和y_是形状(1000)。所以当你减去它们时,你无意中创建了一个2-D矩阵。

要修复它改变你的成本函数:

cost_function = tf.reduce_mean(tf.square(tf.squeeze(y) - y_)) 
-2

作为另一个答复中提到,我只好用

predictions = tf.add(b, tf.matmul(x, w)) 
error = tf.reduce_mean(tf.square(y - predictions)) 

正如你说的,你是一个Tensorflow初学者,你可以看看这里的例子: -

https://medium.com/@saxenarohan97/intro-to-tensorflow-solving-a-simple-regression-problem-e87b42fd4845

+0

虽然这个链接可能回答这个问题,但最好在这里包含答案的重要部分并提供参考链接。如果链接页面更改,则仅链接答案可能会失效。 - [来自评论](/ review/low-quality-posts/18667877) – Liam

+0

好的,我编辑了我的答案 –