我有一個由單個矩陣的下對角線元素組成的陣列。我可以按照如何在 NumPy 中將三角形矩陣轉換為正方形中的方法將其轉換為完整矩陣?. 對于單個矩陣,示例如下所示:
# Create the lower diagonal elements of a 6x6 matrix.
ld = np.arange(21)
# Create full 6x6 matrix
x = np.zeros((6,6))
# Stuff lower triangular values into it
x[np.tril_indices(6)] = ld
# Populate upper triangular elements
x = x x.T
# Fix diagonals (they got doubled)
diag_idx = [0, 2, 5, 9, 14, 20]
np.fill_diagonal(x, ld[diag_idx])
print(x)
我們得到了預期的完整矩陣
[[ 0. 1. 3. 6. 10. 15.]
[ 1. 2. 4. 7. 11. 16.]
[ 3. 4. 5. 8. 12. 17.]
[ 6. 7. 8. 9. 13. 18.]
[10. 11. 12. 13. 14. 19.]
[15. 16. 17. 18. 19. 20.]]
現在我想將其擴展到具有 N 組下對角線元素的陣列,并想要回傳 N 個完整矩陣的陣列。前者有形狀(N, 21),后者有形狀(N, 6, 6)。我將單個矩陣示例擴展為包含 2 個矩陣的示例
# Two sets of lower diagonal elements
ld = np.arange(2*21).reshape(2, 21)
# Two sets of full 6x6 matrices
x = np.zeros((ld.shape[0], 6, 6))
# Find the lower triangular indices of each row and stuff them with the
# values from the corresponding row in the lower diagonal array
x[:, np.tril_indices(6)] = ld[:]
# Populate upper triangular elements
x[:] = x[:] x[:].T
# Fix diagonals (they got doubled)
diag_idx = [0, 2, 5, 9, 14, 20]
np.fill_diagonal(x[:], ld[:][diag_idx])
但我在線上出現形狀不匹配x[:, np.tril_indices(6)] = ld[:]
ValueError: shape mismatch: value array of shape (2,21) could not be broadcast to indexing result of shape (2,2,21,6)
我可以對 N 組較低的對角線值進行正常的 Python 回圈,但我試圖通過 Numpy 來完成這一切。關于我的索引出錯的地方有什么建議嗎?
X 中的期望值為:
[[[ 0. 1. 3. 6. 10. 15.]
[ 1. 2. 4. 7. 11. 16.]
[ 3. 4. 5. 8. 12. 17.]
[ 6. 7. 8. 9. 13. 18.]
[10. 11. 12. 13. 14. 19.]
[15. 16. 17. 18. 19. 20.]],
[[21., 22., 24., 27., 31., 36.],
[22., 23., 25., 28., 32., 37.],
[24., 25., 26., 29., 33., 38.],
[27., 28., 29., 30., 34., 39.],
[31., 32., 33., 34., 35., 40.],
[36., 37., 38., 39., 40., 41.]]]
uj5u.com熱心網友回復:
你可以這樣做,適用于任何N.
import numpy as np
N = 3
ld = np.arange(N*21).reshape(N, 21)
x = np.zeros((ld.shape[0], 6, 6))
tril_ind = np.tril_indices(6)
x[:, tril_ind[0], tril_ind[1]] = ld
x = np.transpose(x, (0, 2, 1))
diag_ind = np.diag_indices(6)
x[:, diag_ind[0], diag_ind[1]] /= 2
print(x)
這列印
[[[ 0. 1. 3. 6. 10. 15.]
[ 1. 2. 4. 7. 11. 16.]
[ 3. 4. 5. 8. 12. 17.]
[ 6. 7. 8. 9. 13. 18.]
[10. 11. 12. 13. 14. 19.]
[15. 16. 17. 18. 19. 20.]]
[[21. 22. 24. 27. 31. 36.]
[22. 23. 25. 28. 32. 37.]
[24. 25. 26. 29. 33. 38.]
[27. 28. 29. 30. 34. 39.]
[31. 32. 33. 34. 35. 40.]
[36. 37. 38. 39. 40. 41.]]
[[42. 43. 45. 48. 52. 57.]
[43. 44. 46. 49. 53. 58.]
[45. 46. 47. 50. 54. 59.]
[48. 49. 50. 51. 55. 60.]
[52. 53. 54. 55. 56. 61.]
[57. 58. 59. 60. 61. 62.]]]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/489404.html
