吴恩达机器学习作业一

本文介绍了如何通过Python实现线性回归,包括数据预览、使用均方误差作为损失函数的模型构建、梯度下降算法求解最优参数,并展示了实际预测结果。关键步骤包括数据读取、散点图展示和使用梯度下降进行参数迭代直至收敛。
摘要由CSDN通过智能技术生成

Introduction

In this exercise, you will implement linear regression and get to see it work
on data.

首先,先看看数据是什么样的好进一步分析

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

path = "data/ex1data1.txt"
data = pd.read_csv(path, header=None, names=['Population', 'profit'])
print(data)
data.plot(kind="scatter", x="Population", y="profit", figsize=(8, 5))
plt.show()

在这里插入图片描述
采用线性回归,尽可能准确地预测输出。
要拟合出一条直线采用均方误差作为损失函数,

我们预测

函数:
在这里插入图片描述
损失函数:
在这里插入图片描述
这里均方误差使用1/2m而不是1/m是因为后期梯度下降时,对损失函数求偏导平方求导会出现2,这里乘1/2
会使得后续计算方便
持续更新a于b直到收敛
在这里插入图片描述
下面就是如何计算偏导数,
在这里插入图片描述

# 均方误差
def squared_error(a, b):
    res = 0
    for row in data.iterrows():
        population = row[1][0]
        profit = row[1][1]
        res += pow(population*a+b - profit, 2)
    res = 1/(2*data.size)*res
    return res

使得均方误差足够小的a和b即为解,使用梯度下降.

同时更新a和b直到均方误差足够小(凭自己喜好),这里我规定偏导数
在这里插入图片描述
达到-9数量级时认为收敛,

附上源码

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


# 均方误差
def squared_error(a, b):
    res = 0
    d_a = 0
    d_b = 0
    for row in data.iterrows():
        population = row[1][0]
        profit = row[1][1]
        res += pow(population*a + b - profit, 2)
        d_a += (population*a + b - profit) * population
        d_b += (population*a + b - profit)
    res *= 1/(2*len(data))
    d_a *= 1/len(data)
    d_b *= 1/len(data)
    print("欧氏距离:", res, "   d_a:", d_a,  "     a:", a)
    return d_a, d_b


# 梯度下降
def gradient_descent(a, b, alpha):
    d_a, d_b = squared_error(a, b)
    print(type(d_b))
    while abs(d_a) > 10e-9 and abs(d_b) > 10e-9:
        tamp_a = a - alpha * d_a
        tamp_b = b - alpha * d_b
        a = tamp_a
        b = tamp_b
        d_a, d_b = squared_error(a, b)
    return a, b


path = "data/ex1data1.txt"
data = pd.read_csv(path, header=None, names=['Population', 'profit'])
data.plot(kind="scatter", x="Population", y="profit", figsize=(8, 5))


a, b = gradient_descent(0, 0, 0.02)
x = np.linspace(data.Population.min(), data.Population.max(), 100)
y = a*x + b
plt.plot(x, y)
plt.show()


结果如下
在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值