吴恩达机器学习第一次作业 Linear Regression(基于Python实现)

本文详细介绍了一个线性回归算法的实现过程,从数据加载到模型训练,再到结果可视化,全面展示了如何使用Python和NumPy实现线性回归。文章首先介绍了数据预处理步骤,包括数据加载、特征分割和数据可视化。然后,通过实现损失函数和梯度下降算法,完成了线性回归模型的训练,并在最后通过绘制预测直线,直观地展示了模型的拟合效果。

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()

如有不当之处,欢迎指出!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值