EX1-线性回归
1简单函数运用
产生一个 的矩阵
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
A=np.eye(5)
A
array([[1., 0., 0., 0., 0.],
[0., 1., 0., 0., 0.],
[0., 0., 1., 0., 0.],
[0., 0., 0., 1., 0.],
[0., 0., 0., 0., 1.]])
2单变量线性回归
文件ex1data1.txt包含线性回归问题的数据集。第一列是一个城市的人口,第二列是该城市食品卡车的利润。负值表示亏损。
2.1 绘制数据
fath='F:\jypternotebook\吴恩达机器学习python作业代码\code\ex1-linear regression\ex1data1.txt'
data=pd.read_csv(fath,header=None)
data.columns=['population','profit']#由于没有列名,需要添加
print(data.head())
population profit
0 6.1101 17.5920
1 5.5277 9.1302
2 8.5186 13.6620
3 7.0032 11.8540
4 5.8598 6.8233
plt.plot(data['population'],data['profit'],'ro')
#对x轴的区域标注倾斜
plt.rc('font',family='Times New Roman')#设置所有字体为新罗马
plt.xlabel('population',fontsize=12)
plt.ylabel('Unemployment Rate',fontsize=12)
plt.title('profit',fonsize=20)
plt.show()
2.2梯度下降拟合
2.2.1更新公式
代价函数:
首先,我们将创建一个以参数θ为特征函数的代价函数
其中
#定义计算代价函数的公式
def cost_fun(x,theta,y):#theta为1*n,x是m*n的矩阵,y是m*1的矩阵,n为theta个数,输入格式均为ndarry不是matrix
m,n=x.shape#矩阵规模
J=(np.sum((x.dot(theta)-y)**2)/(2*m))
return J
#对输入数据进行初始化
#增加一列全为1的列向量
population=np.array(data['population'])
print(population)
print(population.shape)
X=np.c_[np.ones(population.shape),population]#第一列全为1
print(X.shape)
m,n=X.shape
Y=np.array(data['profit'])
print(Y.shape)
theta=np.zeros(n)
print(theta)
[ 6.1101 5.5277 8.5186 7.0032 5.8598 8.3829 7.4764 8.5781 6.4862
5.0546 5.7107 14.164 5.734 8.4084 5.6407 5.3794 6.3654 5.1301
6.4296 7.0708 6.1891 20.27 5.4901 6.3261 5.5649 18.945 12.828
10.957 13.176 22.203 5.2524 6.5894 9.2482 5.8918 8.2111 7.9334
8.0959 5.6063 12.836 6.3534 5.4069 6.8825 11.708 5.7737 7.8247
7.0931 5.0702 5.8014 11.7 5.5416 7.5402 5.3077 7.4239 7.6031
6.3328 6.3589 6.2742 5.6397 9.3102 9.4536 8.8254 5.1793 21.279
14.908 18.959 7.2182 8.2951 10.236 5.4994 20.341 10.136 7.3345
6.0062 7.2259 5.0269 6.5479 7.5386 5.0365 10.274 5.1077 5.7292
5.1884 6.3557 9.7687 6.5159 8.5172 9.1802 6.002 5.5204 5.0594
5.7077 7.6366 5.8707 5.3054 8.2934 13.394 5.4369]
(97,)
(97, 2)
(97,)
[0. 0.]
np.c_[array1,array2] c_表示colum列
np.r_[array1,array2] r_表示row行
计算初始 下的初始的代价函数值
cost_fun(X,theta,Y)
32.072733877455676
2.2.2batch gradient decent(批量梯度下降)
def batch_gradient_decent(X,Y,theta,iters,alpha):
#输入X,Y,theta,最大迭代次数iters,学习率,alpha
m,n=X.shape
J_iters=np.zeros(iters)
for i in range(iters):
for j in range(n):
theta[j]=theta[j]-(alpha/m)*(np.sum((X.dot(theta)-Y)*X[:,j]))
J_iters[i]=cost_fun(X,theta,Y)
J=cost_fun(X,theta,Y)
return theta,J,J_iters
alpha = 0.01
iters = 1000
theta_result,J,J_iters=batch_gradient_decent(X,Y,theta,iters,alpha)
print(theta)#显示最终theta结果
print(J)#显示最小代价函数
[-3.25088222 1.12836314]
4.514833339953507
#绘图显示拟合效果
x_plot=np.arange(population.min(),population.max(),0.00001)
y_plot=x_plot*theta[1]+theta[0]
plt.scatter(data['population'],data['profit'],label='scatter data')
plt.plot(x_plot,y_plot,'r',label='predition')
plt.legend()
#对x轴的区域标注倾斜
plt.rc('font',family='Times New Roman')#设置所有字体为新罗马
plt.xlabel('population',fontsize=12)
plt.ylabel('Unemployment Rate',fontsize=12)
plt.title('profit',fontsize=20)
plt.show()
iters_plot=np.arange(iters)
plt.plot(iters_plot,J_iters,'r')
plt.xlabel('itertion',fontsize=12)
plt.ylabel(r'$J(\theta)$',fontsize=12)
plt.show()
3多变量线性回归
3.1数据说明
文件ex1data2.txt包含俄勒冈州波特兰市房价的培训集。
第一栏是房子的大小(平方英尺),第二栏是卧室的数量,第三栏是房子的价格。
3.2特征归一化
fath='F:\jypternotebook\吴恩达机器学习python作业代码\code\ex1-linear regression\ex1data2.txt'
data2=pd.read_csv(fath,header=None)
data2.columns=['Size', 'Bedrooms', 'Price']#由于没有列名,需要添加
print(data2.head())
Size Bedrooms Price
0 2104 3 399900
1 1600 3 329900
2 2400 3 369000
3 1416 2 232000
4 3000 4 539900
表达式如下:
data2 = (data2 - data2.mean()) / data2.std()#进行数据归一化
data2.insert(0, 'Ones', 1)
print(data2.head())
Ones Size Bedrooms Price
0 1 0.130010 -0.223675 0.475747
1 1 -0.504190 -0.223675 -0.084074
2 1 0.502476 -0.223675 0.228626
3 1 -0.735723 -1.537767 -0.867025
4 1 1.257476 1.090417 1.595389
m2,cols=data2.shape
X2=np.array(data2.iloc[:,0:cols-1])
Y2=np.array(data2['Price'])
m2,n2=X2.shape
theta2=np.zeros(n2)
alpha2= 0.01
iters2= 1000
theta_result2,J2,J2_iters=batch_gradient_decent(X2,Y2,theta2,iters2,alpha2)
print(theta2)#显示最终theta结果
print(J2)#显示最小代价函数
[-1.01567690e-16 8.78592062e-01 -4.70184194e-02]
0.13070286068415232
iters2_plot=np.arange(iters2)
plt.plot(iters2_plot,J2_iters,'r')
plt.xlabel('itertion',fontsize=12)
plt.ylabel(r'$J(\theta)$',fontsize=12)
plt.show()