理论笔记:https://blog.csdn.net/monochrome00/article/details/104077303
单变量线性回归
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# 获取假设函数
def getHypothesis(X, theta):
return X * theta.T
# 获取代价函数
def getCost(X, y, theta):
return np.sum(np.power(X * theta.T - y, 2)) / 2 / len(y)
# 梯度下降
def gradientDescent(X, y):
theta = np.asmatrix([[0]*X.shape[1]]) # 按照X的列数设定theta的大小,初始值都设为0
for i in range(0, epoch):
theta = theta - alpha / len(y) * (X * theta.T - y).T * X
return theta
# 读取数据
def getData():
path = 'ex1data1.txt'
# path是读取文件的路径, header用来指定行作为标题,names指定列名
return_data = pd.read_csv(path, header=None, names=['Population', 'Profit'])
return return_data
if __name__ == '__main__':
data = getData()
col = data.shape[1] # shape[0]存储行数,shape[1]存储列数
sampleX = data.iloc[:, 0:col - 1] # 前col-1列是样本输入
sampleY = data.iloc[:, col - 1:col] # 最后一列是样本输出
plt.scatter(sampleX, sampleY, s=10, label='Training Data') # 样本描点画图
m = len(sampleX) # 样本数
sampleX.insert(0, 'x0', 1) # 在样本输入前插入一个全是1的列,表示x0
matrixX = np.asmatrix(sampleX.values) # 转化成matrix
matrixY = np.asmatrix(sampleY.values)
epoch = 10000 # 迭代次数
alpha = 0.001 # 学习速率
finalTheta = gradientDescent(matrixX, matrixY) # 梯度下降后所得的theta
plt.title('Linear regression with one variable')
x = np.linspace(data.Population.min(), data.Population.max(), 1000) # 横坐标
f = finalTheta[0, 0] + finalTheta[0, 1]*x # 直接计算出y坐标
plt.plot(x, f, 'r', label='Prediction') # 画出最后所得的模型
plt.legend()
plt.show()
最开始计算出的代价函数
J
J
J是32.072733877455676。1000次迭代后,
J
J
J大概收敛在4.516069827120197
这是最后可视化的结果:
多变量线性回归
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# 获取假设函数
def getHypothesis(X, theta):
return X * theta.T
# 获取代价函数
def getCost(X, y, theta):
return np.sum(np.power(X * theta.T - y, 2)) / 2 / len(y)
# 梯度下降
def gradientDescent(X, y):
theta = np.asmatrix([[0]*X.shape[1]]) # 按照X的列数设定theta的大小,初始值都设为0
for i in range(0, epoch):
theta = theta - alpha / len(y) * (X * theta.T - y).T * X
return theta
# 读取数据
def getData():
path = 'ex1data2.txt'
# path是读取文件的路径, header用来指定行作为标题,names指定列名
return_data = pd.read_csv(path, header=None, names=['Size', 'Bedrooms', 'Price'])
return return_data
if __name__ == '__main__':
data = getData()
col = data.shape[1] # shape[0]存储行数,shape[1]存储列数
data = (data - data.mean()) / data.std() # 这里进行了特征归一化
sampleX = data.iloc[:, 0:col - 1] # 前col-1列是样本输入
sampleY = data.iloc[:, col - 1:col] # 最后一列是样本输出
ax = plt.subplot(111, projection='3d')
ax.scatter(sampleX.Size, sampleX.Bedrooms, sampleY, label='Training Data') # 样本描点画图
m = len(sampleX) # 样本数
sampleX.insert(0, 'x0', 1) # 在样本输入前插入一个全是1的列,表示x0
matrixX = np.asmatrix(sampleX.values) # 转化成matrix
matrixY = np.asmatrix(sampleY.values)
epoch = 10000 # 迭代次数
alpha = 0.001 # 学习速率
finalTheta = gradientDescent(matrixX, matrixY) # 梯度下降后所得的theta
plt.title('Linear regression with multiple variable')
x = np.linspace(data.Size.min(), data.Size.max(), 1000) # x坐标
y = np.linspace(data.Bedrooms.min(), data.Bedrooms.max(), 1000) # y坐标
f = finalTheta[0, 0] + finalTheta[0, 1] * x + finalTheta[0, 2] * y # 直接计算出z坐标
ax.scatter(x, y, f, c="r", label='Prediction') # 样本描点画图
plt.legend()
plt.show()
因为写的比较漂亮,代码基本没啥变化
一开始的
J
J
J是0.48936170212765967,最后收敛成0.13070365481036997
可视化后的结果:
正规方程
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# 获取假设函数
def getHypothesis(X, theta):
return X * theta.T
# 获取代价函数
def getCost(X, y, theta):
return np.sum(np.power(X * theta.T - y, 2)) / 2 / len(y)
# 正规方程
def normalEquations(X, y):
theta = (X.T * X).I * X.T * y
return theta.T
# 读取数据
def getData():
path = 'ex1data2.txt'
# path是读取文件的路径, header用来指定行作为标题,names指定列名
return_data = pd.read_csv(path, header=None, names=['Size', 'Bedrooms', 'Price'])
return return_data
if __name__ == '__main__':
data = getData()
col = data.shape[1] # shape[0]存储行数,shape[1]存储列数
data = (data - data.mean()) / data.std() # 这里进行了特征归一化
sampleX = data.iloc[:, 0:col - 1] # 前col-1列是样本输入
sampleY = data.iloc[:, col - 1:col] # 最后一列是样本输出
ax = plt.subplot(111, projection='3d')
ax.scatter(sampleX.Size, sampleX.Bedrooms, sampleY, label='Training Data') # 样本描点画图
m = len(sampleX) # 样本数
sampleX.insert(0, 'x0', 1) # 在样本输入前插入一个全是1的列,表示x0
matrixX = np.asmatrix(sampleX.values) # 转化成matrix
matrixY = np.asmatrix(sampleY.values)
epoch = 10000 # 迭代次数
alpha = 0.001 # 学习速率
# finalTheta = gradientDescent(matrixX, matrixY) # 梯度下降后所得的theta
finalTheta = normalEquations(matrixX, matrixY) # 正规方程所得的theta
plt.title('Linear regression with multiple variable')
x = np.linspace(data.Size.min(), data.Size.max(), 1000) # x坐标
y = np.linspace(data.Bedrooms.min(), data.Bedrooms.max(), 1000) # y坐标
f = finalTheta[0, 0] + finalTheta[0, 1] * x + finalTheta[0, 2] * y # 直接计算出z坐标
ax.scatter(x, y, f, c="r", label='Prediction') # 样本描点画图
plt.legend()
plt.show()
正规方程写起来很最为简单,而且效果也不错,最后代价函数
J
J
J 是0.13068648053904197