2020-09-09

python tf学习(一) 手动实现线性回归

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression


# 产生数据
x = np.linspace(-5, 5, 20)
y = np.linspace(-5, 5, 20)
x += np.random.randn(20)
y += np.random.randn(20)

# 使用线性回归模型训练数据
linear = LinearRegression()
linear.fit(x.reshape(-1, 1), y)

# 训练后的模型可以得出系数w和截距b
w = linear.coef_
b = linear.intercept_
plt.scatter(x, y)

X_model = np.linspace(-5, 5, 520)
Y_model = w * X_model + b
plt.plot(X_model, Y_model, c='r')
plt.rcParams['font.family']=['SimHei']


# 手动算法的三个步骤
#
# 确定算法的目标函数. y = wx + b (θX)
# 确定算法的损失函数. 最小二乘法 sum((y - y_pred)^2)
# 使用梯度下降法求损失函数最小的时候的系数.

# 使用TensorFlow实现线性回归
# 定义阶段
# 样本数据定义为占位符
X = tf.placeholder(dtype=tf.float64)
Y = tf.placeholder(dtype=tf.float64)
# 需要求算的w , b 定义为变量
W_ = tf.Variable(initial_value=np.random.randn(), dtype=tf.float64)
B_ = tf.Variable(initial_value=0, dtype=tf.float64)
Y_pred = tf.add(tf.multiply(W_, X), B_)
# 最小二乘法sum((y - y_pred)^2) 再除以个数,人为减小损失
loss = tf.reduce_mean(tf.square(Y - Y_pred))
# 定义梯度下降法优化w和b, 找到最小损失时候的w b
optimizer = tf.train.GradientDescentOptimizer(0.005).minimize(loss)
init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
# 分批给所有数据, 一个数据一个数据喂
    for i in range(10000):
        for x_train, y_train in zip(x, y):
            sess.run(optimizer, feed_dict={X: x_train, Y: y_train})

        if i % 100 == 0:
            # 打印W, B和损失
            W = sess.run(W_)
            B = sess.run(B_)
            cost = sess.run(loss, feed_dict={X: x, Y: y})
            print(f'第{i}次训练, 斜率:{W}, 截距: {B}, 损失:{cost}')
            # 打印最终结果
    W = sess.run(W_)
    B = sess.run(B_)
    cost = sess.run(loss, feed_dict={X: x, Y: y})
    print(f'线性回归模型, 斜率:{w}, 截距: {b}\n手动实现线性, 斜率:{W}, 截距: {B}, 损失:{cost}')


Y_tf = W * X_model + B
plt.plot(X_model, Y_tf, c='g')
plt.legend(["线性模型", "手动实现"])
plt.show()


在这里插入图片描述
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值