亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

具有稀疏數據的張量流訓練

具有稀疏數據的張量流訓練

小怪獸愛吃肉 2022-10-06 20:18:40
我想在 python 的 tensorflow 中使用稀疏張量進行訓練。我發現了很多代碼如何做到這一點,但沒有一個有效。這是一個示例代碼來說明我的意思,它會引發錯誤:import numpy as npx_vals = tf.sparse.SparseTensor([[0, 0], [0, 1], [1, 2]], [1, 2, 1], [2, 3])#x_vals = tf.sparse.to_dense(x_vals)    #this line decides, if there is an errory_vals = np.array([0, 1])layer_args = lambda : Nonelayer_args.input_shape = (3,)layer_args.activation = "sigmoid"layer_args.use_bias = Falsemodel = tf.keras.models.Sequential(tf.keras.layers.Dense(1, **layer_args.__dict__))model.compile(loss = "mse")model.fit(x_vals, y_vals)錯誤是:ValueError: The two structures don't have the same nested structure....和一個巨大的堆棧跟蹤
查看完整描述

1 回答

?
拉丁的傳說

TA貢獻1789條經驗 獲得超8個贊

好的,我知道它是如何工作的。最簡單的解決方案是使用生成器:


from random import shuffle

def data_generator(x_vals, y_vals):

    inds = list(range(x_vals.shape[0]))

    shuffle(inds)

    for ind in inds:

        yield (x_vals[ind, :].todense(), y_vals[ind])

然后使用該生成器生成適合的 x 值:


model.fit(data_generator(x_vals, y_vals))

但是它非常慢。此外,您一次只能訓練一個 epoch,并且 keras 有很多功能您無法使用。也可能是 tensorflow.keras.utils.Sequence:


class SparseSequence(tf.keras.utils.Sequence):

    def __init__(self, x_vals, y_vals, batch_size = 32):

        self.x_vals = x_vals

        self.y_vals = y_vals

        self.inds = list(range(x_vals.shape[0]))

        shuffle(self.inds)

        self.batch_size = batch_size

    def __getitem__(self, item):

        from_ind = self.batch_size * item

        to_ind = self.batch_size * (item + 1)

        return (self.x_vals[self.inds[from_ind:to_ind], :].todense(),

                y_vals[self.inds[from_ind:to_ind]])

    def on_epoch_end(self):

        shuffle(self.inds)

    def __len__(self):

        return math.ceil(self.x_vals.shape[0] / self.batch_size)

然后在擬合函數中使用它:


model.fit(SparseSequence(x_vals, y_vals))

請記住,需要首先將數據轉換為 scipy csr 稀疏矩陣,否則代碼將不起作用。還要記住不要在 Model.fit() 中使用“y”關鍵字。


查看完整回答
反對 回復 2022-10-06
  • 1 回答
  • 0 關注
  • 89 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號