【发布时间】:2018-08-29 20:48:51
【问题描述】:
我是机器学习的新手。我从梯度下降的线性回归开始。我有这方面的python代码,我以这种方式理解。我的问题是:梯度下降算法最小化函数,我可以绘制这个函数吗?我想看看最小值的函数是什么样的。有可能吗? 我的代码:
import matplotlib.pyplot as plt import numpy as np
def sigmoid_activation(x):
return 1.0 / (1 + np.exp(-x))
X = np.array([
[2.13, 5.49],
[8.35, 6.74],
[8.17, 5.79],
[0.62, 8.54],
[2.74, 6.92] ])
y = [0, 1, 1, 0, 0]
xdata = [row[0] for row in X] ydata = [row[1] for row in X]
X = np.c_[np.ones((X.shape[0])), X] W = np.random.uniform(size=(X.shape[1], ))
lossHistory = []
for epoch in np.arange(0, 5):
preds = sigmoid_activation(X.dot(W))
error = preds - y
loss = np.sum(error ** 2)
lossHistory.append(loss)
gradient = X.T.dot(error) / X.shape[0]
W += - 0.44 * gradient
plt.scatter(xdata, ydata) plt.show()
plt.plot(np.arange(0, 5), lossHistory) plt.show()
for i in np.random.choice(5, 5):
activation = sigmoid_activation(X[i].dot(W))
label = 0 if activation < 0.5 else 1
print("activation={:.4f}; predicted_label={}, true_label={}".format(
activation, label, y[i]))
Y = (-W[0] - (W[1] * X)) / W[2]
plt.scatter(X[:, 1], X[:, 2], c=y) plt.plot(X, Y, "r-") plt.show()
【问题讨论】:
标签: python machine-learning linear-regression gradient-descent