在Tensorflow中查找子矩阵的等级 [英] Find rank of a sub-matrix in Tensorflow

查看:59
本文介绍了在Tensorflow中查找子矩阵的等级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个形状为 [4,4,2,2] 的矩阵 g ,在这里我需要找到 g [0,0]的等级 g [1,1] g [2,2] g [3,3] code> 2x2 矩阵.我使用了 tf.rank 运算符,但将 g 视为单个数组并计算等级并为整个矩阵返回单个值.我需要的是相应的 g [i,j] 的等级的 2x2 矩阵.以下是MWE:

I have a matrix g of shape [4, 4, 2, 2] where I need to find the rank of g[0, 0], g[1, 1], g[2, 2] and g[3, 3] which are all 2x2 matrices. I used the tf.rank operator but it treats g as a single array and computes the rank and returns a single value for the whole matrix. What I need is a 2x2 matrix of ranks of the corresponding g[i, j]'s. Following is a MWE:

import tensorflow as tf
import numpy as np

a = np.array([
 [[[ 0., 0.], [ 0., 0.]], [[-1., -1.], [-1., -1.]], [[-2., -2.], [-2., -2.]], [[-3., -3.], [-3., -3.]]], 
 [[[ 1., 1.], [ 1., 1.]], [[ 0., 0.], [ 0., 0.]], [[-1., -1.], [-1., -1.]], [[-2., -2.], [-2., -2.]]],
 [[[ 2., 2.], [ 2., 2.]], [[ 1., 1.], [ 1., 1.]], [[ 0., 0.], [ 0., 0.]], [[-1., -1.], [-1., -1.]]],
 [[[ 3., 3.], [ 3., 3.]], [[ 2., 2.], [ 2., 2.]], [[ 1., 1.], [ 1., 1.]], [[ 0., 0.], [ 0., 0.]]]
])
rank = tf.rank(a)  # Returns a number

除了使用 for 循环之外,还有什么方法可以获取此排名矩阵?谢谢.

Apart from using a for loop is there any way to get this rank matrix? Thanks.

推荐答案

我认为TensorFlow中没有任何函数可以计算矩阵等级.一种可能性是使用 tf.linalg.svd 并计算非零奇异值的数量:

I don't think there is any function to compute matrix rank in TensorFlow. One possibility is to use tf.linalg.svd and count the number of nonzero singular values:

import tensorflow as tf

EPS = 1e-6
a = tf.ones((4, 4, 2, 2), tf.float32)
s = tf.linalg.svd(a, full_matrices=False, compute_uv=False)
r = tf.math.count_nonzero(tf.abs(s) > EPS, axis=-1)
print(r.numpy())
# [[1 1 1 1]
#  [1 1 1 1]
#  [1 1 1 1]
#  [1 1 1 1]]

这篇关于在Tensorflow中查找子矩阵的等级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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