先决条件
在使用Tensorflow实现线性回归之前,我们将简要总结线性回归。由于我们不会深入了解线性回归或Tensorflow的细节,请阅读以下文章了解更多细节:
线性回归简介
线性回归是一种非常常见的统计方法,它允许我们从给定的一组连续数据中学习函数或关系。例如,我们得到了一些 x
以及相应的 y
我们需要了解它们之间的关系,这被称为 假设 .
在线性回归的情况下,假设是一条直线,即, 哪里
w
一个向量叫做 砝码 和 b
一个标量叫做 偏见 .权重和偏差称为 参数 模型的一部分。
我们所需要做的就是根据给定的一组数据来估计w和b的值,这样得到的假设产生的成本最小 J
其定义如下: 成本函数 哪里
m
是给定数据集中的数据点数。这个成本函数也被称为 均方误差 .
用于找到所需参数的优化值 J
是最小值,我们将使用一种常用的优化器算法,称为 梯度下降 .以下是梯度下降的伪代码:
Repeat untill Convergence { w = w - α * δJ/δw b = b - α * δJ/δb }
哪里 α
是一个 超参数 打电话给 学习率 .
张量流
Tensorflow是一个由谷歌开发的开源计算库。它是创建需要高端数值计算和/或需要利用图形处理单元进行计算的应用程序的常用选择。这些都是Tensorflow成为机器学习应用,尤其是深度学习最受欢迎的选择之一的主要原因。它还具有类似于估计器的API,在构建机器学习应用程序时提供了高度抽象。在本文中,我们将不使用任何高级API,而是在延迟执行模式下使用低级Tensorflow构建线性回归模型,Tensorflow在该模式下创建 有向无环图 或者DAG,它跟踪所有的计算,然后在一个数据库中执行所有的计算 Tensorflow会话 .
实施
我们将从导入必要的库开始。我们将使用 努比 与Tensorflow一起进行计算和 Matplotlib 用于策划。
Python3
import numpy as np import tensorflow as tf import matplotlib.pyplot as plt |
为了使随机数可预测,我们将为Numpy和Tensorflow定义固定种子。
Python3
np.random.seed( 101 ) tf.set_random_seed( 101 ) |
现在,让我们生成一些随机数据来训练线性回归模型。
Python3
# Generating random linear data # There will be 50 data points ranging from 0 to 50 x = np.linspace( 0 , 50 , 50 ) y = np.linspace( 0 , 50 , 50 ) # Adding noise to the random linear data x + = np.random.uniform( - 4 , 4 , 50 ) y + = np.random.uniform( - 4 , 4 , 50 ) n = len (x) # Number of data points |
让我们将训练数据可视化。
Python3
# Plot of Training Data plt.scatter(x, y) plt.xlabel( 'x' ) plt.xlabel( 'y' ) plt.title( "Training Data" ) plt.show() |
输出:
![图片[3]-使用Tensorflow的线性回归-yiteyi-C++库](https://media.geeksforgeeks.org/wp-content/uploads/random_linear_data.png)
现在我们将通过定义 占位符 X
和 Y
,以便我们能够提供我们的培训示例 X
和 Y
进入 优化器 在培训过程中。
Python3
X = tf.placeholder( "float" ) Y = tf.placeholder( "float" ) |
现在我们将宣布两个可训练的Tensorflow 变量 用于权重和偏差,并使用 np.random.randn()
.
Python3
W = tf.Variable(np.random.randn(), name = "W" ) b = tf.Variable(np.random.randn(), name = "b" ) |
现在我们将定义模型的超参数、学习率和历次数。
Python3
learning_rate = 0.01 training_epochs = 1000 |
现在,我们将构建假设、成本函数和优化器。我们不会手动实现梯度下降优化器,因为它是在Tensorflow内部构建的。之后,我们将初始化变量。
Python3
# Hypothesis y_pred = tf.add(tf.multiply(X, W), b) # Mean Squared Error Cost Function cost = tf.reduce_sum(tf. pow (y_pred - Y, 2 )) / ( 2 * n) # Gradient Descent Optimizer optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost) # Global Variables Initializer init = tf.global_variables_initializer() |
现在我们将在Tensorflow课程中开始训练过程。
Python3
# Starting the Tensorflow Session with tf.Session() as sess: # Initializing the Variables sess.run(init) # Iterating through all the epochs for epoch in range (training_epochs): # Feeding each data point into the optimizer using Feed Dictionary for (_x, _y) in zip (x, y): sess.run(optimizer, feed_dict = {X : _x, Y : _y}) # Displaying the result after every 50 epochs if (epoch + 1 ) % 50 = = 0 : # Calculating the cost a every epoch c = sess.run(cost, feed_dict = {X : x, Y : y}) print ( "Epoch" , (epoch + 1 ), ": cost =" , c, "W =" , sess.run(W), "b =" , sess.run(b)) # Storing necessary values to be used outside the Session training_cost = sess.run(cost, feed_dict = {X: x, Y: y}) weight = sess.run(W) bias = sess.run(b) |
输出:
Epoch: 50 cost = 5.8868036 W = 0.9951241 b = 1.2381054
Epoch: 100 cost = 5.7912707 W = 0.99812365 b = 1.0914398
Epoch: 150 cost = 5.7119675 W = 1.0008028 b = 0.96044314
Epoch: 200 cost = 5.6459413 W = 1.0031956 b = 0.8434396
Epoch: 250 cost = 5.590799 W = 1.0053328 b = 0.7389357
Epoch: 300 cost = 5.544608 W = 1.007242 b = 0.6455922
Epoch: 350 cost = 5.5057883 W = 1.008947 b = 0.56222
Epoch: 400 cost = 5.473066 W = 1.01047 b = 0.48775345
Epoch: 450 cost = 5.4453845 W = 1.0118302 b = 0.42124167
Epoch: 500 cost = 5.421903 W = 1.0130452 b = 0.36183488
Epoch: 550 cost = 5.4019217 W = 1.0141305 b = 0.30877414
Epoch: 600 cost = 5.3848577 W = 1.0150996 b = 0.26138115
Epoch: 650 cost = 5.370246 W = 1.0159653 b = 0.21905091
Epoch: 700 cost = 5.3576994 W = 1.0167387 b = 0.18124212
Epoch: 750 cost = 5.3468933 W = 1.0174294 b = 0.14747244
Epoch: 800 cost = 5.3375573 W = 1.0180461 b = 0.11730931
Epoch: 850 cost = 5.3294764 W = 1.0185971 b = 0.090368524
Epoch: 900 cost = 5.322459 W = 1.0190892 b = 0.0663058
Epoch: 950 cost = 5.3163586 W = 1.0195289 b = 0.044813324
Epoch: 1000 cost = 5.3110332 W = 1.0199214 b = 0.02561663
现在让我们看看结果。
Python3
# Calculating the predictions predictions = weight * x + bias print ( "Training cost =" , training_cost, "Weight =" , weight, "bias =" , bias, '' ) |
输出:
Training cost = 5.3110332 Weight = 1.0199214 bias = 0.02561663
注意,在这种情况下,权重和偏差都是标量。这是因为,我们在训练数据中只考虑了一个因变量。如果我们的训练数据集中有m个因变量,那么权重将是一个m维向量,而偏差将是一个标量。
最后,我们将绘制结果。
Python3
# Plotting the Results plt.plot(x, y, 'ro' , label = 'Original data' ) plt.plot(x, predictions, label = 'Fitted line' ) plt.title( 'Linear Regression Result' ) plt.legend() plt.show() |
输出:
![图片[4]-使用Tensorflow的线性回归-yiteyi-C++库](https://www.yiteyi.com/wp-content/uploads/geeks/geeks_linear_regression_result-1.png)