轉換張量的最簡單解決方案是什么:
tensor = tf.constant([4.0])
到 5x5 張量,其中主對角線和對角線的標量是 4.0,但張量的其余部分的值為 0.0,如下所示:
tf.Tensor(
[[4. 0. 0. 0. 4.]
[0. 4. 0. 4. 0.]
[0. 0. 4. 0. 0.]
[0. 4. 0. 4. 0.]
[4. 0. 0. 0. 4.]], shape=(5, 5), dtype=float32)
uj5u.com熱心網友回復:
這是您可以執行此操作的一種方法:
def diag_antidiag(shape):
"""Create an diag and anti-diagonal tensor of ones given `shape`
Examples
--------
>>> diag_antidiag(5)
(<tf.Tensor: shape=(5, 5), dtype=int32, numpy=
array([[1, 0, 0, 0, 0],
[0, 1, 0, 0, 0],
[0, 0, 1, 0, 0],
[0, 0, 0, 1, 0],
[0, 0, 0, 0, 1]], dtype=int32)>,
<tf.Tensor: shape=(5, 5), dtype=int32, numpy=
array([[0, 0, 0, 0, 1],
[0, 0, 0, 1, 0],
[0, 0, 1, 0, 0],
[0, 1, 0, 0, 0],
[1, 0, 0, 0, 0]], dtype=int32)>)
"""
diag = tf.linalg.tensor_diag([1] * shape)
anti = diag[:, ::-1]
return diag, anti
# create the initial diags
shape = 5
diag, anti = diag_antidiag(shape)
# cast as bool tensors
diag = tf.cast(diag, tf.bool)
anti = tf.cast(anti, tf.bool)
# overlay bool masks
overlay = tf.cast(tf.logical_or(diag, anti), tf.float32)
fours = overlay * 4
# <tf.Tensor: shape=(5, 5), dtype=float32, numpy=
# array([[4., 0., 0., 0., 4.],
# [0., 4., 0., 4., 0.],
# [0., 0., 4., 0., 0.],
# [0., 4., 0., 4., 0.],
# [4., 0., 0., 0., 4.]], dtype=float32)>
這會沿著 diags 創建兩個 bool 張量,將它們疊加起來,然后用 4s 填充它們。
uj5u.com熱心網友回復:
只需使用tf.eye:
import tensorflow as tf
tensor = tf.where(tf.greater(tf.reverse(tf.eye(5), axis=[1]) tf.eye(5), 0.0), 1.0, 0.0) * tf.constant([4.0])
tf.Tensor(
[[4. 0. 0. 0. 4.]
[0. 4. 0. 4. 0.]
[0. 0. 4. 0. 0.]
[0. 4. 0. 4. 0.]
[4. 0. 0. 0. 4.]], shape=(5, 5), dtype=float32)
uj5u.com熱心網友回復:
一個簡化版的 AloneTogether 的答案
tf.cast(tf.logical_or(tf.reverse(tf.eye(5, dtype=tf.bool), axis=[1]), tf.eye(5, dtype=tf.bool)), dtype=tf.float32) * 4.0
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/388267.html
下一篇:TypeError:unhashabletype:'numpy.ndarray'Python3.9影像分類使用tensorflow和keras
