[机器学习] 监督学习之线性回归与逻辑回归

一、监督学习概述

监督学习是利用有标记的数据进行模型训练,使模型能够对未知数据进行预测。训练数据包含输入特征(通常用 (x) 表示)和对应的输出标签(通常用 (y) 表示)。其主要任务可分为回归(预测连续值)和分类(预测离散类别)。

二、线性回归

(超爽中英!) 2024公认最好的【吴恩达机器学习】教程!附课件代码 Machine Learning Specialization

(一)模型表示

单变量线性回归模型: h θ ( x ) = θ 0 + θ 1 x h_{\theta}(x)=\theta_{0}+\theta_{1}x hθ(x)=θ0+θ1x,其中 θ 0 \theta_{0} θ0 为截距, θ 1 \theta_{1} θ1 为斜率。

from sklearn.linear_model import LinearRegression
import numpy as np
import matplotlib.pyplot as plt

# 生成模拟数据(这里简单地使用线性关系加一些噪声来模拟)
np.random.seed(0)
x = np.linspace(0, 10, 100).reshape(-1, 1)  # 生成100个在0到10之间均匀分布的x值,并转换为列向量
theta_0_true = 2  # 真实的截距
theta_1_true = 3  # 真实的斜率
y_true = theta_0_true + theta_1_true * x
y = y_true + np.random.normal(0, 2, size=(100, 1))  # 添加一些正态分布的噪声模拟实际观测值

# 创建线性回归模型对象并拟合数据
model = LinearRegression()
model.fit(x, y)

# 获取拟合的参数
theta_0_fit = model.intercept_[0]
theta_1_fit = model.coef_[0][0]

# 定义预测函数(其实可以直接使用model.predict方法进行预测,这里只是为了形式统一展示)
def h_theta(x, theta_0, theta_1):
    """
    根据拟合的参数进行预测
    """
    return theta_0 + theta_1 * x


# 使用拟合的模型进行预测
y_pred = h_theta(x, theta_0_fit, theta_1_fit)

# 可视化数据和拟合的直线
plt.scatter(x, y, label='Observed Data')
plt.plot(x, y_pred, color='r', label='Fitted Line')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Linear Regression')
plt.legend()
plt.show()

代码中,使用了 sklearn 库中的 LinearRegression 类来拟合线性回归模型,它内部已经实现了高效的最小二乘法计算等逻辑,通过调用 fit 方法传入输入特征 x 和目标值 y 就可以完成模型的拟合,然后可以通过 intercept_ 属性获取截距(对应 theta_0),通过 coef_ 属性获取系数(对应 theta_1)
在这里插入图片描述

多变量线性回归模型: h θ ( x ) = θ 0 + θ 1 x 1 + θ 2 x 2 + ⋯ + θ n x n = θ T x h_{\theta}(x)=\theta_{0}+\theta_{1}x_{1}+\theta_{2}x_{2}+\cdots+\theta_{n}x_{n}=\theta^{T}x hθ(x)=θ0+θ1x1+θ2x2++θnxn=θTx,这里 x = [ 1 x 1 x 2 ⋮ x n ] x = \begin{bmatrix} 1 \\ x_{1} \\ x_{2} \\ \vdots \\ x_{n} \end{bmatrix} x= 1x1x2xn , θ = [ θ 0 θ 1 θ 2 ⋮ θ n ] \theta = \begin{bmatrix} \theta_{0} \\ \theta_{1} \\ \theta_{2} \\ \vdots \\ \theta_{n} \end{bmatrix} θ= θ0θ1θ2θn

(二)损失函数

损失函数衡量了当前模型预测值与真实目标值之间的差异程度。

均方误差损失函数: J ( θ ) = 1 2 m ∑ i = 1 m ( h θ ( x ( i ) ) − y ( i ) ) 2 J(\theta)=\frac{1}{2m}\sum_{i = 1}^{m}(h_{\theta}(x^{(i)})-y^{(i)})^{2} J(θ)=2m1i=1m(hθ(x(i))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

微AI

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值