文章目录
1.数据处理部分
1.1 加载数据
data_file_path = "ex1/ex1data1.txt" # 此处需根据你的数据文件的位置进行相应的修改
data = np.loadtxt(data_file_path, dtype=np.float, delimiter=',')
1.2 分割X和y
X = data[:, 0:1]
y = data[:, 1:]
1.3 绘图展示数据
fig = plt.figure(num=1, figsize=(15,8), dpi=80)
plt.scatter(X, y)
plt.xlabel('Population of City in 10,000s')
plt.ylabel("Profit in $10,000s")
plt.show()
1.4 给X加一列全为1的向量
one_col = np.ones((X.shape[0], 1))
X = np.column_stack((one_col, X))
2.实现线性回归算法
2.1 初始化参数
n = X.shape[1]
m = y.shape[0]
theta = np.zeros(2)
alpha = 0.01
iterations = 1500
2.2 实现损失函数
def computeCost(X, y, theta):
return np.sum((np.dot(X, theta).reshape(m,1) - y)**2) / (2*m)
此时,可以测试一下损失函数的正确性
print("%.2f" % computeCost(X, y, theta))
print("此处的结果应该是32.07")
2.3 实现梯度下降
def gradientDescent(X, y, theta, alpha, iterations):
for i in range(iterations):
g = np.dot((np.dot(X, theta).reshape(m,1) - y).T, X) / m
theta -= alpha * g.reshape(n,)
# 观察损失函数的变化
if i % 100 == 0:
loss = computeCost(X, y, theta)
print("第i次的损失函数值为%.2f" % loss)
return theta
# 直接得到最终模型
theta = gradientDescent(X, y, theta, alpha, iterations)
测试一下
print(theta)
print("此处的结果应该是-3.6303 1.1664")
2.4 将得到的直线绘制出来,观察拟合程度
plt.xlabel('Population of City in 10,000s')
plt.ylabel("Profit in $10,000s")
plt.scatter(X[:, 1:], y )
plt.plot(X[:, 1:], theta[0] + theta[1] * X[:, 1:], color='g')
plt.legend(['Linear regression', 'Training data'])
plt.show()

3.完整代码
# coding=utf-8
import numpy as np
import matplotlib.pyplot as plt
# 1.数据处理部分
# 1.1加载数据
data_file_path = "ex1/ex1data1.txt" # 此处需根据你的数据文件的位置进行相应的修改
data = np.loadtxt(data_file_path, dtype=np.float, delimiter=',')
# 1.2分割X和y
X = data[:, 0:1]
y = data[:, 1:]
# 1.3绘图展示数据
# fig = plt.figure(num=1, figsize=(15,8), dpi=80)
# plt.scatter(X, y)
# plt.xlabel('Population of City in 10,000s')
# plt.ylabel("Profit in $10,000s")
# plt.show()
# 1.4给X加一列全为1的向量
one_col = np.ones((X.shape[0], 1))
X = np.column_stack((one_col, X))
# print(X[0:5])
# 2.实现线性回归算法
# 2.1 初始化参数
n = X.shape[1]
m = y.shape[0]
theta = np.zeros(2)
alpha = 0.01
iterations = 1500
# 2.2 实现损失函数
def computeCost(X, y, theta):
return np.sum((np.dot(X, theta).reshape(m,1) - y)**2) / (2*m)
# print("%.2f" % computeCost(X, y, theta))
# print("此处的结果应该是32.07")
# 2.3 实现梯度下降
def gradientDescent(X, y, theta, alpha, iterations):
for i in range(iterations):
g = np.dot((np.dot(X, theta).reshape(m,1) - y).T, X) / m
theta -= alpha * g.reshape(n,)
# 观察损失函数的变化
if i % 100 == 0:
loss = computeCost(X, y, theta)
print("第i次的损失函数值为%.2f" % loss)
return theta
theta = gradientDescent(X, y, theta, alpha, iterations)
# print(theta)
# print("此处的结果应该是-3.6303 1.1664")
# 2.4 将得到的直线绘制出来,观察拟合程度
# fig = plt.figure(num=1, figsize=(15,8), dpi=80)
plt.xlabel('Population of City in 10,000s')
plt.ylabel("Profit in $10,000s")
plt.scatter(X[:, 1:], y )
plt.plot(X[:, 1:], theta[0] + theta[1] * X[:, 1:], color='g')
plt.legend(['Linear regression', 'Training data'])
plt.show()
如有不当之处,欢迎指出!
本文详细介绍了一个线性回归算法的实现过程,从数据加载到模型训练,再到结果可视化,全面展示了如何使用Python和NumPy实现线性回归。文章首先介绍了数据预处理步骤,包括数据加载、特征分割和数据可视化。然后,通过实现损失函数和梯度下降算法,完成了线性回归模型的训练,并在最后通过绘制预测直线,直观地展示了模型的拟合效果。
684

被折叠的 条评论
为什么被折叠?



