批量张量的行处理

2024-04-26 05:39:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要分别得到张量每行的外积。代码如下:

input1=K.placeholder(shape=(无,12)) prod=K.map_fn(someMethod,输入1)

someMethod需要执行以下操作:

*def someMethod(x):*
    ## get the outerproduct row-wise of input1 #
    outer=x*x.T
    ## subtract the identity matrix from the outer product #
    diff=outer-np.eye(12) 
    ## and return the trace of the difference matrix #
    trace=np.trace(diff)
    return trace

我希望跟踪值是标量,但prod是批大小的输入列表?我使用plaidml作为后端,因此,希望与numpy或keras后端一起工作,或者可能是tensorflow。在


Tags: ofthe代码returnnptracediffprod
2条回答

下面的示例对形状[None, None](可变批量大小和可变向量维度)的张量x执行请求的操作。它已经在Tensorflow 1.13.1和2.0RC中进行了测试(tf.placeholder必须在2.0中删除)。注释假定输入形状是[None, 12],以便于解释。在

import tensorflow as tf

x = tf.placeholder(tf.float32, shape=[None, None])  # Remove for TF 2.0
# Explicitly perform batch-wise outer product using Einstein summation notation
outer = tf.einsum('bi, bj -> bij', x, x)
outer.shape
# TensorShape([Dimension(None), Dimension(12), Dimension(12)])
diff = outer - tf.eye(tf.shape(x)[1])
trace = tf.linalg.trace(diff)
trace.shape
# TensorShape([Dimension(None)])

如您所见,Tensorflow不需要在输入的批处理维度上映射helper函数。您可以进一步了解tf.einsumhere。在

你好,欢迎使用堆栈溢出。在

对于矩阵A的行外积,使用以下公式:

outer_product = np.matmul(A[:,:,np.newaxis], A[:,np.newaxis,:])

相关问题 更多 >