python – 神经网络训练平稳的梯度下降
作者:互联网
我一直在尝试在python中实现一个基本的back-propogation神经网络,并完成了初始化和训练权重集的编程.然而,在我训练的所有集合上,误差(均方)总是收敛到一个奇怪的数字 – 错误总是在进一步的迭代中减少,但从未真正接近零.
任何帮助将非常感激.
import csv
import numpy as np
class NeuralNetwork:
layers = 0
shape = None
weights = []
layerIn = []
layerOut = []
def __init__(self, shape):
self.shape = shape
self.layers = len(shape) - 1
for i in range(0,self.layers):
n = shape[i]
m = shape[i+1]
self.weights.append(np.random.normal(scale=0.2, size = (m,n+1)))
def sgm(self, x):
return 1/(1+np.exp(-x))
def dersgm(self, x):
y = self.sgm(x)
return y*(y-1)
def run(self, input):
self.layerIn = []
self.layerOut = []
for i in range(self.layers):
if i == 0:
layer = self.weights[0].dot(np.vstack((input.transpose(), np.ones([1,input.shape[0]]))))
else:
layer = self.weights[i].dot(np.vstack((self.layerOut[-1], np.ones([1,input.shape[0]]))))
self.layerIn.append(layer)
self.layerOut.append(self.sgm(layer))
return self.layerOut[-1].T
def backpropogate(self, input, y, learning_rate):
deltas = []
y_hat = self.run(input)
#Calculate deltas
for i in reversed(range(self.layers)):
#for last layer
if i == self.layers-1:
error = y_hat - y
msq_error = sum(.5 * ((error) ** 2))
#returns delta, k rows for k inputs, m columns for m nodes
deltas.append(error * self.dersgm(y_hat))
else:
error = deltas[-1].dot(self.weights[i+1][:,:-1])
deltas.append(self.dersgm(self.layerOut[i]).T * error)
#Calculate weight-deltas
wdelta = []
ordered_deltas = list(reversed(deltas)) #reverse order because created backwards
#returns weight deltas, k rows for k nodes, m columns for m next layer nodes
for i in range(self.layers):
if i == 0:
#add bias
input_with_bias = np.vstack((input.T, np.ones(input.shape[0])))
#some over n rows of deltas for n training examples to get one delta for all examples
#for all nodes
wdelta.append(ordered_deltas[i].T.dot(input_with_bias.T))
else:
with_bias = np.vstack((self.layerOut[i-1], np.ones(input.shape[0])))
wdelta.append(ordered_deltas[i].T.dot(with_bias.T))
#update_weights
def update_weights(self, weight_deltas, learning_rate):
for i in range(self.layers):
self.weights[i] = self.weights[i] +\
(learning_rate * weight_deltas[i])
update_weights(self, wdelta, learning_rate)
return msq_error
#end backpropogate
def train(self, input, target, lr, run_iter):
for i in range(run_iter):
if i % 100000 == 0:
print self.backpropogate(input, target, lr)
解决方法:
以下场景中的误差函数不能为0,因为误差函数为0将要求点与曲线完美匹配.
拥有更多神经元肯定会减少误差,因为该功能可以具有更复杂和精确的形状.但是,如果您对数据非常适合,则会出现称为过度拟合的问题,如下图所示.从左到右,曲线要么不适合数据集,要么几乎正确拟合,然后右边的过度拟合.
右边的场景会导致错误为0,但这不是必需的,你想避免这种情况.怎么样?
确定网络中神经元数量是否理想(具有良好拟合)的最简单方法是通过反复试验.将您的数据分成训练数据(80% – 训练网络)和测试数据(20% – 仅保留用于在训练后测试网络).虽然只训练训练数据,但可以在测试数据集上绘制性能.
您还可以使用第3个数据集进行验证,请参阅:
whats is the difference between train, validation and test set, in neural networks?
标签:python,machine-learning,neural-network,numpy,gradient-descent 来源: https://codeday.me/bug/20190628/1317390.html