Python 梯度下降不收敛

Python gradient descent not converge

所以我是机器学习的新手,我一直在尝试实现梯度下降。我的代码似乎是正确的(我认为)但它没有收敛到全局最优。

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


def AddOnes(matrix):
    one = np.ones((matrix.shape[0], 1))
    X_bar = np.concatenate((one, matrix), axis=1)
    return X_bar


# Load data
df = pd.read_excel("Book1.xlsx", header=3)
X = np.array([df['Height']]).T
y = np.array([df['Weight']]).T

m = X.shape[0]
n = X.shape[1]
iterations = 30

# Build X_bar
X = AddOnes(X)

# Gradient descent
alpha = 0.00003
w = np.ones((n+1,1))
for i in range(iterations):
    h = np.dot(X, w)
    w -= alpha/m * np.dot(X.T, h-y)

print(w)

x0 = np.array([np.linspace(145, 185, 2)]).T
x0 = AddOnes(x0)
y0 = np.dot(x0, w)
x0 = np.linspace(145, 185, 2)

# Visualizing
plt.plot(X, y, 'ro')
plt.plot(x0, y0)
plt.axis([140, 190, 40, 80])
plt.xlabel("Height(cm)")
plt.ylabel("Weight(kg)")
plt.show()

Visualizing data

您正在对单个神经元使用线性回归,无论您提供的数据集如何,单个神经元只能学习一条直线,其中 W 充当斜率,您的网络已经为您的 X 学习了最佳 W,使得 WX 给出最小的错误。

输出的散点图(红点)显示了你的数据集值,你可以观察到,数据集是非线性的,所以即使你训练 1M 次,算法也永远不会收敛。但是学习到的函数肯定是最优的,因为它是一条误差最小的直线。

所以,我建议您使用具有非线性激活的多层,例如 ReLu 和 Sigmoid。在预测实数时在输出端使用线性激活。