2016-11-12 62 views
0

我是新来的深度学习,我试图实现NOT逻辑keras。但结果不正确。以下是代码。
Keras简单的神经网络NOT逻辑产生错误的输出

from keras.layers import Input, Dense 
from keras.models import Model 
import numpy as np 

inputs = Input(shape=(1,)) 
x = Dense(1024, activation='relu')(inputs) 
x = Dense(2048, activation='relu')(x) 
predictions = Dense(1, activation='softmax')(x) 

model = Model(input=inputs, output=predictions) 
model.compile(optimizer='adam', loss='mean_squared_error', metrics=['accuracy']) 

X = np.array([[0.], [1.]], dtype=np.float32) 
y = np.array([[1.], [0.]], dtype=np.float32) 
print "learning....." 
model.fit(X, y, nb_epoch=100) 
print model.predict(X) 

输出:
在每一个时代的输出是一样的:

Epoch 100/100 
2/2 [==============================] - 0s - loss: 0.5000 - acc: 0.5000 

和预测是:

[[ 1.] 
[ 1.]] 

我不知道是什么这个网络错了。

回答

1

您对损失的使用看起来不正确。 Softmax通常用于多级预测,并且您已经使用Dense(2)将输出设置为由2个值组成。因此,使您的目标成为dim=2的多类目标。

from keras.layers import Input, Dense 
from keras.models import Model 
import numpy as np 

inputs = Input(shape=(1,)) 
x = Dense(1024, activation='relu')(inputs) 
x = Dense(2048, activation='relu')(x) 
predictions = Dense(2, activation='softmax')(x) 

model = Model(input=inputs, output=predictions) 
model.compile(optimizer='adam', loss='mean_squared_error', metrics=['accuracy']) 

X = np.array([[0.], [1.]], dtype=np.float32) 
y = np.array([[1., 0], [0., 1]], dtype=np.float32) 
print "learning....." 
model.fit(X, y, nb_epoch=100) 
print model.predict(X) 

输出

Epoch 100/100 
2/2 [==============================] - 0s - loss: 1.5137e-07 - acc: 1.0000 
[[ 9.99880254e-01 1.19736877e-04] 
[ 5.35955711e-04 9.99464035e-01]] 

编辑:人们可以说如果最终层活化和失功能的上述设置是一个很好的用于二进制分类(可能不是)。 Link

替代使用乙状结肠只有一个目标:

from keras.layers import Input, Dense 
from keras.models import Model 
import numpy as np 

inputs = Input(shape=(1,)) 
x = Dense(1024, activation='relu')(inputs) 
x = Dense(2048, activation='relu')(x) 
predictions = Dense(1, activation='sigmoid')(x) 

model = Model(input=inputs, output=predictions) 
model.compile(optimizer='adam', loss='mean_squared_error', metrics=['accuracy']) 

X = np.array([[0.], [1.]], dtype=np.float32) 
y = np.array([1., 0.], dtype=np.float32) 
print "learning....." 
model.fit(X, y, nb_epoch=100) 
print model.predict(X) 

输出

Epoch 100/100 
2/2 [==============================] - 0s - loss: 9.9477e-07 - acc: 1.0000 
[[ 0.99945992] 
[ 0.00129277]] 
+1

@MrPyCharm不客气。我只是添加了一些编辑,包括您应该阅读的链接。这只是关于第一种情况下的设置的一个小警告(softmax with mse)。 – sascha