在 TensorFlow.js 中周期性地分配一个带有自身 sin/cos 的 2d 子集张量
Assign a 2d subset tensor with the sin/cos of itself periodically in TensorFlow.js
如何将下面的Python代码翻译成TensorFlow.js?
# apply sin to even indices in the array; 2i
angle_rads[:, 0::2] = np.sin(angle_rads[:, 0::2])
# apply cos to odd indices in the array; 2i+1
angle_rads[:, 1::2] = np.cos(angle_rads[:, 1::2])
将 sin 应用于偶数索引并将 cos 应用于奇数索引表明我们正在跨列过滤初始张量。要使用 tf.where,第一个维度必须匹配条件大小,这意味着 tf.where 将跨行进行分区。因此需要对初始张量进行转置
const p = t.transpose()
第二步是从初始张量形状的最后一维 t.shape[t.shape.length -1]
创建条件张量 - 它成为置换张量的第一维 p.shape[0]
。
const cond = tf.tensor1d(Array.from({length: p.shape[0]},(_, i) => i%2 === 1), 'bool')
张量是不可变的。无法重新分配给初始张量。当张量值被修改时,一个新的张量被创建。
一切都在一起:
const t = tf.tensor2d([[1, 2, 3, 4], [5, 6, 7, 8]])
p = t.transpose()
const cond = tf.tensor1d(Array.from({length: p.shape[0]},
(_, i) => i%2 === 1), 'bool')
const newp = p.cos().where(cond, p.sin());
const newt = newp.transpose()
newt.print()
如何将下面的Python代码翻译成TensorFlow.js?
# apply sin to even indices in the array; 2i
angle_rads[:, 0::2] = np.sin(angle_rads[:, 0::2])
# apply cos to odd indices in the array; 2i+1
angle_rads[:, 1::2] = np.cos(angle_rads[:, 1::2])
将 sin 应用于偶数索引并将 cos 应用于奇数索引表明我们正在跨列过滤初始张量。要使用 tf.where,第一个维度必须匹配条件大小,这意味着 tf.where 将跨行进行分区。因此需要对初始张量进行转置
const p = t.transpose()
第二步是从初始张量形状的最后一维 t.shape[t.shape.length -1]
创建条件张量 - 它成为置换张量的第一维 p.shape[0]
。
const cond = tf.tensor1d(Array.from({length: p.shape[0]},(_, i) => i%2 === 1), 'bool')
张量是不可变的。无法重新分配给初始张量。当张量值被修改时,一个新的张量被创建。
一切都在一起:
const t = tf.tensor2d([[1, 2, 3, 4], [5, 6, 7, 8]])
p = t.transpose()
const cond = tf.tensor1d(Array.from({length: p.shape[0]},
(_, i) => i%2 === 1), 'bool')
const newp = p.cos().where(cond, p.sin());
const newt = newp.transpose()
newt.print()