Tensorflow 简明教程
TensorFlow - Linear Regression
在本章中,我们将重点关注使用 TensorFlow 实现线性回归的基本示例。逻辑回归或线性回归是一种监督机器学习方法,用于对有序离散类别进行分类。我们在本章中的目标是构建一个模型,用户可以通过该模型来预测预测变量和一个或多个自变量之间的关系。
In this chapter, we will focus on the basic example of linear regression implementation using TensorFlow. Logistic regression or linear regression is a supervised machine learning approach for the classification of order discrete categories. Our goal in this chapter is to build a model by which a user can predict the relationship between predictor variables and one or more independent variables.
这两个变量之间的关系被认为是线性的。如果 y 是因变量,x 被视为自变量,那么两个变量的线性回归关系将如下方程式所示 −
The relationship between these two variables is cons −idered linear. If y is the dependent variable and x is considered as the independent variable, then the linear regression relationship of two variables will look like the following equation −
Y = Ax+b
我们将设计一个线性回归算法。这将使我们理解以下两个重要概念 −
We will design an algorithm for linear regression. This will allow us to understand the following two important concepts −
-
Cost Function
-
Gradient descent algorithms
线性回归的示意图如下所示 −
The schematic representation of linear regression is mentioned below −
线性回归方程的图形视图如下:
The graphical view of the equation of linear regression is mentioned below −
Steps to design an algorithm for linear regression
现在我们将了解有关设计线性回归算法的帮助步骤。
We will now learn about the steps that help in designing an algorithm for linear regression.
Step 1
对于绘制线性回归模块非常重要的模块是导入。我们开始导入 Python 库 NumPy 和 Matplotlib。
It is important to import the necessary modules for plotting the linear regression module. We start importing the Python library NumPy and Matplotlib.
import numpy as np
import matplotlib.pyplot as plt
Step 2
为逻辑回归定义必要的系数数量。
Define the number of coefficients necessary for logistic regression.
number_of_points = 500
x_point = []
y_point = []
a = 0.22
b = 0.78
Step 3
对变量进行迭代以生成 300 个围绕回归方程的随机点 −
Iterate the variables for generating 300 random points around the regression equation −
Y = 0.22x+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])
Step 4
使用 Matplotlib 查看生成点。
View the generated points using Matplotlib.
fplt.plot(x_point,y_point, 'o', label = 'Input Data') plt.legend() plt.show()
逻辑回归的完整代码如下 −
The complete code for logistic regression is as follows −
import numpy as np
import matplotlib.pyplot as plt
number_of_points = 500
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])
plt.plot(x_point,y_point, 'o', label = 'Input Data') plt.legend()
plt.show()
输入点数被认为是输入数据。
The number of points which is taken as input is considered as input data.