tensorflow线性回归

本文通过使用TensorFlow实现线性回归模型,演示了如何从随机生成的数据中学习最佳的参数A和B来拟合直线y = Ax + B。模型通过梯度下降法进行优化,并展示了每5步训练后的拟合情况。

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

# -*- coding: utf-8 -*-
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

__author__ = 'BrownWong'

# 产生数据
number_of_points = 200
x_point = []
y_point = []
a = 0.22
b = 0.78
for i in range(number_of_points):
    x = np.random.normal(0.0, 0.5)
    y = a * x + b + np.random.normal(0.0, 0.1)
    x_point.append([x])
    y_point.append([y])

# 拟合模型
A = tf.Variable(tf.random_uniform([1], -1., 1.))
B = tf.Variable(tf.zeros([1]))
y = A * x_point + B
cost_func = tf.reduce_mean(tf.square(y - y_point))
optimizer = tf.train.GradientDescentOptimizer(.5)
train = optimizer.minimize(cost_func)
init_op = tf.initialize_all_variables()
with tf.Session() as session:
    session.run(init_op)
    for step in xrange(100):
        session.run(train)
        if step % 5 == 0:
            print('Current, Step: %s, A=%s, B=%s' % (step, session.run(A), session.run(B)))
            plt.plot(x_point, y_point, 'o', label='step = {}'.format(step))
            plt.plot(x_point, session.run(A) * x_point + session.run(B))
            plt.legend()
            plt.show()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值