data_file_path = "ex1/ex1data1.txt" # 此处需根据你的数据文件的位置进行相应的修改
data = np.loadtxt(data_file_path, dtype=np.float, delimiter=',')
X = data[:, 0:1]
y = data[:, 1:]
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()
one_col = np.ones((X.shape[0], 1))
X = np.column_stack((one_col, X))
n = X.shape[1]
m = y.shape[0]
theta = np.zeros(2)
alpha = 0.01
iterations = 1500
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")
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")
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()
# 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()
如有不当之处,欢迎指出!