【问题标题】:Use sparse Input in Keras with Tensorflow在 Keras 和 Tensorflow 中使用稀疏输入
【发布时间】:2018-03-16 16:35:44
【问题描述】:

我正在尝试将稀疏 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.

【问题讨论】:

标签: numpy tensorflow keras


【解决方案1】:

如果您编写自定义训练循环,则可以使用稀疏矩阵作为 Keras 模型的输入。 在下面的例子中,模型以一个稀疏矩阵作为输入,输出一个密集矩阵。

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 还不支持稀疏输出。

【讨论】:

  • 我收到此错误 -> 尝试使用不受支持的类型( ) 到张量。
猜你喜欢
  • 2017-05-23
  • 1970-01-01
  • 1970-01-01
  • 2019-04-11
  • 1970-01-01
  • 2021-04-19
  • 2022-10-15
  • 1970-01-01
  • 2020-03-14
相关资源
最近更新 更多