給定一個整數k和一個對稱矩陣A(如tf.Variable),如何計算k的次冪A
tf.matmul(A, tf.matmul(A, tf.matmul(A, ...)... )
最有效地TensorFlow?
uj5u.com熱心網友回復:
使用tf.while應該非常有效:
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)>
uj5u.com熱心網友回復:
這可能是解決這個問題的一種方法。
一世。將矩陣 A 轉換為 numpy ndarray(假設為 B)
ii. 使用以下方法計算 B 的 k 次冪:np.linalg.matrix_power(B, k)
iii。將結果轉換回 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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/393778.html
