多項式回帰の原理と実装、重回帰の原理

1. 多項式回帰の原理と実装

ノートは「Mathematics of Vernacular Machine Learning」からのものです

1.1 多項式回帰の原理

変数xxを予測するxと変数yyyの関係
例:広告料xxxyyy
データを曲線でフィッティングする
導出プロセスは、導出に関する私の以前のブログに似ています。関連メモ:最小二乗法の原理と実装

θ ( x ) の不分散
= θ 0 + θ 1 x + θ 2 x 2 + ⋯ + θ nxn f_{\theta}(x)=\theta_0+\theta_1x+\theta_2x^2+\cdots+\theta_nx^nf( × )=0+1バツ+2バツ2++バツn数値が大きいほど
、トレーニングデータの適合(過適合)の精度は高くなりますが、このフィッティング曲線を使用してトレーニングデータ以外のデータを予測することが目的です。この曲線またはモデルには、代表的なトレーニングデータだけでなく、一般化機能が必要です、過学習によりモデルが代表的ではなくなり、一般的な状況を予測できなくなります。

1.2 多項式回帰の実装

広告料××xyyy

import numpy as np
import matplotlib.pyplot as plt

# 读入训练数据
train = np.loadtxt('~/Downloads/sourcecode-cn/click.csv', delimiter=',', dtype='int', skiprows=1)
train_x = train[:,0] # 第一列
train_y = train[:,1] # 第二列

データ前処理ステップの 1 つ: パラメーターの収束が速くなるように、トレーニング データを標準化/正規化します。データ内のすべての x の
平均値μ \muを計算します。μと標準偏差σ \sigmaσ、各値 x は次の式に従って標準化されます。

# 标准化
mu = train_x.mean()
sigma = train_x.std()
def standardize(x):
    return (x - mu) / sigma

train_z = standardize(train_x)
# 展示标准化后的数据
plt.plot(train_z, train_y, 'o')
plt.show()

# 参数初始化
theta = np.random.rand(3)

# 创建训练数据的矩阵
def to_matrix(x):
    return np.vstack([np.ones(x.size), x, x ** 2]).T

X = to_matrix(train_z)

教師データが多いので、1行のデータを1教師データとして扱い、行列形式で処理すると良いでしょう。

# 预测函数
def f(x):
    return np.dot(x, theta)

# 目标函数
def E(x, y):
    return 0.5 * np.sum((y - f(x)) ** 2)

# 学习率
ETA = 1e-3
# 初始化误差的差值,随后作为循环结束判断依据
diff = 1
# 初始化更新次数
count = 0



この例には 3 つのパラメーターθ 0 、 θ 1 、 θ 2 \theta_0、 \theta_1、 \theta_2 があるため、パラメーターの更新式 (勾配の方向が安定した状態を維持できるように、パラメーターを更新するときにすべてのパラメーターを同期して更新する必要があることに注意してください)。012,
方法 1: ループ本体内の 3 つの数式を使用して 3 つのパラメーターを直接更新します。

方法 2: パラメータ更新式の後半を行列として記述し、



勾配降下法を使用して1 つの式で 3 つのパラメータを更新する

# 直到误差的差值小于 0.01 为止,重复参数更新
error = E(X, train_y)
while diff > 1e-2:
    # 更新结果保存到临时变量
    # 这里使用矩阵直接计算出所有参数,而不是每个参数进行更新迭代
    theta = theta - ETA * np.dot(f(X) - train_y, X)

    # 计算与上一次误差的差值
    current_error = E(X, train_y)
    diff = error - current_error
    error = current_error

    # 输出日志
    count += 1
    log = '第 {} 次 : theta = {}, 差值 = {:.4f}'
    print(log.format(count, theta, diff))

# 绘图确认
x = np.linspace(-3, 3, 100)
plt.plot(train_z, train_y, 'o')
plt.plot(x, f(to_matrix(x)))
plt.show()


横軸に繰り返し回数、縦軸に平均二乗誤差をとり、繰り返し回数が増加するにつれて平均二乗誤差は徐々に減少します。

# 均方误差
def MSE(x, y):
    return (1 / x.shape[0]) * np.sum((y-f(x))**2)

# 用随机值初始化参数
theta = np.random.rand(3)

# MSE的历史记录
errors = []

# 误差的差值
diff = 1
# 重复学习
errors.append(MSE(X, train_y))
while diff > 1e-2:
    theta = theta - ETA * np.dot(f(X) - train_y, X)
    errors.append(MSE(X, train_y))
    diff = errors[-2] - errors[-1]
# 绘制误差变化图
x = np.arange(len(errors))
plt.plot(x, errors)
plt.show()

上記のプロセスでは、勾配降下法 (すべてのトレーニング データを使用) を使用して目的関数を最適化しましたが、次に、確率的勾配降下法 (1 つのトレーニング データのみを使用) を使用して、確率的勾配降下法の n 回の目的関数の最適化 (所要時間)比較的短い時間
) 1 つの勾配降下に相当します (比較的長い時間がかかります)


上の写真のkkkはランダムです

import numpy as np
import matplotlib.pyplot as plt

# 读入训练数据
train = np.loadtxt('~/Downloads/sourcecode-cn/click.csv', delimiter=',', dtype='int', skiprows=1)
train_x = train[:,0]
train_y = train[:,1]

# 标准化
mu = train_x.mean()
sigma = train_x.std()
def standardize(x):
    return (x - mu) / sigma

train_z = standardize(train_x)

# 参数初始化
theta = np.random.rand(3)

# 创建训练数据的矩阵
def to_matrix(x):
    return np.vstack([np.ones(x.size), x, x ** 2]).T

X = to_matrix(train_z)

# 预测函数
def f(x):
    return np.dot(x, theta)

# 均方误差
def MSE(x, y):
    return (1 / x.shape[0]) * np.sum((y - f(x)) ** 2)

# 学习率
ETA = 1e-3

# 误差的差值
diff = 1

# 更新次数
count = 0

# 重复学习
error = MSE(X, train_y)
while diff > 1e-2:
    # 使用随机梯度下降法更新参数
    p = np.random.permutation(X.shape[0]) # 随机p
    for x, y in zip(X[p,:], train_y[p]): # 选择第p行的训练数据(此例中一个x,一个y)对参数进行更新
        theta = theta - ETA * (f(x) - y) * x

    # 计算与上一次误差的差值
    current_error = MSE(X, train_y)
    diff = error - current_error
    error = current_error

    # 输出日志
    count += 1
    log = '第 {} 次 : theta = {}, 差值 = {:.4f}'
    print(log.format(count, theta, diff))

# 绘图确认
x = np.linspace(-3, 3, 100)
plt.plot(train_z, train_y, 'o')
plt.plot(x, f(to_matrix(x)))
plt.show()

2. 重回帰の原理

2.1 重回帰の原理

複数の変数を予測しますxxxと変数yyyの関係
例: 広告料x 1 x_1バツ1、広告の配置x 2 x_2バツ2、広告レイアウト サイズx 3 x_3バツ3そして「yy」を押しますy
f θ ( x 1 , ⋯ , xn ) = θ 0 + θ 1 x 1 + θ 2 x 2 + ⋯ + θ nxn f_{\theta}(x_1,\cdots,x_n)=\theta_0+\theta_1x_1+\theta_2x_2+\ cdots+\theta_nx_nf( ×1×)=0+1バツ1+2バツ2++バツ
θ = [ θ 0 θ 1 ⋮ θ n ] 、 x = [ x 0 x 1 ⋮ xn ] ( x 0 = 1 ) \boldsymbol{\theta}= \left [ \begin{matrix} \theta_0\\ \theta_1 \ \ \vdots\\ \theta_n \end{行列} \right ] 、 \boldsymbol{x}= \left [ \begin{行列} x_0\\ x_1 \\ \vdots\\ x_n \end{行列} \right ]( x_0=1)= 01 ×= バツ0バツ1バツ ×0=1
f θ ( x ) = θ T x = θ 0 x 0 + θ 1 x 1 + θ 2 x 2 + ⋯ + θ nxn f_{\boldsymbol{\theta}}(\boldsymbol{x})=\boldsymbol {\theta}^T\boldsymbol{x}=\theta_0x_0+\theta_1x_1+\theta_2x_2+\cdots+\theta_nx_nf( × )=T ×=0バツ0+1バツ1+2バツ2++バツ

θ j : = θ j − η ∑ i = 1 n ( f θ ( x ( i ) ) − y ( i ) ) xj ( i ) \theta_j:=\theta_j-\eta\sum_{i=1}^n \big(f_{\boldsymbol{\theta}}(\boldsymbol{x}^{(i)})-y^{(i)}\big)x_j^{(i)}j:=ji = 1( f( ×( i ) )y( i ) )xj()
上記の式はすべてのトレーニング データを使用します

データの前処理中にすべての変数 x を標準化する必要があることに注意してください。
変数x 1 x_1を計算します。バツ1変数x 1 x_1に次の式を使用した、すべての値の平均と標準偏差。バツ1すべての値は標準化されており、他の値は類似しています。

トレーニング プロセスは多項式回帰と似ていますが、唯一の違いは予測関数が異なることです。

おすすめ

転載: blog.csdn.net/weixin_48524215/article/details/131362902