linear regression
1. 代码演示
1.单变量的线性回归
本次作业在jupyter notebook上完成
首先,导入需要用到的类库
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d, Axes3D
from matplotlib import cm
import itertools
%matplotlib inline
加载文件ex1dara1.txt
datafile = 'data/ex1data1.txt'
#','为分隔符,抽出第0列和第1列,转置
cols = np.loadtxt(datafile,delimiter=',',usecols=(0,1),unpack=True) #Read in comma separated data
#X为第0列,y为第1列
X = np.transpose(np.array(cols[:-1]))
y = np.transpose(np.array(cols[-1:]))
m = y.size
#在矩阵第一列前加上全为1的一列,目的是1到时候就是常数
X = np.insert(X,0,1,axis=1)
画图看看数据的分布
plt.figure(figsize=(10,6))
plt.plot(X[:,1],y[:,0],'rx',markersize=10)
plt.grid(True) #Always plot.grid true!
plt.ylabel('Profit')
plt.xlabel('Population')
定义两个函数,一个用于计算线性回归值,一个用于计算损失值
#线性假设函数
def h(theta,X): #Linear hypothesis function
return np.dot(X,theta)
#利用公式计算损失值
def computeCost(mytheta,X,y):
return float((1/(2*m)) * np.dot((h(mytheta,X)-y).T,h(mytheta,X)-y))
定义迭代次数和学习率
iterations = 1500
alpha = 0.01
#测试,返回32.07
test_theta = np.zeros((X.shape[1],1))
print(computeCost(test_theta, X ,y))
定义梯度下降函数
#Actual gradient descent minimizing routine
def descendGradient(X, y, theta_start = np.zeros(2),alpha=0.01,iterations=1500):
theta = theta_start
#损失值的列表,len=1500
costList = []
#theta值列表,len=1500
theta_history = []
for i in range(iterations):
tmp_theta = theta
#计算损失值并记录
costList.append(computeCost(theta,X,y))
theta_history.append(list(theta[:,0]))
#同时对每个特征进行更新
for j in range(len(tmp_theta)):
tmp_theta[j] = theta[j] - (alpha/m)*np.sum((h(initial_theta,X) - y)*np.array(X[:,j]).reshape(m,1))#梯度下降
#theta更新
theta = tmp_theta
return theta, theta_history, costList
初始化参数,定义绘制cost函数迭代图像的函数
#初始化参数theta
initial_theta = np.zeros((X.shape[1],1))
theta, theta_history, costList = descendGradient(X,y,initial_th