繁体   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