TensorFlow实现一元线性回归

本文通过使用TensorFlow实现线性回归,展示了如何利用Python进行数据拟合,通过梯度下降法最小化损失函数,最终得到最佳拟合直线。

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

  • 代码
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

train_x = np.array([[3.3], [4.4], [5.5], [6.71], [6.93], [4.168], [9.779], [6.128],
                    [7.59], [2.167], [7.042], [10.791], [5.313], [7.997], [5.654],
                    [9.27], [3.1]])
train_y = np.array([[1.7], [2.76], [2.09], [3.19], [1.649], [1.573], [3.366], 
                    [2.596], [2.53], [1.221], [2.827], [3.465], [1.65], [2.904],
                    [2.42], [2.94], [1.3]])
total_samples = train_x.shape[0]
#total_samples = tf.constant(17.)
x = tf.placeholder(dtype = tf.float32, shape = (None, 1))
w = tf.Variable(initial_value = [[1]], dtype = tf.float32)
b = tf.Variable(tf.zeros(1), dtype = tf.float32)
y = tf.matmul(x, w) + b
y_ = tf.placeholder(dtype = tf.float32, shape = (None, 1))
global_step = tf.Variable(0, trainable = False)
loss = tf.reduce_sum(tf.pow(y - y_, 2)) / total_samples
optimizer = tf.train.GradientDescentOptimizer(learning_rate = 0.01)
train_op = optimizer.minimize(loss = loss, global_step = global_step)

with tf.Session() as sess:
  sess.run(tf.global_variables_initializer())
  while global_step.eval() < 2000:
    sess.run(train_op, feed_dict = {x:train_x, y_:train_y})
    print('step:%d, w = %f, b = %f, loss = %f' % (global_step.eval(), w.eval(), b.eval(), loss.eval(feed_dict = {x:train_x, y_:train_y})))
    
    plt.plot(train_x, train_y, 'ro')
    plt.plot(train_x, w.eval() * train_x + b.eval())
    plt.show()

可以看到拟合直线的变化过程,如下图
在这里插入图片描述

  • 最终结果如下图
    在这里插入图片描述
    共迭代2000步,最终w = 0.252106, b = 0.793189, loss = 0.158868
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值