Python 在TensorFlow.js中周期性地指定一个2d子集张量及其自身的正弦/余弦
如何将以下Python代码翻译成TensorFlow.jsPython 在TensorFlow.js中周期性地指定一个2d子集张量及其自身的正弦/余弦,python,numpy,tensorflow,tensorflow.js,Python,Numpy,Tensorflow,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应用于奇数索引,表明我
# 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应用于奇数索引,表明我们正在过滤初始张量accross列。要使用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()