Keras中的输入塑造与模型训练

2024-09-25 10:30:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道目前有一些讨论这个话题的好帖子(this one非常好,非常详细),但经过2个小时的努力,我仍然有一些问题:

只是为了有一些背景:我正在获取一些wav文件的频谱图(16khz,3秒除以20ms)并将它们输入神经网络,以确定它们是否包含一个具体的单词(考虑到0到1的确定范围)。你知道吗

def obtain_sample(wav):
    sample_rate, samples = wavfile.read(wav)
    frequencies, times, spectrogram = signal.spectrogram(samples, sample_rate, nperseg=320, noverlap=16)
    dBS = 10 * np.log10(spectrogram)  # convert to dB

    return dBS

def create_model():
    print("Creating Model...")
    model= Sequential()
    model.add(Dense(10,input_shape=(161,157)))
    model.add(Activation('sigmoid'))

    model.compile(optimizer='rmsprop',
                  loss='binary_crossentropy',
                  metrics=['accuracy'])

    com1=obtain_sample("comando.wav")
    com2=obtain_sample("comando2.wav")
    nocom=obtain_sample("nocomando.wav")
    inputs=np.array([com1,com2,nocom])
    results=np.array([[1.],[1.],[0.]])
    model.fit(inputs,results,epochs=10,)
    #model.fit(com1,[1.],epochs=10)
    #model.fit(com2,[1.],epochs=10)
    #model.fit(nocom,[0.],epochs=10)

    model.save("modelo_comando")
    print("Model saved")

我实际上得到了以下错误:

ValueError('Error when checking target: expected activation_1 to have 3 dimensions, but got array with shape (3, 1)',)

在检查局部var值时,我花了将近一个小时试图更好地解释这个问题,我想我更愿意问,我是否真的给出了正确的输入形状,以及如何使用展平/重塑层来获得每个样本的单个值输出?你知道吗

很抱歉不能更具体


Tags: samplemodelratedefnparrayfitepochs
1条回答
网友
1楼 · 发布于 2024-09-25 10:30:57

在稠密层之后添加一个展平层,在展平层之后添加一个稠密层,其中单位数应等于预期输出的形状。在这种情况下,我们期望一个值。因此Dense(1)

inputs = np.random.rand(3,161,157)
model= Sequential()
model.add(Dense(10,input_shape=(161,157)))
model.add(Flatten())
model.add(Dense(1))
model.add(Activation('sigmoid'))

model.compile(optimizer='rmsprop',
              loss='binary_crossentropy',
              metrics=['accuracy'])
model.summary()
results=np.array([[1.],[1.],[0.]])
model.fit(inputs,results,epochs=10)

我运行了上面的代码,没有任何问题。请检查一下这个

在模型上预测时

# Since i don't have the original data, i am creating some random values
test = np.random.rand(161,157)
test = np.expand_dims(test,axis=0)
model.predict(test)

相关问题 更多 >