Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/294.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 成批处理中张量的行处理_Python_Numpy_Tensorflow_Keras_Tensor - Fatal编程技术网

Python 成批处理中张量的行处理

Python 成批处理中张量的行处理,python,numpy,tensorflow,keras,tensor,Python,Numpy,Tensorflow,Keras,Tensor,我需要分别得到张量每一行的外积。代码如下所示: input1=K.占位符(形状=(无,12)) prod=K.map\u fn(someMethod,input1) someMethod需要执行以下操作: *def someMethod(x):* ## get the outerproduct row-wise of input1 # outer=x*x.T ## subtract the identity matrix from the outer product #

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

input1=K.占位符(形状=(无,12)) prod=K.map\u fn(someMethod,input1)

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
outer_product = np.matmul(A[:,:,np.newaxis], A[:,np.newaxis,:])

我希望跟踪值是标量,但prod是批量大小的输入列表?我正在使用plaidml作为后端,因此,我希望能够使用numpy或keras后端,或者tensorflow。您好,欢迎使用Stack Overflow

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

*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
outer_product = np.matmul(A[:,:,np.newaxis], A[:,np.newaxis,:])

以下示例对形状为
[None,None]
(可变批量大小和可变向量维度)的张量
x
执行请求的操作。它已经在Tensorflow 1.13.1和2.0RC中进行了测试(
tf。对于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不需要在输入的批处理维度上映射辅助函数。您可以了解更多关于
tf.einsum

np.matmul给出了错误,但是A[:,:,np.newaxis]*A[:,np.newaxis,:]与tensorflow后端一起工作,但是PlaidML在与None协商索引大小时遇到问题。我正在寻找解决这个问题的ML实现,因为tensorflow的执行速度非常慢,而且我没有Nvidia gpu。你能在Colab上共享你的代码,这样我们就可以一起观察问题了吗?好的。斜体粗体我希望代码与plaidml后端一起工作。我不知怎的让它为tensorflow工作我请求你的许可。