在Tensorflow中使用稀疏输入(Sparse Input)的Keras

5

我正在尝试使用稀疏的numpy矩阵在tensorflow作为后端的keras中。模型编译时没有问题,但是在拟合时却出现了错误。代码如下。任何帮助都将不胜感激。

from keras.layers import Dense, Input
from keras.models import Model
inputs = Input(shape=(trainX.shape[1],), sparse=True)
outputs = Dense(trainY.shape[1], activation='softmax')(inputs)
model = Model(inputs=inputs, outputs=outputs)
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

trainX是

<2404941x337071 sparse matrix of type '<type 'numpy.float64'>'
with 4765705 stored elements in Compressed Sparse Row format>

同样地,trainY是一个CSR矩阵。

model.fit(trainX, trainY, verbose=1)

出现以下错误:

ValueError: setting an array element with a sequence.

1
如果文档(例如 fit)没有说明参数可以是稀疏矩阵,则不行。通常,如果输入不是数组,则代码会将其包装在 np.asarray(trainX) 中。如果输入是稀疏的,则结果是一个元素为1的对象数组,这不是您想要的。 - hpaulj
是的,我也是这么想的。但是为什么他们会有一个稀疏选项呢?在这里https://github.com/fchollet/keras/issues/4984,一些人声称已经解决了这个问题@hpaulj - TheRajVJain
在这里也有:https://rstudio-pubs-static.s3.amazonaws.com/260770_e9f31a39cea94ff1b5616fe8b6b4ff28.html#18 - TheRajVJain
1
我认为对于稀疏张量,使用自定义批处理生成器将仅将张量的一部分转换回其密集形式。参考:https://dev59.com/IloU5IYBdhLWcg3wTVoe - Sussch
1个回答

2

如果您编写自定义训练循环,可以将稀疏矩阵用作Keras模型的输入。

在下面的示例中,该模型以稀疏矩阵作为输入,并输出一个密集矩阵。

"Original Answer"翻译成中文是"最初的回答"。

from keras.layers import Dense, Input
from keras.models import Model
import scipy
import numpy as np

trainX = scipy.sparse.random(1024, 1024)
trainY = np.random.rand(1024, 1024)

inputs = Input(shape=(trainX.shape[1],), sparse=True)
outputs = Dense(trainY.shape[1], activation='softmax')(inputs)
model = Model(inputs=inputs, outputs=outputs)
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])

steps = 10
for i in range(steps):
  # For simplicity, we directly use trainX and trainY in this example
  # Usually, this is where batches are prepared
  print(model.train_on_batch(trainX, trainY))
# [3549.2546, 0.0]
# ...
# [3545.6448, 0.0009765625]

从您的示例中,似乎您希望输出也是一个稀疏矩阵。这更加困难,因为您的模型需要输出一个稀疏矩阵,并且您的损失函数必须能够计算稀疏矩阵。此外,我认为Keras目前还不支持稀疏输出。"最初的回答"。

我遇到了这个错误 -> 尝试将一个不支持的类型 (<class 'scipy.sparse.coo.coo_matrix'>) 转换为张量,该值为 (<1024x1024 sparse matrix of type '<class 'numpy.float64'>' with 10485 stored elements in COOrdinate format>)。 - Areza

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接