python - 我们应该如何对全序列进行分类?

标签 python machine-learning classification keras lstm

我想将完整序列分为两类。我在网上搜索了很多,但没有找到任何结果。我首选的方法是使用 keras 的 LSTM 模型将“完整”序列的可变行分为两类。这种方法的问题是 Xy 的形状不同。这是我为解释我的问题而编写的示例代码。

import numpy as np
from keras.layers import Dense,LSTM
from keras.models import Sequential

#(no of samples, no of rows,step, feature)
feat= np.random.randint(0, 100, (150, 250, 25,10))

#(no of samples, binary_output)
target= np.random.randint(0, 2, (150, 1))

#model
model = Sequential()
model.add(LSTM(10, input_shape=(25, 10), return_sequences=True))
model.add(LSTM(10,return_sequences=False))
model.add(Dense(1, activation='softmax'))
model.compile(loss='binary_crossentropy', optimizer='rmsprop')
print model.summary()

for i in xrange(target.shape[0]):
    X=feat[i]
    y=target[i]
    model.fit(X,y)

这里我有 150 个样本序列,我想将其分类为 01。问题是这个

ValueError: Input arrays should have the same number of samples as target arrays. Found 250 input samples and 1 target samples.

如果无法在深度学习方法中实现这一点,您能否推荐任何其他机器学习算法?

编辑

很多人对此提出疑问

#(no of samples, no of rows,step, feature)
feat= np.random.randint(0, 100, (150, 250, 25,10))

150 是样本数(将其视为 150 个时间序列数据)。 250 and 10是一个250行10列的时间序列数据。 (250, 25,10) 是 25 个时间步长的补充,这样它就可以传递给 keras lstm 输入

最佳答案

问题是当你这样做的时候

X=feat[i]
y=target[i]

这会删除第一个轴,从而导致 X.shape = (250, 25, 10)y.shape == (1,)。当您调用 model.fit(X, y) 时,keras 会假设 X 有 250 个样本,而 y 只有一个样本。这就是您收到该错误的原因。

您可以通过提取 feattarget 的切片来解决这个问题,例如调用

X=feat[i:i+batch_size]
y=target[i:i+batch_size]

batch_size 是每次迭代要使用的样本数。如果您设置 batch_size = 1,您应该在代码中获得预期的行为。

关于python - 我们应该如何对全序列进行分类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45031090/

相关文章:

python - 如何在python中批量加载数据到hbase

python - Python 中的线性代数 : Calculating Eigenvectors for 3x3 Matrix

python - 具有大值的 numpy linalg.lstsq

java - 如何在 apache spark 中执行词干提取?

machine-learning - 导入错误: cannot import name JSONClient

python - 神经网络的输入形状

python - 在Scrapy中,如何使用嵌套项目加载器而无需进一步调用 'add_xpath'

javascript - 如何使用 Brain.js 查找模式

python - scikit 管道 python 中的多个分类模型

python - 使用经过训练的 ConvNet 的参数预测图像类别