主题
  • 默认模式
  • 浅蓝色模式
  • 淡绿色模式
  • 深夜模式

TensorFlow 操作

TensorFlow 提供了一套完整的张量运算体系,这些基础操作是构建深度学习模型的核心计算组件。

✅ TensorFlow 的核心操作包括以下基本张量运算:

  • 张量加法(Tensor Addition):逐元素相加
  • 张量减法(Tensor Subtraction):逐元素相减
  • 张量乘法(Tensor Multiplication):支持逐元素乘(*)和矩阵乘(@tf.matmul
  • 张量除法(Tensor Division):逐元素除
  • 张量平方(Tensor Square):逐元素平方(等价于tf.square
  • 张量重塑(Tensor Reshape):调整张量形状(tf.reshape

张量加法(Tensor Addition)

✅ 可以通过tensorA.add(tensorB)方法实现两个张量的相加:

实例代码 运行代码
复制
const tensorA = tf.tensor([[1, 2], [3, 4], [5, 6]]);
const tensorB = tf.tensor([[1,-1], [2,-2], [3,-3]]);

// Tensor Addition
const tensorNew = tensorA.add(tensorB);

// Result: [ [2, 1], [5, 2], [8, 3] ]

张量减法(Tensor Subtraction)

✅ 可以通过tensorA.sub(tensorB)方法实现两个张量的相减:

实例代码 运行代码
复制
const tensorA = tf.tensor([[1, 2], [3, 4], [5, 6]]);
const tensorB = tf.tensor([[1,-1], [2,-2], [3,-3]]);

// Tensor Addition
const tensorNew = tensorA.add(tensorB);

// Result: [ [2, 1], [5, 2], [8, 3] ]

张量乘法(Tensor Multiplication)

✅ 可以通过tensorA.mul(tensorB)方法实现两个张量的相乘:

实例代码 运行代码
复制
const tensorA = tf.tensor([1, 2, 3, 4]);
const tensorB = tf.tensor([4, 4, 2, 2]);

// Tensor Multiplication
const tensorNew = tensorA.mul(tensorB);

// Result: [ 4, 8, 6, 8 ]

张量除法(Tensor Division)

✅ 可以通过tensorA.div(tensorB)方法实现两个张量的相除:

实例代码 运行代码
复制
const tensorA = tf.tensor([2, 4, 6, 8]);
const tensorB = tf.tensor([1, 2, 2, 2]);

// Tensor Division
const tensorNew = tensorA.div(tensorB);

// Result: [ 2, 2, 3, 4 ]

张量平方(Tensor Square)

✅ 可以通过tensor.square()方法对张量进行平方运算:

实例代码 运行代码
复制
const tensorA = tf.tensor([1, 2, 3, 4]);

// Tensor Square
const tensorNew = tensorA.square();

// Result [ 1, 4, 9, 16 ]

张量重塑(Tensor Reshape)

张量中的元素数量等于其形状(shape)各维度大小的乘积。

由于可能存在不同形状但元素总数相同的情况,因此将张量重塑(reshape)为其他相同元素数量的形状通常十分有用。

✅ 可以通过tensor.reshape()方法对张量进行形状重塑:

实例代码 运行代码
复制
const tensorA = tf.tensor([[1, 2], [3, 4]]);
const tensorB = tensorA.reshape([4, 1]);

// Result: [ [1], [2], [3], [4] ]


评论区 0
发表评论
教程介绍
机器学习是人工智能的子领域,通过算法让计算机从数据中自动学习规律,并做出预测或决策。
29 章节
28 阅读
0 评论