2017-01-11 42 views
2

我是keras的新手,我尝试构建自己的神经网络。如何在keras上构建简单的神经网络(不是图像识别)

任务:

我需要写一个系统,可以使人物,这可能满足一个或多个敌人的决定。该系统可以知道:

  • 百分比卫生字符
  • 手枪的存在;
  • 敌人的数量。

答案必须是下列之一形式:

  1. 攻击
  2. 运行
  3. 隐藏(用于偷袭)
  4. 什么也不做

为了培养起来,我做了一个“课程”的表格:

https://i.stack.imgur.com/lD0WX.png

因此,这里是我的代码:

# Create first network with Keras 
from keras.models import Sequential 
from keras.layers import Dense 
from keras.optimizers import SGD 
import numpy 
# fix random seed for reproducibility 
seed = 7 
numpy.random.seed(seed) 
# split into input (X) and output (Y) variables 
X = numpy.array([[0.5,1,1], [0.9,1,2], [0.8,0,1], [0.3,1,1], [0.6,1,2], [0.4,0,1], [0.9,1,7], [0.5,1,4], [0.1,0,1], [0.6,1,0], [1,0,0]]) 
Y = numpy.array([[1],[1],[1],[2],[2],[2],[3],[3],[3],[4],[4]]) 
# create model 
model = Sequential() 
model.add(Dense(3, input_dim=3, init='uniform', activation='relu')) 
model.add(Dense(1, init='uniform', activation='sigmoid')) 
# Compile model 
sgd = SGD(lr=0.001) 
model.compile(loss='binary_crossentropy', optimizer=sgd, metrics=['accuracy']) 

# Fit the model 
model.fit(X, Y, nb_epoch=150) 
# calculate predictions 
predictions = model.predict(X) 
# round predictions 
rounded = [round(x) for x in predictions] 
print(rounded) 

在这里,我的预测得到。 [1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0,1.0]

每个时期的准确度是0.2727,损失是减少的。 这是不对的。

我试图把学习速度除以10,改变激活和优化。即使我手动输入数据。 任何人都可以告诉我如何解决我的简单问题。谢谢。

回答

2

你的代码有几个问题。

  1. 与NN模型相比,数据条目的数量非常少。
  2. Y表示为类编号而不是类矢量。回归模型可以从中学习,但它是一个糟糕的设计选择。
  3. softmax函数的输出总是在0-1之间..因为这是用来模型只知道在0-1之间的值。

这里下面是一个好一点修改后的代码:

from keras.models import Sequential 
from keras.layers import Dense 
from keras.optimizers import SGD 
import numpy 
# fix random seed for reproducibility 
seed = 7 
numpy.random.seed(seed) 
# split into input (X) and output (Y) variables 
X = numpy.array([[0.5,1,1], [0.9,1,2], [0.8,0,1], [0.3,1,1], [0.6,1,2], [0.4,0,1], [0.9,1,7], [0.5,1,4], [0.1,0,1], [0.6,1,0], [1,0,0]]) 
y = numpy.array([[1],[1],[1],[2],[2],[2],[3],[3],[3],[0],[0]]) 

from keras.utils import np_utils 
Y = np_utils.to_categorical(y, 4) 
# print Y 

# create model 
model = Sequential() 
model.add(Dense(3, input_dim=3, activation='relu')) 
model.add(Dense(4, activation='softmax')) 
# Compile model 
# sgd = SGD(lr=0.1) 
# model.compile(loss='categorical_crossentropy', optimizer=sgd, metrics=['accuracy']) 
model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy']) 

# Fit the model 
model.fit(X, Y, nb_epoch=700) 

# calculate predictions 
predictions = model.predict(X) 

predictions_class = predictions.argmax(axis=-1) 
print(predictions_class) 

注我已经使用了softmax活化的类是相互排斥的