TensorFlow 中的矩阵幂

Matrix Powers in TensorFlow

给定一个整数k和一个对称矩阵A(如tf.Variable),如何计算Ak次方

tf.matmul(A, tf.matmul(A, tf.matmul(A, ...)... )

TensorFlow 中效率最高?

这可能是解决此问题的一种方法。
一世。将矩阵 A 转换为 numpy ndarray(比方说 B)
二.使用 np.linalg.matrix_power(B, k)
计算 B 的 k 次方 三.将结果转换回 tf.Variable

这是上述方法的工作代码

import tensorflow as tf
import numpy as np
k = 2
A = tf.Variable([[1, -3], [2, 5]])
B = A.numpy()
M = np.linalg.matrix_power(B, k)
power = tf.Variable(M)
print(power)

使用tf.while_loop应该是相当有效的:

import tensorflow as tf

k = 3
A = tf.Variable([[1, -3], [2, 5]])
result = tf.Variable(A)

i = tf.constant(0)
c = lambda i: tf.less(i, k - 1)

def body(i):
  result.assign(tf.matmul(A, result))
  return [tf.add(i, 1)]

_ = tf.while_loop(c, body, [i])

print(result)
<tf.Variable 'Variable:0' shape=(2, 2) dtype=int32, numpy= array([[-41, -75], [ 50, 59]], dtype=int32)>