Tensorflow 线性回归

本文通过使用TensorFlow框架,实现了一个简单的线性回归模型,以预测数据集中的线性关系。首先,生成了一组带有随机噪声的数据点,然后使用梯度下降法训练模型,以最小化预测值与实际值之间的平方误差。
import numpy as np
复制代码
data_x = np.linspace(0, 10, 100)
复制代码
data_y = data_x *3 + 7 + np.random.normal(0, 1, 100)
复制代码
import matplotlib.pyplot as plt
%matplotlib inline
复制代码
plt.scatter(data_x, data_y)
复制代码
<matplotlib.collections.PathCollection at 0x10dbfe908>
复制代码

import tensorflow as tf
复制代码
/anaconda3/envs/py35/lib/python3.5/importlib/_bootstrap.py:222: RuntimeWarning: compiletime version 3.6 of module 'tensorflow.python.framework.fast_tensor_util' does not match runtime version 3.5
  return f(*args, **kwds)
/anaconda3/envs/py35/lib/python3.5/site-packages/h5py/__init__.py:36: FutureWarning: Conversion of the second argument of issubdtype from `float` to `np.floating` is deprecated. In future, it will be treated as `np.float64 == np.dtype(float).type`.
  from ._conv import register_converters as _register_converters
复制代码
w = tf.Variable(1., name='quanzhong')
b = tf.Variable(0., name='pianzhi')
复制代码
x = tf.placeholder(tf.float32, shape=None)
复制代码
y = tf.placeholder(tf.float32, shape=[None])
复制代码
pred = tf.multiply(x, w) + b
复制代码
loss = tf.reduce_sum(tf.squared_difference(pred, y))
复制代码
learn_rate = 0.0001
train_step = tf.train.GradientDescentOptimizer(learn_rate).minimize(loss)
复制代码
sess = tf.Session()
sess.run(tf.global_variables_initializer())
复制代码
for i in range(10000):
    sess.run(train_step, feed_dict={x:data_x, y:data_y})
    if i%1000 == 0:
        print(sess.run([loss, w ,b], feed_dict={x:data_x, y:data_y}))
    
复制代码
[4275.1426, 3.0419059, 0.34032884]
[92.10727, 3.007915, 6.965689]
[92.055786, 3.0011888, 7.010422]
[92.05579, 3.0011494, 7.0106854]
[92.05579, 3.0011494, 7.0106854]
[92.05579, 3.0011494, 7.0106854]
[92.05579, 3.0011494, 7.0106854]
[92.05579, 3.0011494, 7.0106854]
[92.05579, 3.0011494, 7.0106854]
[92.05579, 3.0011494, 7.0106854]
复制代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值