吴恩达机器学习ex1-linear regression python版

机器学习练习 1 - 线性回归

单变量线性回归

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
#文件在ipynb文件同个文件夹下,否则写完整路径
​
path =  'ex1data1.txt'#
# 读取数据
# names 添加列名,分别是人口,利润
# header 指定第几行作为列名,默认将第一行作为列名
​
data = pd.read_csv(path, header=None, names=['Population', 'Profit'])# 读取数据中的前五项数据,head()内不写时默认5,若输入4,则输出4行,9则输出9行数据,-1输出至倒数第二行数据,-11输出至倒数第12行数据
​
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

data.describe()

Population Profit
count 97.000000 97.000000
mean 8.159800 5.839135
std 3.869884 5.510262
min 5.026900 -2.680700
25% 5.707700 1.986900
50% 6.589400 4.562300
75% 8.578100 7.046700
max 22.203000 24.147000

看下数据长什么样子

# 将数据可视化
# kind设置图标类型,scatter为散点图
# x,y为坐标轴标题
# figsize为打开窗口大小,可以不设置 默认大小
# title为图标标题
​
data.plot(kind='scatter', x='Population', y='Profit', figsize=(12,8))
# 或者可以使用
#data.plot.scatter('Population','Profit',label='Popultaion')
plt.show()

在这里插入图片描述

现在让我们使用梯度下降来实现线性回归,以最小化成本函数。 以下代码示例中实现的方程在“练习”文件夹中的“ex1.pdf”中有详细说明。

首先,我们将创建一个以参数θ为特征函数的代价函数
𝐽(𝜃)=12𝑚∑𝑖=1𝑚(ℎ𝜃(𝑥(𝑖))−𝑦(𝑖))2
其中:
ℎ𝜃(𝑥)=𝜃𝑇𝑋=𝜃0𝑥0+𝜃1𝑥1+𝜃2𝑥2+…+𝜃𝑛𝑥𝑛

def computeCost(X, y, theta):
    inner = np.power(((X * theta.T) - y), 2)
    #至于为什么是X*Theta.T,我们可以往下进行将X和y的维度捋清之后,看怎么样能凑出y的维度,theta只是一个参数矩阵,维度不固定,全靠凑
    return np.sum(inner) / (2 * len(X))

让我们在训练集中添加一列,以便我们可以使用向量化的解决方案来计算代价和梯度。

#data  的格式为DataFrame,插入可以使用insert进行插入
# insert(loc,column,value)
# loc,列索引;column;列的标签值;value;插入的值
#在第0列插入列名为ones,列的值全为1
​
data.insert(0, 'Ones', 1)
data.head()

Ones Population Profit
0 1 6.1101 17.5920
1 1 5.5277 9.1302
2 1 8.5186 13.6620
3 1 7.0032 11.8540
4 1 5.8598 6.8233

现在我们来做一些变量初始化。

# set X (training data) and y (target variable)
cols = data.shape[1]
#data可以看作一个二维数据其中print的值为(97,3)表示97行3列
#print(data.shape)# .iloc[a,b]:取行索引为a列索引为b的数据 如c:d 则为c到d不到,c到d-1 行|列
#选取前两列作为输入向量
X = data.iloc[:,0:cols-1]#X是所有行,去掉最后一列
y = data.iloc[:,cols-1:cols]#X是所有行,最后一列

观察下 X (训练集) and y (目标变量)是否正确.

X.head()#head()是观察前5行

Ones Population
0 1 6.1101
1 1 5.5277
2 1 8.5186
3 1 7.0032
4 1 5.8598

y.head()

Profit
0 17.5920
1 9.1302
2 13.6620
3 11.8540
4 6.8233

代价函数是应该是numpy矩阵,所以我们需要转换X和Y,然后才能使用它们。 我们还需要初始化theta。

#.values返回数据矩阵
X = np.matrix(X.values)
#print(type(X))
y = np.matrix(y.values)
theta = np.matrix(np.array([0,0]))
#print(theta)

theta 是一个(1,2)矩阵

theta

matrix([[0, 0]])

看下维度

X.shape, theta.shape, y.shape

((97, 2), (1, 2), (97, 1))

计算代价函数 (theta初始值为0).

computeCost(X, y, theta)

32.072733877455676

batch gradient decent(批量梯度下降)

𝜃𝑗:=𝜃𝑗−𝛼∂∂𝜃𝑗𝐽(𝜃)

#修改参数theta,找到代价函数的最小值,其中记录最后的theta和每次更新代价函数的值
def gradientDescent(X, y, theta, alpha, iters):
    temp = np.matrix(np.zeros(theta.shape))
    #存theta更新的值做中间量,更新完赋给theta
    parameters = int(theta.ravel().shape[1])
    #.ravel() 将数组维度拉成一维数组,theta本身就是一维数组了 不用应该也行
    # parameters表示theta j ,更新j从0到 parameters
    cost = np.zeros(iters)
    #cost为一维的长度为iters的数组
    
    for i in range(iters):
        error = (X * theta.T) - y
        
        for j in range(parameters):#更新theta j 
            term = np.multiply(error, X[:,j]) #multiply数组对应元素位置相乘
            temp[0,j] = theta[0,j] - ((alpha / len(X)) * np.sum(term))
            
        theta = temp
        cost[i] = computeCost(X, y, theta)
        
    return theta, cost

初始化一些附加变量 - 学习速率α和要执行的迭代次数。

alpha = 0.01
iters = 1000

现在让我们运行梯度下降算法来将我们的参数θ适合于训练集。

g, cost = gradientDescent(X, y, theta, alpha, iters)
g

matrix([[-3.24140214, 1.1272942 ]])

最后,我们可以使用我们拟合的参数计算训练模型的代价函数(误差)。

computeCost(X, y, g)

4.515955503078914

现在我们来绘制线性模型以及数据,直观地看出它的拟合。

# np.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0)
# start:返回样本数据开始点
# stop:返回样本数据结束点
# num:生成的样本数据量,默认为50
# endpoint:True则包含stop;False则不包含stop
# retstep:If True, return (samples, step), where step is the spacing between samples.(即如果为True则结果会给出数据间隔)
# dtype:输出数组类型
# axis:0(默认)或-1# 返回在区间[`start`,`stop`]中计算出的num个均匀间隔的样本
x = np.linspace(data.Population.min(), data.Population.max(), 100)
f = g[0, 0] + (g[0, 1] * x)#y=theta0+theta1*x
​
fig, ax = plt.subplots(figsize=(12,8))#plt.subplots()是一个函数,返回一个包含figure和axes对象的元组。通常我们只使用ax
ax.plot(x, f, 'r', label='Prediction')#x,f为坐标(x,y) 'r'为red红色
ax.scatter(data.Population, data.Profit, label='Traning Data')
ax.legend(loc=2)
ax.set_xlabel('Population')
ax.set_ylabel('Profit')
ax.set_title('Predicted Profit vs. Population Size')
plt.show()

在这里插入图片描述

由于梯度方程式函数也在每个训练迭代中输出一个代价的向量,所以我们也可以绘制。 请注意,代价总是降低 - 这是凸优化问题的一个例子。

fig, ax = plt.subplots(figsize=(12,8))
ax.plot(np.arange(iters), cost, 'r')#np.arange()函数返回一个有终点和起点的固定步长的排列
#可以一个参数、两个参数、三个参数 。若三个参数则自定义起点、终点、步长。若一个参数 默认起点0,步长为1 。若两个参数 默认步长为1 
​
ax.set_xlabel('Iterations')
ax.set_ylabel('Cost')
ax.set_title('Error vs. Training Epoch')
plt.show()

在这里插入图片描述

多变量线性回归

练习1还包括一个房屋价格数据集,其中有2个变量(房子的大小,卧室的数量)和目标(房子的价格)。 我们使用我们已经应用的技术来分析数据集。

path =  'ex1data2.txt'
data2 = pd.read_csv(path, header=None, names=['Size', 'Bedrooms', 'Price'])
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

对于此任务,我们添加了另一个预处理步骤 - 特征归一化。 这个对于pandas来说很简单

data2 = (data2 - data2.mean()) / data2.std()#mean()表示均值 std()表示标准差
data2.head()

Size Bedrooms Price
0 0.130010 -0.223675 0.475747
1 -0.504190 -0.223675 -0.084074
2 0.502476 -0.223675 0.228626
3 -0.735723 -1.537767 -0.867025
4 1.257476 1.090417 1.595389

现在我们重复第1部分的预处理步骤,并对新数据集运行线性回归程序。

# add ones column
data2.insert(0, 'Ones', 1)# set X (training data) and y (target variable)
cols = data2.shape[1]
X2 = data2.iloc[:,0:cols-1]
y2 = data2.iloc[:,cols-1:cols]# convert to matrices and initialize theta
X2 = np.matrix(X2.values)
y2 = np.matrix(y2.values)
theta2 = np.matrix(np.array([0,0,0]))# perform linear regression on the data set
g2, cost2 = gradientDescent(X2, y2, theta2, alpha, iters)# get the cost (error) of the model
computeCost(X2, y2, g2)

0.13070336960771892

我们也可以快速查看这一个的训练进程。

fig, ax = plt.subplots(figsize=(12,8))
ax.plot(np.arange(iters), cost2, 'r')
ax.set_xlabel('Iterations')
ax.set_ylabel('Cost')
ax.set_title('Error vs. Training Epoch')
plt.show()

在这里插入图片描述

我们也可以使用scikit-learn的线性回归函数,而不是从头开始实现这些算法。 我们将scikit-learn的线性回归算法应用于第1部分的数据,并看看它的表现。

from sklearn import linear_model
model = linear_model.LinearRegression()
#X=np.array(X)
#y=np.array(y)
model.fit(X, y)
#print(model.coef_) theta

LinearRegression()

scikit-learn model的预测表现

x = np.array(X[:, 1].A1)#.A1和flatten()效果一样
f = model.predict(X).flatten()#flatten()是对多维数据的降维函数,即返回一个折叠成一维的数组
fig, ax = plt.subplots(figsize=(12,8))
ax.plot(x, f, 'r', label='Prediction')
ax.scatter(data.Population, data.Profit, label='Traning Data')
ax.legend(loc=2)
ax.set_xlabel('Population')
ax.set_ylabel('Profit')
ax.set_title('Predicted Profit vs. Population Size')
plt.show()

在这里插入图片描述

normal equation(正规方程)

正规方程是通过求解下面的方程来找出使得代价函数最小的参数的:∂∂𝜃𝑗𝐽(𝜃𝑗)=0 。 假设我们的训练集特征矩阵为 X(包含了𝑥0=1)并且我们的训练集结果为向量 y,则利用正规方程解出向量 𝜃=(𝑋𝑇𝑋)−1𝑋𝑇𝑦 。 上标T代表矩阵转置,上标-1 代表矩阵的逆。设矩阵𝐴=𝑋𝑇𝑋,则:(𝑋𝑇𝑋)−1=𝐴−1
梯度下降与正规方程的比较:

梯度下降:需要选择学习率α,需要多次迭代,当特征数量n大时也能较好适用,适用于各种类型的模型

正规方程:不需要选择学习率α,一次计算得出,需要计算(𝑋𝑇𝑋)−1,如果特征数量n较大则运算代价大,因为矩阵逆的计算时间复杂度为𝑂(𝑛3),通常来说当𝑛小于10000 时还是可以接受的,只适用于线性模型,不适合逻辑回归模型等其他模型

# 正规方程
def normalEqn(X, y):
    theta = np.linalg.inv(X.T@X)@X.T@y#X.T@X等价于X.T.dot(X) (@可以理解为矩阵的乘)    np.linalg.inv():矩阵求逆
    #np.dot():点积,又称内积 先对两个数字序列对应元素求积,然后对所有积求和,得到一个向量
    #eg: (5,5)·(5,1)=(5,1)
    return theta
final_theta2=normalEqn(X, y)#感觉和批量梯度下降的theta的值有点差距
final_theta2

matrix([[-3.89578088],
[ 1.19303364]])

#梯度下降得到的结果是matrix([[-3.24140214,  1.1272942 ]])

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值