【问题标题】:Row-wise processing of tensors in a batch批量中按行处理张量
【发布时间】:2019-11-03 19:07:41
【问题描述】:

我需要分别获取张量每一行的外积。代码如下:

input1=K.placeholder(shape=(None, 12)) prod=K.map_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

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

【问题讨论】:

    标签: python numpy tensorflow keras tensor


    【解决方案1】:

    您好,欢迎来到 Stack Overflow。

    对于矩阵 A 的逐行外积,请使用以下代码:

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

    【讨论】:

    • np.matmul 给出了错误,但 A[:,:,np.newaxis]*A[:,np.newaxis,:] 与 tensorflow 后端一起使用,但 PlaidML 在以 None 作为索引进行协商时存在问题尺寸。我正在寻找解决该问题的 ML 实现,因为 tensorflow 执行速度非常慢,而且我没有 Nvidia gpu。
    • 能否在 Colab 上分享您的代码,以便我们一起观察问题?
    • 好的。 Colab link italic bold 我希望代码与 plaidml 后端一起使用。我不知何故让它适用于 tensorflow。
    • 我请求您的许可。
    【解决方案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 不需要在输入的批处理维度上映射辅助函数。你可以了解更多关于tf.einsumhere的信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-21
      • 1970-01-01
      • 1970-01-01
      • 2020-10-14
      • 2019-05-13
      • 2019-08-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多