簡體   English   中英

將張量作為輸入傳遞給 Keras api 功能模型

[英]passing Tensor as input to Keras api functional model

我有一個 api 功能模型,它可以很好地將 numpy 數組作為輸入。 我的模型的簡化版本如下。

inputLayerU = Input(shape=(10,))
denseLayerU = Dense(10, activation='relu')(inputLayerU)

inputLayerM = Input(shape=(10,))    
denseLayerM = Dense(10, activation='relu')(inputLayerM)

concatLayerUM = concatenate([denseLayerU, denseLayerM], axis = 1)
outputLayer = Dense(1,activation='linear')(concatLayerUM)

model = Model(inputs=[inputLayerUM, inputLayerMU], outputs=outputLayer)

model.fit_generator(dataGenerator(train, matA, matB, matC, batchSize,1),
    epochs=3,
    steps_per_epoch=10)

我使用了一個不適合我的記憶的非常大的數據集,所以我使用了一個如下的生成器:

def dataGenerator(data, matA, matB, matC, batchSize):

    sampleIndex = range(len(data))    
    batchNumber = int(len(data)/batchSize)  #count of batches

    counter=0
    while 1:
        U = np.zeros((batchSize,N))
        M = np.zeros((batchSize,N))
        outY = np.zeros((batchSize))

        for i in range(0,batchSize):
            ind = sampleIndex[i+counter*batchSize]
            U[i,:] = matA[ind,:]
            M[i,:] = matB[ind,:]
            outY[i] = data.iloc[ind]['y']

        matU = np.dot(U,matC)            
        matM = np.dot(M,matC)

        yield ([matU, matM], outY)

        #increase counter and restart it to yeild data in the next epoch as well
        counter += 1    
        if counter >= batchNumber:
            counter = 0  

如您所見,我在dataGenerator函數中使用了兩個二維數組的dot積。 我在 GPU 上運行我的代碼並使其更快,我想用matmaul替換點積,它以張量格式提供相同的結果。 所以它會是這樣的:

matU = tf.matmul(U,matB)        
matM = tf.matmul(M,matB)

但是,它提供了此錯誤:

InvalidArgumentError: Requested tensor connection from unknown node: "input_4:0".

input_4:0是模型中的第一個inputLayerU節點。 所以似乎我無法將張量傳遞給 InputLayer。 那我應該怎么通過呢?

另外,我嘗試將張量 matU 和 matM 轉換為 numpy 數組,然后再將它們傳遞給輸入層

matU = tf.Session().run(tf.matmul(U,matB))       
matM = tf.Session().run(tf.matmul(M,matB))

但它比最初使用點積慢 10 倍。

我檢查了這篇文章,但是,它是針對順序模型的,在開始訓練模型之前我沒有張量。

您可以將 U 和 M 作為輸入傳遞,然后在模型中應用 Lambda:

Lambda(lambda x: tf.matmul(x, tf.constant(constant_matrix)))

假設constant_matrix是模型中的常數。

使用函數式 API:

import numpy as np
from tensorflow import keras
from tensorflow.keras.layers import *
from tensorflow.keras.models import Model
from tensorflow.keras import backend as K

const_matrix = np.random.rand(10, 20)

def apply_const_matrix(x):
  """
      x: shape=(batch_size, input_dims)
      const_matrix: shape=(input_dims, output_dims)
      output: (batch_size, output_dims)
  """
  return K.dot(x, K.constant(const_matrix))

def make_model():
  inp_M = Input(shape=(10,))
  inp_U = Input(shape=(10,))
  Mp = Lambda(apply_const_matrix)(inp_M)
  Up = Lambda(apply_const_matrix)(inp_U)
  join = Concatenate(axis=1)([Mp, Up])
  h1 = Dense(32, activation='relu')(join)
  out = Dense(1, activation='sigmoid')(h1)
  model = Model([inp_M, inp_U], out)
  model.compile('adam', 'mse')
  return model

model = make_model()
model.summary()

這里的假設是在 matmul 運算之前模型的輸入是 M、U 向量,並且變換是使用常數矩陣進行的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM