TensorFlow 操作
- 加
- 減
- 乘
- 除
- 方形
- 重塑形狀
張量加法
您可以使用 tensorA.add(tensorB) 將兩個張量相加
示例
const tensorA = tf.tensor([[1, 2], [3, 4], [5, 6]]);
const tensorB = tf.tensor([[1,-1], [2,-2], [3,-3]]);
// 張量加法
const tensorNew = tensorA.add(tensorB);
// 結果: [ [2, 1], [5, 2], [8, 3] ]
張量減法
您可以使用 tensorA.sub(tensorB) 來減去兩個張量
示例
const tensorA = tf.tensor([[1, 2], [3, 4], [5, 6]]);
const tensorB = tf.tensor([[1,-1], [2,-2], [3,-3]]);
// 張量減法
const tensorNew = tensorA.sub(tensorB);
// 結果: [ [0, 3], [1, 6], [2, 9] ]
張量乘法
您可以使用 tensorA.mul(tensorB) 將兩個張量相乘
示例
const tensorA = tf.tensor([1, 2, 3, 4]);
const tensorB = tf.tensor([4, 4, 2, 2]);
// 張量乘法
const tensorNew = tensorA.mul(tensorB);
// 結果: [ 4, 8, 6, 8 ]
張量除法
您可以使用 tensorA.div(tensorB) 來除以兩個張量
示例
const tensorA = tf.tensor([2, 4, 6, 8]);
const tensorB = tf.tensor([1, 2, 2, 2]);
// 張量除法
const tensorNew = tensorA.div(tensorB);
// 結果: [ 2, 2, 3, 4 ]
張量平方
您可以使用 tensor.square() 來計算張量的平方
示例
const tensorA = tf.tensor([1, 2, 3, 4]);
// 張量平方
const tensorNew = tensorA.square();
// 結果 [ 1, 4, 9, 16 ]
張量重塑
張量中的元素數量是形狀中各尺寸的乘積。
由於具有相同尺寸的形狀可能不同,因此通常需要將張量重塑為具有相同尺寸的其他形狀。
您可以使用 tensor.reshape() 來重塑張量
示例
const tensorA = tf.tensor([[1, 2], [3, 4]]);
const tensorB = tensorA.reshape([4, 1]);
// 結果: [ [1], [2], [3], [4] ]