简单线性回归的Tensorflow实现

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,但结果并没有得到很大的改善。

我的实现有什么问题吗?


我在你的代码中没有看到error_function的定义。这个和cost_functions一样吗?你尝试降低学习率了吗? - shekkizh
抱歉,我是指 cost_function。我已经修复了。感谢您的评论。 - Firman
2个回答

5
这是因为y的形状与y_不同。y的形状为(1000, 1),而y_的形状为(1000)。所以当你减去它们时,无意中创建了一个2-D矩阵。
要修复它,请将您的代价函数更改为:
cost_function = tf.reduce_mean(tf.square(tf.squeeze(y) - y_))

-2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接