如何在Keras中实现矩阵乘法? [英] How to implement a matrix multiplication in Keras?

查看:1420
本文介绍了如何在Keras中实现矩阵乘法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想实现一个给定矩阵X返回X的协方差矩阵(X ^ T * X)的函数,这只是一个简单的矩阵乘法.

I just want to implement a function that given a matrix X returns the covariance matrix of X (X^T*X), which is just a simple matrix multiplication.

在Tensorflow中会很容易:tf.matmul(X,tf.transpose(X))

In Tensorflow it's gonna be easy: tf.matmul(X, tf.transpose(X))

但是我没想到这对Keras来说是一场噩梦. Keras中的API(例如乘法和点运算)不适合我的要求.我还尝试了不同的方法(Lambda层并与TF操作混合使用),但仍然失败,并出现了很多错误.

But I didn't expect that it's a nightmare with Keras. The APIs in Keras like multiply and dot don't fit my request. I also tried different ways (Lambda layer and mixed with TF operations) but still failed, occurred lots of errors.

希望有人可以提供帮助.谢谢.

Hope someone may help. Thanks.

推荐答案

实际上,您确实在Keras中有类似之处.尝试dot(x, transpose(x)).

Actually you do have the analogous in Keras. Try dot(x, transpose(x)).

下面是一个比较两个平台的工作示例.

A working example comparing the two platforms follows.

import keras.backend as K
import numpy as np
import tensorflow as tf


def cov_tf(x_val):
    x = tf.constant(x_val)
    cov = tf.matmul(x, tf.transpose(x))
    return cov.eval(session=tf.Session())

def cov_keras(x_val):
    x = K.constant(x_val)
    cov = K.dot(x, K.transpose(x))
    return cov.eval(session=tf.Session())

if __name__ == '__main__':
    x = np.random.rand(4, 5)
    delta = np.abs(cov_tf(x) - cov_keras(x)).max()
    print('Maximum absolute difference:', delta)

打印出最大绝对差,并给我一些1e-7的信息.

The maximum absolute difference is printed and gives me something around 1e-7.

这篇关于如何在Keras中实现矩阵乘法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆