Theano输入和输出样本号错误

时间:2016-02-01 23:58:55

标签: python neural-network theano keras

我正在研究一些项目,我需要在python中使用神经网络。我正在尝试训练神经网络,但我总是得到FIT()函数的错误。这是我的代码:

def matrix_to_vector(m):
    return m.flatten()


def prepare_for_rnn(tones):
    ready_for_rnn = []
    for tone in tones:
        ready_for_rnn.append(matrix_to_vector(tone))

    return ready_for_rnn

def convert_output2(outputs):
    return np.eye(len(outputs))

tone = LoadDataSet('samples/ddur.wav')

X_train = []
X_train.append(tone.DataSet)


x_train = prepare_for_rnn(X_train)
tones = ['D']
y_train = convert_output2(tones)

model = Sequential()

model.add(Dense(128, input_dim=1, activation='sigmoid'))
model.add(Dense(1, activation='sigmoid'))

sgd = SGD(lr=0.01, momentum=0.9)
model.compile(loss='mean_squared_error', optimizer=sgd)

y_train = np.array(y_train)

print x_train
print y_train
print y_train.shape
print len(y_train)

model.fit(x_train, y_train, nb_epoch=2000, batch_size=1, verbose=0, shuffle=False, show_accuracy=False)
score = model.evaluate(x_train, y_train, batch_size=16)

我收到的错误是我的输入数组和输出数组没有相同的样本数。

我的控制台输出:

/usr/bin/python2.7 /home/misel/PycharmProjects/SoftProjekat/main.py
Using Theano backend.
[array([ 0.70347332,  0.72311571,  2.64259667, ...,  0.52694423,
        0.21127148,  0.43055696])]
[[ 1.]]
(1, 1)
1
Traceback (most recent call last):
  File "/home/misel/PycharmProjects/SoftProjekat/main.py", line 103, in <module>
    model.fit(x_train, y_train, nb_epoch=2000, batch_size=1, verbose=0, shuffle=False, show_accuracy=False)
  File "/usr/local/lib/python2.7/dist-packages/keras/models.py", line 503, in fit
    raise Exception('All input arrays and the target array must '
Exception: All input arrays and the target array must have the same number of samples.

1 个答案:

答案 0 :(得分:1)

当我遇到此问题时,我正在实现Autoencoders&#34;异常:所有输入数组和目标数组必须具有相同数量的样本。&#34;。 model.fit期望numpy数组作为输入。

X: data, as a numpy array.
y: labels, as a numpy array.

将列表转换为numpy数组解决了我的问题。

如果我们看到model.fit的文档,它会说:

if type(X) == list:
            if len(set([len(a) for a in X] + [len(y)])) != 1:
                raise Exception('All input arrays and the target array must ''have the same number of samples.')

所以如果X是类型列表:列表X中所有项目的长度和列表y的长度应该相同,否则将引发异常。

相关问题