TensorFlow 实现线性回归

1、生成高斯分布的随机数

导入numpy模块,通过numpy模块内的方法生成一组在方程

y = 2 * x + 3

周围小幅波动的随机坐标。代码如下:

 1 import numpy as np
 2 import matplotlib.pyplot as plot
 3
 4
 5 def getRandomPoints(count):
 6     xList = []
 7     yList = []
 8     for i in range(count):
 9         x = np.random.normal(0, 0.5)
10         y = 2 * x + 3 + np.random.normal(0, 0.3)
11         xList.append(x)
12         yList.append(y)
13     return xList, yList
14
15
16 if __name__ == ‘__main__‘:
17     X, Y = getRandomPoints(1000)
18     plot.scatter(X, Y)
19     plot.show()

运行上述代码,输出图形如下:

2、采用TensorFlow来获取上述方程的系数

  首先搭建基本的预估模型y = w * x + b,然后再采用梯度下降法进行训练,通过最小化损失函数的方法进行优化,最终训练得出方程的系数。

  在下面的例子中,梯度下降法的学习率为0.2,训练迭代次数为100次。

 1 def train(x, y):
 2     # 生成随机系数
 3     w = tf.Variable(tf.random_uniform([1], -1, 1))
 4     # 生成随机截距
 5     b = tf.Variable(tf.random_uniform([1], -1, 1))
 6     # 预估值
 7     preY = w * x + b
 8
 9     # 损失值:预估值与实际值之间的均方差
10     loss = tf.reduce_mean(tf.square(preY - y))
11     # 优化器:梯度下降法,学习率为0.2
12     optimizer = tf.train.GradientDescentOptimizer(0.2)
13     # 训练:最小化损失函数
14     trainer = optimizer.minimize(loss)
15
16     with tf.Session() as sess:
17         sess.run(tf.global_variables_initializer())
18         # 打印初始随机系数
19         print(‘init w:‘, sess.run(w), ‘b:‘, sess.run(b))
20         # 先训练个100次:
21         for i in range(100):
22             sess.run(trainer)
23             # 每10次打印下系数
24             if i % 10 == 9:
25                 print(‘w:‘, sess.run(w), ‘b:‘, sess.run(b))
26
27
28 if __name__ == ‘__main__‘:
29     X, Y = getRandomPoints(1000)
30     train(X, Y)

  运行上面的代码,某次的最终结果为:

w = 1.9738449
b = 3.0027733

仅100次的训练迭代,得出的结果已十分接近方程的实际系数。

  某次模拟训练中的输出结果如下:

init w: [-0.6468966] b: [0.52244043]
w: [1.0336646] b: [2.9878206]
w: [1.636582] b: [3.0026987]
w: [1.8528996] b: [3.0027785]
w: [1.930511] b: [3.0027752]
w: [1.9583567] b: [3.0027738]
w: [1.9683474] b: [3.0027735]
w: [1.9719319] b: [3.0027733]
w: [1.9732181] b: [3.0027733]
w: [1.9736794] b: [3.0027733]
w: [1.9738449] b: [3.0027733]

3、完整代码和结果

完整测试代码:

 1 import numpy as np
 2 import matplotlib.pyplot as plot
 3 import tensorflow as tf
 4
 5
 6 def getRandomPoints(count, xscale=0.5, yscale=0.3):
 7     xList = []
 8     yList = []
 9     for i in range(count):
10         x = np.random.normal(0, xscale)
11         y = 2 * x + 3 + np.random.normal(0, yscale)
12         xList.append(x)
13         yList.append(y)
14     return xList, yList
15
16
17 def train(x, y, learnrate=0.2, cycle=100):
18     # 生成随机系数
19     w = tf.Variable(tf.random_uniform([1], -1, 1))
20     # 生成随机截距
21     b = tf.Variable(tf.random_uniform([1], -1, 1))
22     # 预估值
23     preY = w * x + b
24
25     # 损失值:预估值与实际值之间的均方差
26     loss = tf.reduce_mean(tf.square(preY - y))
27     # 优化器:梯度下降法
28     optimizer = tf.train.GradientDescentOptimizer(learnrate)
29     # 训练:最小化损失函数
30     trainer = optimizer.minimize(loss)
31
32     with tf.Session() as sess:
33         sess.run(tf.global_variables_initializer())
34         # 打印初始随机系数
35         print(‘init w:‘, sess.run(w), ‘b:‘, sess.run(b))
36         for i in range(cycle):
37             sess.run(trainer)
38             # 每10次打印下系数
39             if i % 10 == 9:
40                 print(‘w:‘, sess.run(w), ‘b:‘, sess.run(b))
41         return sess.run(w), sess.run(b)
42
43
44 if __name__ == ‘__main__‘:
45     X, Y = getRandomPoints(1000)
46     w, b = train(X, Y)
47     plot.scatter(X, Y)
48     plot.plot(X, w * X + b, c=‘r‘)
49     plot.show()

  最终效果图如下,蓝色为高斯随机分布数据,红色为最终得出的直线:

本文地址:https://www.cnblogs.com/laishenghao/p/9571343.html

原文地址:https://www.cnblogs.com/laishenghao/p/9571343.html

时间: 2024-08-30 14:28:56

TensorFlow 实现线性回归的相关文章

如何用TensorFlow实现线性回归

环境Anaconda 废话不多说,关键看代码 import tensorflow as tf import os os.environ['TF_CPP_MIN_LOG_LEVEL']='2' tf.app.flags.DEFINE_integer("max_step", 300, "训练模型的步数") FLAGS = tf.app.flags.FLAGS def linear_regression(): ''' 自实现线性回归 :return: ''' #1.准备1

tensorflow 学习1——tensorflow 做线性回归

1. 首先 Numpy: Numpy是Python的科学计算库,提供矩阵运算. 想想list已经提供了矩阵的形式,为啥要用Numpy,因为numpy提供了更多的函数. 使用numpy,首先要导入numpy: import numpy as np 使用numpy创建数组以list 或tuple作为参数: np.array([1,2,3,4]) np.array((1.2,2,3,4)) 使用numpy可以指定数据类型: numpy.int32, numpy.int16, numpy.float64

tensorflow训练线性回归模型

完整代码 import tensorflow as tf import matplotlib.pyplot as plt import numpy as np #样本数据 x_train = np.linspace(-1,1,300)[:,np.newaxis] noise = np.random.normal(0, 0.1, x_train.shape) y_train = x_train * 3 + noise + 0.8 #线性模型 W = tf.Variable([0.1],dtype

自学tensorflow——2.使用tensorflow计算线性回归模型

废话不多说,直接开始 1.首先,导入所需的模块: import numpy as np import os import tensorflow as tf 关闭tensorflow输出的一大堆硬件信息 os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' 2.写一个函数generate_data(),用来生成我们所需要的数据,这里使用的线性函数是y = 0.1*x + 0.3,具体解释见注释 def generate_data():#随机生成测试数据 num_poin

tensorflow版线性回归

import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' import tensorflow as tf def linearregression(): X = tf.random_normal([100,1],mean=0.0,stddev=1.0) y_true = tf.matmul(X,[[0.8]]) + [[0.7]] weights = tf.Variable(initial_value=tf.random_normal([1,1]))

TensorFlow经典案例3:实现线性回归

TensorFlow实现线性回归 #实现线性回归 import tensorflow as tf import numpy as np import matplotlib.pyplot as plt rng = np.random learn_rate = 0.01 training_epochs = 1000 display_step = 50 #生成训练数据 train_X = np.asarray([3.3,4.4,5.5,6.71,6.93,4.168,9.779,6.182,7.59,

线性回归模型的 MXNet 与 TensorFlow 实现

本文主要探索如何使用深度学习框架 MXNet 或 TensorFlow 实现线性回归模型?并且以 Kaggle 上数据集 USA_Housing 做线性回归任务来预测房价. 回归任务,scikit-learn 亦可以实现,具体操作可以查看 线性回归模型的原理与 scikit-learn 实现. 载入数据 import pandas as pd import numpy as np name = '../dataset/USA_Housing.csv' dataset = pd.read_csv(

tensorflow笔记(一)之基础知识

tensorflow笔记(一)之基础知识 版权声明:本文为博主原创文章,转载请指明转载地址 http://www.cnblogs.com/fydeblog/p/7399701.html 前言 这篇notebook将一步步构建一个tensorflow的线性回归的例子,并讲述其中的一些基础知识.我会把notebook文件放在结尾的百度云链接. 首先第一步,要安装tensorflow,这个网上的教程很多,我安装的版本是ubuntu下1.2.1的tensorflow,推荐用pip(一步就好)这里附上一个

使用线性回归识别手写阿拉伯数字mnist数据集

学习了tensorflow的线性回归. 首先是一个sklearn中makeregression数据集,对其进行线性回归训练的例子.来自腾讯云实验室 import tensorflow as tf import numpy as np class linearRegressionModel: def __init__(self,x_dimen): self.x_dimen=x_dimen self._index_in_epoch=0 self.constructModel() self.sess=