我试图实现一个前馈神经网络。
这是结构:输入层:8个神经元,隐藏层:8个神经元,输出层:8个神经元。
输入数据是8位的向量(输入层的每个神经元1位)。神经网络的输出也是8位的向量。因此,数据集总共有256个示例。
示例:如果给定x= 0.0,1.0,0.0,0.0,1.0,1.0,0.0,1.0
输出必须为y= 1.0,0.0,0.0,0.0,0.0,1.0,0.0,1.0
具体实现如下:
from keras.models import Sequential
from keras.layers import Dense
import numpy as np
import random
from math import ceil
#Dimension of layers
dim = 8
#Generate dataset
X = []
for i in range(0,2**dim):
n = [float(x) for x in bin(i)[2:]]
X.append([0.]*(dim-len(n))+n)
y = X[:]
random.shuffle(y)
X = np.array(X)
y = np.array(y)
# create model
model = Sequential()
model.add(Dense(dim, input_dim=dim, init='normal', activation='sigmoid'))
model.add(Dense(dim, init='normal', activation='sigmoid'))
model.add(Dense(dim, init='normal', activation='sigmoid'))
# Compile model
model.compile(loss='mse', optimizer='SGD', metrics=['accuracy'])
# Fit the model
model.fit(X, y, nb_epoch=1000, batch_size=50, verbose=0)
# evaluate the model
scores = model.evaluate(X, y)
print("%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))
output = model.predict(X)
#Make the output binary
for i in range(0, output[:,0].size):
for j in range(0, output[0].size):
if output[i][j] > 0.5 or output[i][j] == 0.5:
output[i][j] = 1
else:
output[i][j] = 0
print(output)
这是我在输出中得到的结果:
acc: 50.39%
[[ 1. 0. 0. ..., 0. 1. 1.]
[ 1. 0. 0. ..., 0. 1. 1.]
[ 1. 0. 0. ..., 0. 1. 1.]
...,
[ 1. 0. 0. ..., 0. 1. 1.]
[ 1. 0. 0. ..., 0. 1. 1.]
[ 1. 0. 0. ..., 0. 1. 1.]]
似乎所有的输出都有相同的值。所以我不知道配置出了什么问题。我尝试了这个Cannot train a neural network in keras - stackoverflow,它建议删除输出层的激活函数,但当我运行它时,我得到了具有此值的所有输出向量:
0。1. 1. 1. 1. 1.
有什么关于如何让它工作的见解吗?
发布于 2017-01-19 15:49:58
如果你尝试了上述所有方法,但都不起作用,这意味着你试图拟合噪声,在你的输入和输出之间没有联系/相关性/相关性。
https://stackoverflow.com/questions/39217567
复制相似问题