文章目录
1.形式化定义
2.梯度下降法
1)举例
2)数学原理
3)代码演示
# 梯度下降法代码实现
import matplotlib.pyplot as plt
# 梯度下降法代码实现
import numpy as np
x = np.linspace(-6, 4, 100)
y = x ** 2 + 2 * x + 5
# 构建绘图窗口与坐标
fig, ax = plt.subplots()
ax.plot(x, y, linewidth=3)
plt.show()
# 初始化x,步长α和迭代次数
# 步长要控制,不宜过大
# 可以通过设置精度来控制迭代次数
x = 3
alpha = 0.8
iteraterNum = 10
# y的导数为2x-2,迭代求theta
for i in range(iteraterNum):
x = x - alpha * (2 * x + 2)
print(x)
-0.9758135295999999
3.梯度下降法求解线性回归
1)理论
2)线性回归代码实现梯度下降算法
# 线性回归代码实现梯度下降算法
import matplotlib.pyplot as plt
import numpy as np
# 定义一个加载数据的函数
def loaddata():
data = np.loadtxt('data1.txt', delimiter=',')
n = data.shape[1] - 1 # 特征数
X = data[:, 0:n]
# reshape(-1,1)表示转变成一行
y = data[:, 1].reshape(-1, 1)
return X, y
# 定义特征标准化函数-减小异常点的影响
# 标准化方式是:对每一个特征,这列中的每个数据分别减去这列的均值,然后再除以这列的方差
def featureNormalize(X):
# 均值
mu = np.average(X, axis=0)
# 方差
# 参数ddof=1,表示求方差时除的n-1,否则的话,除以n
sigma = np.std(X, axis=0, ddof=1)
X = (X - mu) / sigma
return X, mu, sigma
# 定义计算代价函数
def computeCost(X, y, theta):
m = X.shape[0] # 数据量
# np.dot()这里均为一维向量,向量点乘
# np.power(x1,x2)表示对x1中的每个元素求x2次方
return np.sum(np.power(np.dot(X, theta) - y, 2)) / (2 * m)
# 定义梯度下降求解函数
def gradientDescent(X, y, theta, iterations, alpha):
# transpose()转置
c = np.ones(X.shape[0]).transpose()
# 对原始数据加入一个全为1的列,插入
X = np.insert(X, 0, values=c, axis=1)
m = X.shape[0] # 数据量
n = X.shape[1] # 特征数
costs = np.zeros(iterations)
for num in range(iterations):
for j in range(n):
theta[j] = theta[j] + (alpha / m) * np.sum((y - np.dot(X, theta)) * X[:, j].reshape(-1, 1))
costs[num] = computeCost(X, y, theta)
return theta, costs
# 预测函数-预测值
def predict(X):
X = (X - mu) / sigma
c = np.ones(X.shape[0]).transpose()
X = np.insert(X, 0, values=c, axis=1)
return np.dot(X, theta)
# 定义评价函数mse
def mse(y_true, y_pred):
return (1 / len(y_true)) * np.sum(np.power(y_true - y_pred, 2))
if __name__ == '__main__':
# 加载数据
X_orgin, y = loaddata()
# 标准化
X, mu, sigma = featureNormalize(X_orgin)
theta = np.zeros(X.shape[1] + 1).reshape(-1, 1)
iterations = 400
alpha = 0.01
# 梯度下降求解
theta, costs = gradientDescent(X, y, theta, iterations, alpha)
print(theta)
# 预测值
print(predict([[5.734]]))
# 模型的评价
model_pred = predict(X_orgin)
print(model_pred)
print('mse',mse(y,model_pred))
# mse 8.972317211137899
# 画子图
ax1 = plt