Tensorflow线性拟合 线性回归代码

import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
import tensorflow as tf

import numpy as np
import matplotlib.pyplot as plt

train_X = np.linspace(-np.pi, np.pi, 100)
# train_Y = np.sin(train_X) 
train_Y = train_X * 2 + 1 + np.random.randn(len(train_X))

X = tf.placeholder("float")
Y = tf.placeholder("float")

W = tf.Variable(np.random.randn())
b = tf.Variable(np.random.randn())

out = tf.add(tf.multiply(X, W), b)

sess = tf.Session()
sess.run(tf.global_variables_initializer())

# cost = tf.reduce_sum(tf.multiply(out-Y, out-Y))/(2*train_X.shape[0])
cost = tf.reduce_sum(tf.pow(out-Y, 2))

# cost = tf.pow(out-Y, 2)
# print(sess.run(cost, feed_dict={X:[1, 2], Y:[1,2]}))
# os._exit()

optimizer = tf.train.GradientDescentOptimizer(0.001).minimize(cost)

for epoch in range(200):
    for (x, y) in zip(train_X, train_Y):
        sess.run(optimizer, feed_dict={X: x, Y: y})

    if epoch % 50 == 0:
        print (f"epoch={epoch:4}, cost={sess.run(cost, feed_dict={X: train_X, Y:train_Y}):8.4}, \
W={sess.run(W):8.4}, b={sess.run(b):8.4}")

plt.plot(train_X, train_Y, 'ro', label='Original data')
plt.plot(train_X, sess.run(W) * train_X + sess.run(b), label='Fitted line')
plt.legend()
plt.show()

sess.close()
参考:https://zhuanlan.zhihu.com/p/30486925


发表于:2017-11-14 15:48:27

原文链接(转载请保留): http://www.multisilicon.com/blog/a22325849.html

友情链接: MICROIC
首页