![](/img/trans.png)
[英]How do I make a hollow symmetric matrix with zeros in the main diagonal, ones elsewhere in numpy
[英]How to pad multiple tensors with one on main diagonal and zeros elsewhere?
我將R
作為形狀為(N,2,2)
2D旋轉矩陣。 現在,我希望將每個矩陣擴展到(3,3)
3D旋轉矩陣,即在每個[:,:2,:2]
放入零,並在[:,2,2]
放入1
。
如何在張量流中做到這一點?
UPDATE
我這樣嘗試
R = tf.get_variable(name='R', shape=np.shape(R_value), dtype=tf.float64,
initializer=tf.constant_initializer(R_value))
eye = tf.eye(np.shape(R_value)[1]+1)
right_column = eye[:2,2]
bottom_row = eye[2,:]
R = tf.concat([R, right_column], 3)
R = tf.concat([R, bottom_row], 2)
但失敗了,因為concat
不進行廣播...
更新2
我進行了明確的廣播,還修復了concat
調用中的錯誤索引:
R = tf.get_variable(name='R', shape=np.shape(R_value), dtype=tf.float64,
initializer=tf.constant_initializer(R_value))
eye = tf.eye(np.shape(R_value)[1]+1, dtype=tf.float64)
right_column = eye[:2,2]
right_column = tf.expand_dims(right_column, 0)
right_column = tf.expand_dims(right_column, 2)
right_column = tf.tile(right_column, (np.shape(R_value)[0], 1, 1))
bottom_row = eye[2,:]
bottom_row = tf.expand_dims(bottom_row, 0)
bottom_row = tf.expand_dims(bottom_row, 0)
bottom_row = tf.tile(bottom_row, (np.shape(R_value)[0], 1, 1))
R = tf.concat([R, right_column], 2)
R = tf.concat([R, bottom_row], 1)
解決方案看起來相當復雜。 有更簡單的嗎?
padded = tf.pad(R, [[0, 0], [0, 1], [0, 1]])
第一個填充零至[N, 2, 2]
為[N, 3, 3]
padded = tf.pad(R, [[0, 0], [0, 1], [0, 1]])
然后將padded[N, 2, 2]
為1:
由於tf.Tensor
不支持分配,因此可以初始化np.array
,然后將它們添加在一起。
arr = np.zeros((3, 3))
arr[2, 2] = 1
R = padded + arr # broadcast used here
現在變量R
是您需要的
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.