吴恩达机器学习课后作业 Linear Regression

吴恩达机器学习课后作业 Linear Regression

损失函数

1 2 m Σ i = 1 m ( h ( x ) − y ) 2 \frac{1}{2m}\Sigma_{i=1}^m(h(x) -y)^2 2m1Σi=1m(h(x)y)2

其中:
h ( x ) = θ 1 ∗ x + θ 0 h(x) = \theta_1*x + \theta_0 h(x)=θ1x+θ0
m:代表训练样本实例的个数
x, y都来来源于数据集,对应的意义x代表房屋的面积,y代表房屋的价格。目标是求两个参数 θ 0 , θ 1 \theta_0,\theta_1 θ0,θ1。使得对于给定的x(房屋的面积),能够预测出y(房屋的价格)。

对应的代码

def cost_function(x, y, theta):
    inner = np.power(x*theta.T - y, 2)
    return np.sum(inner) / (2 * len(x))

梯度下降公式

θ j = θ j − α ∂ J ( θ 0 , θ 1 ) ∂ θ j \theta_j = \theta_j - \alpha\frac{\partial J(\theta_0,\theta_1)}{\partial \theta_j} θj=θjαθjJ(θ0,θ1)
α 是 学 习 率 \alpha是学习率 α
j: 0、1
对应的代码:

def gradient_descent(x, y, theta, alpha, iters):
    temp = np.mat(np.zeros(theta.shape))
    paramters = int(theta.shape[1])
    cost = np.zeros(iters)
    for i in range(iters):
        error = (x*theta.T) - y

        for j in range(paramters):
            term = np.multiply(error, x[:, j])
            temp[0, j] = theta[0, j] - (alpha/len(x))*np.sum(term)

        cost[i] = cost_function(x, y, theta)
        theta = temp

    return theta, cost

数据分布图:
在这里插入图片描述

求出 θ 0 , θ 1 \theta_0, \theta_1 θ0,θ1拟合数据分布图:
在这里插入图片描述

梯度下降图:

在这里插入图片描述

数据集
提取码:ek19

完整代码如下:

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

"""读取文件的内容,可视化展示出来"""
file = './data/ex1data1.txt'   # 换成自己的路径
data = pd.read_csv(file, names=['Size', 'Price'])
plt.scatter(data.iloc[:, 0], data.iloc[:, 1], marker='v', c='red')
plt.xlabel("The size of house")
plt.ylabel("Price")
plt.show()

"""处理数据"""
data.insert(0, 'Ones', 1)
x = data.iloc[:, 0:2]
y = data.iloc[:, -1]
x = np.mat(x)
y = np.mat(np.array(y).reshape(y.shape[0], 1))
theta = np.zeros(x.shape[1])
theta = np.mat(theta)
print(theta.shape)


# 代价函数
def cost_function(x, y, theta):
    inner = np.power(x*theta.T - y, 2)
    return np.sum(inner) / (2 * len(x))


# 梯度下降函数
def gradient_descent(x, y, theta, alpha, iters):
    temp = np.mat(np.zeros(theta.shape))
    paramters = int(theta.shape[1])
    cost = np.zeros(iters)
    for i in range(iters):
        error = (x*theta.T) - y

        for j in range(paramters):
            term = np.multiply(error, x[:, j])
            temp[0, j] = theta[0, j] - (alpha/len(x))*np.sum(term)

        cost[i] = cost_function(x, y, theta)
        theta = temp

    return theta, cost


alpha = 0.003           # 学习率
iters = 100000           # 迭代次数

g, cost = gradient_descent(x, y, theta, alpha, iters)

# 拟合图
x0 = g[0, 0]
x1 = g[0, 1]
x_t = np.linspace(5, 25, 1000)
y_t = []
for i in x_t:
    y_t.append(x0 + x1*i)
plt.plot(x_t, y_t)
plt.scatter(data.iloc[:, 1], data.iloc[:, -1], marker='x', c='red')
plt.show()
# 梯度下降图
plt.plot(cost)
plt.title('Cost Function')
plt.xlabel('Iters')
plt.show()
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值