我是 keras 新手,我正在尝试构建自己的神经网络。
任务:
我需要编写一个可以为角色做出决定的系统,该角色可能会遇到一个或多个敌人。系统可知:
- 健康状况百分比
- 存在手枪;
- 敌人的数量。
答案必须采用以下形式之一:
- 攻击
- 运行
- 隐藏(进行突然袭击)
- 什么也不做
为了训练,我制作了一张“类(class)”表:
这是我的代码:
# 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,损失在减少。 这是不对的。
我试图将学习率除以 10,更改激活和优化器。即使是我手动输入的数据。 谁能告诉我如何解决我的简单问题。谢谢。
最佳答案
您的代码中有几个问题。
- 与神经网络模型相比,数据条目数量非常少。
- Y 表示为类数而不是类向量。可以在此基础上学习回归模型,但这是一个糟糕的设计选择。
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
激活,因为这些类是互斥的
关于neural-network - 如何在keras上构建简单的神经网络(不是图像识别),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41596619/