在模型训练后获得错误的权重值

时间:2018-05-03 21:19:18

标签: python tensorflow linear-regression

我在TensorFlow中实现了线性回归模型。

import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
import time

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

import utils

DATA_FILE = 'data/birth_life_2010.txt'


data, n_samples = utils.read_birth_life_data(DATA_FILE)`
X = tf.placeholder(tf.float32, name ='X')
Y = tf.placeholder(tf.float32,name = 'Y') 
w = tf.Variable(np.random.randn(), name = 'w')
b = tf.Variable(np.random.randn(), name = 'b')
Y_predicted = w * X + b
loss = tf.square(Y - Y_predicted, name='loss')
opt = tf.train.GradientDescentOptimizer(learning_rate = 0.001)
optimizer = opt.minimize(loss)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
        for epoch in range(100):

            for x,y in data:
                sess.run([optimizer,loss], feed_dict={X:x,Y:x})

    w_out,b_out = sess.run([w,b])
plt.plot(data[:,0], data[:,1], 'bo', label='Real data')
plt.plot(data[:,0], data[:,0] * w_out + b_out, 'r', label='Predicted 
data')
plt.legend()
plt.show()

这是情节:

fitted vs actual values

好像我已经学会了绝对不好的参数。我做错了什么?

1 个答案:

答案 0 :(得分:0)

您应该考虑分批培训。目前,您的实施一次只需要一个样本。