机器学习-单变量的线性回归

机器学习-单变量的线性回归,第1张

1 模型表示(Model Representation) 1.房价预测训练集
Size in feet²**(x)**Price ($) in 1000’s(y)
2104460
1416232
1534315
852178

房价预测训练集中,同时给出了输入 和输出结果 ,即给出了人为标注的 ”正确结果“,且预测的量是连续的,属于监督学习中的回归问题。


2.问题解决模型

2 代价函数(Cost Function)

3 代价函数 - 直观理解1(Cost Function - Intuition I)

4 代价函数 - 直观理解2(Cost Function - Intuition II)

5 梯度下降(Gradient Descent)

6 梯度下降直观理解(Gradient Descent Intuition)

最后,梯度下降不止可以用于线性回归中的代价函数,还通用于最小化其他的代价函数。


7 线性回归中的梯度下降(Gradient Descent For Linear Regression)

另外,使用循环求解,代码较为冗余,后面会讲到如何使用**向量化(Vectorization)**来简化代码并优化计算,使梯度下降运行的更快更好。


8 代码实现

整个2的部分需要根据城市人口数量,预测开小吃店的利润
数据在ex1data1.txt里,第一列是城市人口数量,第二列是该城市小吃店利润。


8.1 Plotting the Data

读入数据,然后展示数据

In [1]:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

In [2]:

path =  '../ex1data1.txt'
data = pd.read_csv(path, header=None, names=['Population', 'Profit'])
data.head()

Out [2]:

In [3]:

data.plot(kind='scatter', x='Population', y='Profit', figsize=(12,8))
plt.show()

8.2 梯度下降

这个部分你需要在现有数据集上,训练线性回归的参数θ

8.2.1 公式

#这个部分计算J(Ѳ),X是矩阵
def computeCost(X, y, theta):
    inner = np.power(((X * theta.T) - y), 2)
    return np.sum(inner) / (2 * len(X))
#调用
computeCost(X, y, theta)
8.2.2实现

In [4]:

data.insert(0, 'Ones', 1)

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


In [5]:

# 初始化X和y
cols = data.shape[1]
X = data.iloc[:,:-1]#X是data里的除最后列
y = data.iloc[:,cols-1:cols]#y是data最后一列

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

In [6]:

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

Out [6]:

\

In [7]:

y.head()

Out [7]:

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


我们还需要初始化theta。


In [8]:

X = np.matrix(X.values)
y = np.matrix(y.values)
theta = np.matrix(np.array([0,0]))

In [9]:

X.shape, theta.shape, y.shape

Out [9]:

8.2.3计算J(θ)

计算代价函数 (theta初始值为0),答案应该是32.07

In [10]:

def computeCost(X, y, theta):
    inner = np.power(((X * theta.T) - y), 2)
    return np.sum(inner) / (2 * len(X))
#这个部分计算J(Ѳ),X是矩阵
computeCost(X, y, theta)

Out [10]:

32.072733877455676

8.2.4 梯度下降

In [11]:

def gradientDescent(X, y, theta, alpha, iters):
    temp = np.matrix(np.zeros(theta.shape))
    parameters = int(theta.ravel().shape[1])
    cost = np.zeros(iters)
    
    for i in range(iters):
        error = (X * theta.T) - y
        
        for j in range(parameters):
            term = np.multiply(error, X[:,j])
            temp[0,j] = theta[0,j] - ((alpha / len(X)) * np.sum(term))
            
        theta = temp
        cost[i] = computeCost(X, y, theta)
        
    return theta, cost
#这个部分实现了Ѳ的更新

初始化一些附加变量 - 学习速率α和要执行的迭代次数,2.2.2中已经提到。


In [12]:

alpha = 0.01
iters = 1500

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


In [13]:

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

Out [13]:

matrix([[-3.63029144, 1.16636235]])

In [14]:

predict1 = [1,3.5]*g.T
print("predict1:",predict1)
predict2 = [1,7]*g.T
print("predict2:",predict2)
#预测35000和70000城市规模的小吃摊利润

predict1: [[0.45197679]]

predict2: [[4.53424501]]

In [15]:

x = np.linspace(data.Population.min(), data.Population.max(), 100)
f = g[0, 0] + (g[0, 1] * x)

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()
#原始数据以及拟合的直线

8.3 可视化J(θ)

并不会用python复现,截个图意思一下

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/570562.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-09
下一篇 2022-04-09

发表评论

登录后才能评论

评论列表(0条)

保存