tensorflow搭建最基本的线性回归模型

写在开头,tensorflow的版本属于2.0-CPU版本。

线性回归模型的分析步骤如下

  1. 线性回归模型数学表达式如下。
    y=w1*x1+w2*x2+。。。+w_n*x_n+bias

    2.准备好模型的数据,假设本文实现的线性回归只有一个特征,故模型数据取1000个,构建模型自定为。

y = x *0.7 + 0.8

    3.建立模型,随机初始化一个W和一个bias,在这里模型参数必须为tensorflow中的变量,因为variable类型是默认可以被模型训练的。

y_predict = x *w +bias

     4.求损失,线性回归的损失使用均方误差计算出来的。

loss = ((y_1预测-y_1真实)^2+……+(y_1000预测-y_1000真实)^2)/1000

    5.最后使用梯度下降函数来训练loss。

最后贴上实现代码

import tensorflow as tf
import os

def myLinearRegression():
    """
    使用TensorFlow中的API实现的一个简单线性回归模型
    :return: None
    """
    with tf.compat.v1.variable_scope("data"):
        # 实现步骤:
        # 第一步:准备好线性回归模型的数据 1000个样本 一个特征值
        # 实现模型 y = w x +b
        x = tf.random.normal([1000, 1], mean=1.70, stddev=1)

        y = tf.matmul(x, [[0.7]]) + 0.8

    with tf.compat.v1.variable_scope("model"):
        # 第二步:构建线性回归模型
        # 1.初始化 weight 和 bias ,使用变量定义
        # 因为这两个系数需要训练 Variable 默认是可被训练的类型
        weight = tf.Variable(tf.random.normal([1, 1], mean=0.0, stddev=1.0))

        bias = tf.Variable(0.0)

        # 2.初始化变量(全局变量初始化)
        variable_op = tf.compat.v1.global_variables_initializer()

    with tf.compat.v1.variable_scope("loss"):
        # 3.线性回归模型建立
        y_predict = tf.matmul(x, weight) + bias

        # 第三步:利用均方误差计算线性回归的损失(loss)

        loss = tf.reduce_mean(tf.square(y-y_predict))

        loss_op = tf.compat.v1.train.GradientDescentOptimizer(learning_rate=0.1).minimize(loss)

    # 定义一个保存模型的实例
    saver = tf.compat.v1.train.Saver()

    with tf.compat.v1.Session() as sess:
        # 运行全局变量初始化这个OP
        sess.run(variable_op)
        print("初始化时,模型的权重为{},偏值为{}".format(weight.eval()[0][0], bias.eval()))
        # 先判断模型文件是否存在
        if os.path.exists("./temp/ckpt/checkpoint"):
            #加载训练模型
            saver.restore(sess, "./temp/ckpt/model")
            print("模型加载后为,模型的权重为{},偏值为{}".format(weight.eval()[0][0], bias.eval()))

        for i in range(100):

            sess.run(loss_op)

            print("训练{}次后,模型的权重为{},偏值为{}".format(i, weight.eval()[0][0], bias.eval()))
        #保存训练好的模型
        saver.save(sess, "./temp/ckpt/model")

    return None


if __name__ == '__main__':
    myLinearRegression()

文章最后贴上一张,线性回归模型训练的GIF图

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值