0
我試圖教我的多層神經網絡XOR函數。我有一個架構網絡[2,2,1]。我將損失定義爲平方誤差的總和(我知道這並不理想,但我需要這樣)。如果我將所有圖層的激活函數設置爲sigmoid函數,我總會陷入局部最優(0.25左右,所有輸出大約爲0.5)。如果我將隱藏層的激活函數更改爲ReLU,我有時會陷入相同的最佳狀態,但有時我會解決它。難道這是因爲我使用均方誤差而不是交叉熵?以防萬一,這是我的神經網絡代碼:教完全連接的前饋神經網絡XOR函數
import tensorflow as tf
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.5)
return tf.Variable(initial)
def bias_variable(shape):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial)
class FCLayer():
def __init__(self, inputs, outputs, activation):
self.W = weight_variable([inputs, outputs])
self.b = bias_variable([outputs])
self.activation = activation
def forward(self, X):
s = tf.matmul(X, self.W) + self.b
return self.activation(s)
class Network:
def __init__(self, architecture, activations=None):
self.layers = []
for i in range(len(architecture)-1):
self.layers.append(FCLayer(architecture[i], architecture[i+1],
tf.nn.sigmoid if activations==None else activations[i]))
self.x = tf.placeholder(tf.float32, shape=[None, architecture[0]])
self.out = self.x
for l in self.layers:
self.out = l.forward(self.out)
self.session = tf.Session();
self.session.run(tf.initialize_all_variables())
def train(self, X, Y_, lr, niter):
y = tf.placeholder(tf.float32, shape=[None, Y_.shape[1]])
loss = tf.reduce_mean((self.out - y)**2)
#loss = tf.reduce_sum(tf.nn.sigmoid_cross_entropy_with_logits(self.out, y))
train_step = tf.train.GradientDescentOptimizer(lr).minimize(loss)
errs = [];
for i in range(niter):
train_step.run(feed_dict={self.x: X, y: Y_},session=self.session)
errs.append(loss.eval(feed_dict={self.x: X, y: Y_},session=self.session))
return errs;
def predict(self, X):
return self.out.eval(feed_dict={self.x: X}, session = self.session)
更新:我嘗試了更復雜的架構([2,2,2,1]),但仍然沒有成功。