我对机器学习非常陌生,正在尝试实施MLP,但是成本函数似乎在达到全局最小值之前已达到局部最小值。我将成本绘制为迭代函数(包括一个0值,以免被y轴开始的地方所欺骗)。 这是我尝试使用的代码:
import numpy as np
class NNet(object):
def __init__(self, n_in, n_hidden, n_out):
self.n_in = n_in
self.n_hidden = n_hidden
self.n_out = n_out
self.W1 = np.random.randn(n_in, n_hidden)
self.W2 = np.random.randn(n_hidden, n_out)
self.b1 = np.random.randn(n_hidden,)
self.b2 = np.random.randn(n_out,)
def sigmoid(self, z):
return 1/(1 + np.exp(-z))
def sig_prime(self, z):
return (np.exp(-z))/((1+np.exp(-z))**2)
def propagate_forward(self, X):
self.z1 = np.dot(self.W1.T, X) + self.b1
self.a1 = self.sigmoid(self.z1)
self.z2 = np.dot(self.W2.T, self.a1) + self.b2
self.a2 = self.sigmoid(self.z2)
return self.a2
def cost(self, y, y_hat):
return np.mean([np.sum((y[i] - y_hat[i])**2) for i in range(y.shape[0])])/2
def cost_grad(self, X, y):
y_hat = self.propagate_forward(X)
d2 = np.multiply(self.sig_prime(self.z2), -(y - y_hat))
gJ_W2 = np.matrix(np.multiply(self.a1.T, d2))
d1 = np.dot(self.W2, d2)*self.sig_prime(self.z1)
gJ_W1 = np.dot(np.matrix(X).T, np.matrix(d1))
return [gJ_W1, d1, gJ_W2, d2]
m = 1000
n = 1
X = np.zeros((m, n))
y = np.zeros((m,1))
import random
import math
i = 0
for r, theta in zip(np.linspace(0, 5, num=m), np.linspace(0, 8 * math.pi, num=m)):
r += random.random()
X[i] = [r * math.cos(theta), r * math.sin(theta)]
if i < 333:
y[i] = 0
elif i < 666:
y[i] = 1
else:
y[i] = 2
i += 1
nnet = NNet(n, 5, 1)
learning_rate = 0.2
improvement_threshold = 0.995
cost = np.inf
xs = []
ys = []
iter = 0
while cost > 0.2:
cost = nnet.cost(y, [nnet.propagate_forward(x_train) for x_train
if iter % 100 == 0:
xs.append(iter)
ys.append(cost)
print("Cost", cost)
if iter >= 1000:
print("Gradient descent is taking too long, giving up.")
break
cost_grads = [nnet.cost_grad(x_train, y_train) for x_train, y_train in zip(X, y)]
gW1 = [grad[0] for grad in cost_grads]
gb1 = [grad[1] for grad in cost_grads]
gW2 = [grad[2] for grad in cost_grads]
gb2 = [grad[3] for grad in cost_grads]
nnet.W1 -= np.mean(gW1, axis=0)/2 * learning_rate
nnet.b1 -= np.mean(gb1, axis=0)/2 * learning_rate
nnet.W2 -= np.mean(gW2, axis=0).T/2 * learning_rate
nnet.b2 -= np.mean(gb2, axis=0)/2 * learning_rate
iter += 1
为什么成本在某一点之后没有改善?此外,任何其他技巧也受到高度赞赏。
生成的玩具数据集如下所示:
最佳答案
您的目标似乎是预测数据属于哪个类{0,1,2}。
网络的输出是一个S型信号([0,1]中的sigm(x)),
使用均方误差(MSE)进行训练时,模型无法预测大于1的值。因此,如果预测的类为2,则总是错误的。
成本可能趋于平缓,因为您的S形单位饱和(当尝试预测2时)并且S形饱和的梯度为0
对于分类,神经网络通常以softmax层结尾,
使用cross-entropy进行培训。
如果要继续使用MSE和Sigmoids单位进行分类,则应考虑以One-vs-(One/All)某种方式一次仅预测两个类别。
无论如何,如果仅通过将输出舍入为0或1来进行双类别分类,则它似乎可以工作。成本在降低,准确性在提高(quickly modified code):
关于python - 为什么MLP的成本函数趋于平坦?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45248198/