现有一组某市的房价与其位置数据如表 2-12 所示,其中 D 表示房屋到市中心的直线距离,单位为 km,R 表示房屋单价,单位为元/m²。
表 2-12 房价与其位置数据表
序号 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
---|---|---|---|---|---|---|---|---|---|
D/km | 4.2 | 7.1 | 6.3 | 1.1 | 0.2 | 4.0 | 3.5 | 8 | 2.3 |
R/(元/m²) | 8600 | 6100 | 6700 | 12000 | 14200 | 8500 | 8900 | 6200 | 11200 |
其中:
和
分别是第 i 个数据点的距离和房价。
:距离的总和。
:房价的总和。
:距离平方的总和。
:距离和房价的乘积的总和。
我们将表格补充中间值,进行计算:
序号 | (km) | (元/m²) | ||
---|---|---|---|---|
1 | 4.2 | 8600 | 17.64 | 36120 |
2 | 7.1 | 6100 | 50.41 | 43310 |
3 | 6.3 | 6700 | 39.69 | 42210 |
4 | 1.1 | 12000 | 1.21 | 13200 |
5 | 0.2 | 14200 | 0.04 | 2840 |
6 | 4.0 | 8500 | 16.00 | 34000 |
7 | 3.5 | 8900 | 12.25 | 31150 |
8 | 8.0 | 6200 | 64.00 | 49600 |
9 | 2.3 | 11200 | 5.29 | 25760 |
接下来,我们计算求和:
现在将上述值代入最小二乘法公式:
最终的房价与距离关系为:
可视化
和
的取值。(单位:cm)
最大似然估计讲的太高级,其实就是知道数据,然后要让能够观测到这些数据的概率最大化
公式的话:就是一个求均值,一个求偏方差
假设某学校男生的身高服从正态分布 N(μ,σ2),现从全校所有男生中随机采样测量得到身高数据如表 2-13 所示
表 2-13 身高数据表
序号 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 |
---|---|---|---|---|---|---|---|---|
身高 | 167 | 175 | 163 | 169 | 174 | 187 | 168 | 176 |
正态分布的概率密度函数为:
最大似然估计原理: 给定样本数据
,最大似然估计通过最大化样本数据联合概率(似然函数)来估计参数。
似然函数
为:
(1)取对数,得到对数似然函数:
(2)对
求偏导,令其等于 0:
样本均值是
的最大似然估计值
(3)对
求偏导,令其等于 0:
(4)得到:
样本大小: n=8
:
: 先计算每个样本与均值的差平方:
差平方结果:
然后求和并除以样本大小 n:
让我们计算并展示最终结果。
通过计算得到:
: 172.375 cm
: 47.984 cm²
和
的估计值。
假设某学校男生的身高服从正态分布 N(μ,σ2),上一次测试时得到身高均值的估计值为 172 cm,方差为 36。故在本次测试前,以 0.7 的概率相信该校男生身高服从 N(172,36)。
且先验权重为 0.7(即我们对先验分布有较高的置信度)。
:
最大后验估计(MAP)通过最大化后验分布,来估计
和
。
其中 α=0.7是先验权重。
的 MAP 估计: 在 MAP 方法中,
的估计需要结合样本方差和先验分布。公式为:
计算样本均值
和样本方差
:
将
、
、先验权重
、样本数据代入公式:
代入数据计算:
让我们一步步计算得到结果。
通过最大后验估计法(MAP),得到男生身高分布参数的估计值为:
其中,
,要求选取初始点
,终止误差
。
梯度下降法是迭代优化方法,其核心是沿目标函数的负梯度方向更新解:
其中:
是目标函数的梯度。
是学习率(步长)。
检查停止条件:
让我们选择一个合适的学习率 α,并开始计算迭代过程。
通过梯度下降法计算,得到的结果为:
该解满足终止条件
。
代码:
import numpy as np
# Define the objective function and its gradient
def f(X):
x1, x2 = X
return (x1 - 2)**4 + (x1 - 2*x2)**2
def grad_f(X):
x1, x2 = X
df_dx1 = 4 * (x1 - 2)**3 + 2 * (x1 - 2 * x2)
df_dx2 = -4 * (x1 - 2 * x2)
return np.array([df_dx1, df_dx2])
# Gradient descent parameters
X = np.array([0, 3]) # Initial point
epsilon = 0.1 # Stopping criterion
alpha = 0.01 # Learning rate
iterations = 0 # Iteration counter
# Gradient descent loop
while np.linalg.norm(grad_f(X)) >= epsilon:
X = X - alpha * grad_f(X) # Update rule
iterations += 1
X, f(X), iterations
可视化:
若要使用表 2-12 中的数据构造一个用于预测房屋价格与房屋到市区距离之间关系的线性模型,其中模型优化过程使用梯度下降算法,试取任意初始点开始迭代,步长取 0.05,计算前两次迭代的结果。
目标是通过梯度下降法优化模型参数 a和 b。
其中 α是学习率。
# Data from Table 2-12
D = np.array([4.2, 7.1, 6.3, 1.1, 0.2, 4.0, 3.5, 8.0, 2.3]) # Distances
R = np.array([8600, 6100, 6700, 12000, 14200, 8500, 8900, 6200, 11200]) # Prices
# Initialize parameters
a = 0 # Initial value for slope
b = 0 # Initial value for intercept
alpha = 0.05 # Learning rate
n = len(D) # Number of data points
# Function to compute gradients
def compute_gradients(a, b, D, R):
da = -(1 / n) * np.sum(D * (R - (a * D + b))) # Gradient for a
db = -(1 / n) * np.sum(R - (a * D + b)) # Gradient for b
return da, db
# Store results for the first two iterations
results = []
for i in range(2): # Compute two iterations
da, db = compute_gradients(a, b, D, R) # Compute gradients
a = a - alpha * da # Update a
b = b - alpha * db # Update b
results.append((a, b)) # Store updated parameters
results
得到结果:
特性 | 梯度下降法 | 共轭梯度法 |
---|---|---|
方向选择 | 沿负梯度方向 | 沿共轭方向(结合前几步信息) |
收敛速度 | 慢,可能震荡 | 快,避免震荡 |
学习率依赖 | 需要选择学习率,调试较复杂 | 自动线搜索,无需人工调整 |
适用场景 | 简单问题或小规模优化 | 大规模、复杂或条件数较大问题 |
共轭梯度法通过引入共轭方向解决了梯度下降法的上述问题,特别是在处理二次优化问题时效果显著。
其中,
,取迭代起始点为
。
其中
其中:
是第 k 步的搜索方向。
是步长,通过线搜索确定。
目标函数:
梯度为:
# Define the gradient and Hessian of the function
def gradient(X):
x1, x2 = X
df_dx1 = 1 + 4 * x1 + 2 * x2
df_dx2 = -1 + 2 * x1 + 2 * x2
return np.array([df_dx1, df_dx2])
def hessian():
# Hessian matrix of the quadratic function
return np.array([[4, 2], [2, 2]])
# Initialize variables
X = np.array([1, 1]) # Starting point
grad = gradient(X) # Initial gradient
P = -grad # Initial search direction (negative gradient)
H = hessian() # Hessian matrix
# Store results for the first two iterations
results = []
for _ in range(2):
# Compute step size alpha_k
alpha = -(grad @ P) / (P @ H @ P)
# Update X
X_new = X + alpha * P
# Store the result
results.append((X_new, alpha))
# Compute new gradient
grad_new = gradient(X_new)
# Compute beta_k
beta = (grad_new @ grad_new) / (grad @ grad)
# Update search direction
P = -grad_new + beta * P
# Update X and gradient for next iteration
X, grad = X_new, grad_new
results
得到结果:
若要使用表 2-12 中的数据构造一个用于预测房屋价格与房屋到市区距离之间关系的线性模型,其中模型优化过程使用共轭梯度法,试取任意初始点开始迭代,计算前两次迭代的结果。
根据表 2-12 中的数据,构建一个线性模型:
其中:
通过共轭梯度法优化损失函数:
这里,损失函数是均方误差(MSE),且目标是找到参数 a和 b 使得 J(a,b) 最小。
对于线性回归模型的 MSE:
让我们计算结果。
通过共轭梯度法计算得到前两次迭代结果如下:
# Re-importing necessary libraries
import numpy as np
# Data from Table 2-12
D = np.array([4.2, 7.1, 6.3, 1.1, 0.2, 4.0, 3.5, 8.0, 2.3]) # Distances
R = np.array([8600, 6100, 6700, 12000, 14200, 8500, 8900, 6200, 11200]) # Prices
n = len(D)
# Initial parameters
a, b = 0, 0 # Starting point
X = np.array([a, b]) # Parameter vector
# Hessian matrix
H = (1 / n) * np.array([
[np.sum(D**2), np.sum(D)],
[np.sum(D), n]
])
# Gradient function
def gradient(X):
a, b = X
da = -(1 / n) * np.sum(D * (R - (a * D + b)))
db = -(1 / n) * np.sum(R - (a * D + b))
return np.array([da, db])
# Store results for first two iterations
results = []
# Initial gradient and search direction
grad = gradient(X)
P = -grad
# Perform two iterations of conjugate gradient method
for _ in range(2):
# Step size alpha
alpha = -(grad @ P) / (P @ H @ P)
# Update parameters
X_new = X + alpha * P
# Store the result
results.append((X_new, alpha))
# Compute new gradient
grad_new = gradient(X_new)
# Compute beta
beta = (grad_new @ grad_new) / (grad @ grad)
# Update search direction
P = -grad_new + beta * P
# Update X and gradient for the next iteration
X, grad = X_new, grad_new
results
其中,
,取迭代起始点为
。
代码:
# Define the gradient and Hessian functions
def gradient(X):
x1, x2 = X
df_dx1 = 3 * (x1 - x2)**2 + 2 * (x1 + 3 * x2)
df_dx2 = -3 * (x1 - x2)**2 + 6 * (x1 + 3 * x2)
return np.array([df_dx1, df_dx2])
def hessian(X):
x1, x2 = X
d2f_dx1dx1 = 6 * (x1 - x2) + 2
d2f_dx1dx2 = -6 * (x1 - x2) + 6
d2f_dx2dx2 = 6 * (x1 - x2) + 18
return np.array([[d2f_dx1dx1, d2f_dx1dx2],
[d2f_dx1dx2, d2f_dx2dx2]])
# Initial conditions
X = np.array([1.0, 2.0]) # Starting point
# Store results for the first two iterations
results = []
# Perform two iterations of Newton's method
for _ in range(2):
grad = gradient(X) # Gradient at X
H = hessian(X) # Hessian at X
H_inv = np.linalg.inv(H) # Inverse of Hessian
X_new = X - H_inv @ grad # Newton update
results.append(X_new) # Store the updated X
X = X_new # Update X for the next iteration
results
Hessian 矩阵计算 | 需要明确计算 | 通过梯度近似逐步构造 |
---|
Hessian 矩阵逆计算 | 显式计算 | 通过递推公式逐步更新逆矩阵 |
---|
计算成本 | 高,复杂度O(n^3) | 较低,复杂度 O(n^2) |
---|
稳定性 | 可能发散(Hessian 非正定) | 更稳定,近似矩阵保持正定 |
---|
适用场景 | 低维问题或二次优化问题 | 高维问题,非线性优化 |
---|
的矩阵)。
,对高维优化问题来说非常昂贵。
拟牛顿法(Quasi-Newton Method)通过近似 Hessian 矩阵及其逆矩阵,克服了牛顿法的上述缺陷。其主要思想是逐步构造一个对 Hessian 的近似,而不直接计算 Hessian。
其中,
,取迭代起始点为
。
代码:
# Define the gradient function
def gradient(X):
x1, x2 = X
df_dx1 = 2 * (x1 + 4 * x2)
df_dx2 = -3 * (4 - x2)**2 + 8 * (x1 + 4 * x2)
return np.array([df_dx1, df_dx2])
# Initialize parameters
X = np.array([2.0, 1.0]) # Starting point
B = np.eye(2) # Initial Hessian approximation (identity matrix)
# Store results for the first two iterations
results = []
# Perform two iterations of quasi-Newton method (BFGS update)
for _ in range(2):
grad = gradient(X) # Gradient at current X
# Compute the search direction
P = -np.linalg.inv(B) @ grad
# Update X
X_new = X + P
# Store the result
results.append(X_new)
# Compute new gradient
grad_new = gradient(X_new)
# Update B using the BFGS formula
s = X_new - X
y = grad_new - grad
B = B + np.outer(y, y) / (y.T @ s) - (B @ np.outer(s, s) @ B) / (s.T @ B @ s)
# Update X for the next iteration
X = X_new
results
方法 | 每次梯度计算复杂度 | 适用场景 |
---|---|---|
梯度下降法 (GD) | O(n) | 小规模数据,追求高精度 |
随机梯度下降法 (SGD) | O(1) | 大规模数据,在线学习,训练时间较短需求 |
其中:
其中:
是随机抽取的一个样本。
是该样本的梯度。
每次迭代样本量 | 单个样本 | 小批量样本 |
---|
计算复杂度 | 每次更新计算快,复杂度低 | 较 SGD 高,但低于全梯度下降 |
---|
梯度波动性 | 较大,容易不稳定 | 较小,更接近全局梯度 |
---|
收敛速度 | 较慢,收敛过程不平稳 | 更快,收敛稳定性更强 |
---|
硬件利用 | 计算无法并行化,效率低 | 利用并行计算能力,效率高 |
---|
适用场景 | 超大规模数据 | 中大规模数据,适配并行硬件 |
---|
其中 m 是小批量的样本数。
是一个随机样本。
设
为观测数据的似然函数,
为用 EM 算法得到的参数估计序列,
为对应的似然函数序列,则
是单调递增的。
在第 i 次迭代中,辅助函数
表示条件期望:
根据 Jensen 不等式,可以证明对数似然函数有以下关系:
。
由 EM 算法性质:
结合 Jensen 不等式,得到:
通过以上分析,EM 算法在每次迭代中都保证:
即似然函数
是单调递增的。
简单来说:
简单讲一下:
蒙特卡洛方法是一种基于随机采样的数值计算方法,其理论基础是大数法则和概率统计理论:
,可以近似计算:
假设在单位正方形内(边长为 2,中心为原点)绘制一个单位圆(半径为 1),则:
。
中均匀随机生成 n 个点 (x,y)。
,则点落在单位圆内。
正则化方法 | 核心思想 | 应用场景 |
---|---|---|
L1正则化 | 限制特征的绝对值,产生稀疏解 | 特征选择、高维数据 |
L2 正则化 | 限制特征的平方和,防止权重过大 | 回归模型、高维数据、神经网络 |
Dropout | 随机屏蔽神经元,减少过拟合 | 深度学习、全连接层 |
数据增强 | 增加数据多样性,扩展训练集规模 | 图像、文本、时序数据 |
Early Stopping | 限制训练轮次,避免训练过长导致过拟合 | 神经网络训练 |
正则化方法从多个角度(损失函数、数据、训练过程)限制模型的复杂性,提升泛化能力。在实际应用中,不同任务通常会组合使用多种正则化方法来取得最优效果。
正则化
范数(即权重绝对值的和)的惩罚项。
其中:
:模型的原损失函数。
:权重的绝对值。
正则化
范数(即权重平方和)的惩罚项。
不同,
正则化不会将权重变为完全的零,而是会使权重趋近于零(缩小权重值)。
通过引入先验信息,正则化方法让模型更偏向简单解,避免过拟合。
使用
范数惩罚可以达到什么样的约束效果?使用
范数惩罚又能达到什么样的约束效果?能够达到这些约束效果的原因是什么?
特性 | L2 正则化(Ridge) | L1 正则化(Lasso) |
---|---|---|
惩罚方式 | 参数平方和 | 参数绝对值和 |
对权重的影响 | 所有权重趋于接近零,但不完全为零 | 部分权重直接为零,导致稀疏性 |
特征选择能力 | 不具有特征选择能力 | 具有特征选择能力 |
适用场景 | 数据维度不高,特征重要性较为均衡的场景 | 高维稀疏数据,部分特征重要性较高的场景 |
度后该像素点所对应的新的坐标。
对于图像
,假设在以图像中心点为原点建立的坐标系中,某个像素点的坐标为
import numpy as np
def rotate_point(x, y, width, height, theta_degrees):
"""
Rotate a point (x, y) around the center of an image with dimensions (width, height)
by an angle theta (in degrees).
Args:
x (float): Original x-coordinate of the point.
y (float): Original y-coordinate of the point.
width (int): Width of the image.
height (int): Height of the image.
theta_degrees (float): Rotation angle in degrees (clockwise).
Returns:
(float, float): New coordinates of the point after rotation.
"""
# Convert angle from degrees to radians
theta = np.radians(theta_degrees)
# Translate point to the center of the image (centered coordinates)
x_c = x - width / 2
y_c = y - height / 2
# Apply rotation matrix
x_c_rotated = x_c * np.cos(theta) + y_c * np.sin(theta)
y_c_rotated = -x_c * np.sin(theta) + y_c * np.cos(theta)
# Translate point back to the original coordinate system
x_rotated = x_c_rotated + width / 2
y_rotated = y_c_rotated + height / 2
return x_rotated, y_rotated
# Example usage
width, height = 200, 100 # Image dimensions (width, height)
x, y = 150, 50 # Original point coordinates
theta_degrees = 45 # Rotation angle in degrees (clockwise)
rotated_x, rotated_y = rotate_point(x, y, width, height, theta_degrees)
(rotated_x, rotated_y)
得到旋转后的点坐标为
。
对抗训练(Adversarial Training)是一种提升模型鲁棒性的训练方法: