码迷,mamicode.com
首页 > 其他好文 > 详细

4.线性回归

时间:2019-09-28 23:31:26      阅读:80      评论:0      收藏:0      [点我收藏+]

标签:src   err   lob   png   port   array   ima   atp   normal   

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
x_data = np.random.rand(100)
noise = np.random.normal(0,0.01,x_data.shape)
y_data = x_data*0.1 + 0.2 + noise

plt.scatter(x_data, y_data)
plt.show()

技术图片

# 构建一个线性模型
d = tf.Variable(np.random.rand(1))
k = tf.Variable(np.random.rand(1))
y = k*x_data + d

# 二次代价函数
loss = tf.losses.mean_squared_error(y_data, y)
# 定义一个梯度下降法优化器
optimizer = tf.train.GradientDescentOptimizer(0.3)
# 最小化代价函数
train = optimizer.minimize(loss)

# 初始化变量
init= tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    for i in range(201):
        sess.run(train)
        if i%20==0:
            print(i,sess.run([k,d]))
    y_pred = sess.run(y)
    plt.scatter(x_data,y_data)
    plt.plot(x_data,y_pred,r-,lw=3)
    plt.show()
0 [array([0.42558686]), array([0.07772181])]
20 [array([0.24686251]), array([0.1212207])]
40 [array([0.17103131]), array([0.16282419])]
60 [array([0.13410329]), array([0.18308412])]
80 [array([0.1161202]), array([0.19295024])]
100 [array([0.10736286]), array([0.1977548])]
120 [array([0.10309823]), array([0.20009452])]
140 [array([0.10102146]), array([0.2012339])]
160 [array([0.10001012]), array([0.20178875])]
180 [array([0.09951763]), array([0.20205895])]
200 [array([0.09927779]), array([0.20219054])]

技术图片

4.线性回归

标签:src   err   lob   png   port   array   ima   atp   normal   

原文地址:https://www.cnblogs.com/liuwenhua/p/11605338.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!