如何在keras上建立简单的神经网络(不是图像识别)

How to build simple neural network on keras (not image recognition)

我是 keras 的新手,我正在尝试构建自己的神经网络。

一个任务:

我需要编写一个系统,可以为可能遇到一个或多个敌人的角色做出决定。系统可知:

答案必须采用以下形式之一:

  1. 攻击
  2. 运行
  3. 隐藏(突然袭击)
  4. 什么都不做

为了训练我做了一个 table of "lessons":

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]

每个epoch的准确率是0.2727,loss在减少。 不对。

我试图将学习率除以 10,改变激活和优化器。甚至我手动输入的数据。 谁能告诉我如何解决我的简单问题。谢谢

你的代码有几个问题。

  1. 与 NN 模型相比,数据条目的数量非常少。
  2. Y 表示为 classes 数字而不是 class 向量。可以在此基础上学习回归模型,但这是一个糟糕的设计选择。
  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 激活,因为 classes 是互斥的