使用TensorFlow进行线性回归

本文介绍使用TensorFlow进行线性回归拟合。先随机生成数据,预期拟合函数为Y = 30X + 100,假设拟合函数为y = Wx + b,给W、b赋初值,用梯度下降算法减小y与实际值差距,定义损失函数,最后完成训练,拟合结果不错。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文首发在我的个人博客:https://jlice.top/p/7hmgi/。欢迎大家前去参观,么么哒~

我们先随机生成一些数据:

import numpy as np

train_X = 20 * np.random.rand(100).astype(np.float32)
train_Y = (30 * train_X + 100 + 10 * np.random.randn(100)).astype(np.float32)

https://jlice-top.oss-cn-beijing.aliyuncs.com/449b48d8002211e9b2eb509a4c21c90b.png

预期拟合的函数为:

\[ Y = 30 X + 100 \]

现在我们使用线性回归,假设拟合的函数为:

\[ y = W x + b \]

先给W、b赋初值,然后计算y和实际值的差距,并使用梯度下降算法来减小差距。定义这个差距(损失函数)为:

\[ C = \frac 1 {2m} \sum _{i=1} ^{m} (Y_i - y_i)^2 \]

现在使用TensorFlow来完成。

首先定义变量:

import tensorflow as tf

W = tf.Variable(1.0)
b = tf.Variable(0.0)
X = tf.placeholder(tf.float32)
Y = tf.placeholder(tf.float32)
y = tf.add(tf.multiply(W, X), b)
cost = tf.reduce_sum(tf.pow(Y-y, 2))/(2*train_X.shape[0])

W、b是待训练的参数,使用tf.Variable;X、Y接收输入的数据,使用tf.placeholder

然后开始训练:

init = tf.global_variables_initializer()
train = tf.train.GradientDescentOptimizer(0.2).minimize(cost)

with tf.Session() as sess:
    sess.run(init)
    for i in range(100):
        for tx, ty in zip(train_X, train_Y):
            sess.run(train, feed_dict={X: tx, Y: ty})

        if (i+1) % 10 == 0:
            c = sess.run(cost, feed_dict={X: train_X, Y: train_Y})
            print('epoch: %d   cost:%f   y = %f x + %f' % (i + 1, c, sess.run(W), sess.run(b)))

https://jlice-top.oss-cn-beijing.aliyuncs.com/44b897b8002211e99a2d509a4c21c90b.gif

可以看到,拟合的结果还不错。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值