如何在 Python 中使用 Tensorflow 对矩阵的特定元素/行求和?


Tensorflow 是 Google 提供的一个机器学习框架。它是一个开源框架,与 Python 结合使用以实现算法、深度学习应用程序等等。它用于研究和生产目的。

它具有优化技术,有助于快速执行复杂的数学运算。这是因为它使用了 NumPy 和多维数组。这些多维数组也称为“张量”。该框架支持使用深度神经网络。它具有高度可扩展性,并附带许多流行的数据集。它使用 GPU 计算并自动管理资源。

可以使用以下代码行在 Windows 上安装“tensorflow”包:

pip install tensorflow

张量是 TensorFlow 中使用的数据结构。它有助于连接流图中的边。此流图称为“数据流图”。张量只不过是多维数组或列表。

我们将使用 Jupyter Notebook 来运行这些代码。可以使用“pip install tensorflow”在 Jupyter Notebook 上安装 TensorFlow。

以下是一个示例:

示例

import tensorflow as tf
import numpy as np

matrix_1 = tf.Variable([[1,2,3],[4,5,8],[9,10,0]])
print("The matrix is ")
print (matrix_1)

print("The sum of all elements ")
result = tf.reduce_sum(matrix_1)
print(result)
print("The sum of specific rows is")
result = tf.reduce_sum(matrix_1, 1)
print(result)

输出

The matrix is
<tf.Variable 'Variable:0' shape=(3, 3) dtype=int32, numpy=
array([[ 1, 2, 3],
   [ 4, 5, 8],
   [ 9, 10, 0]], dtype=int32)>
The sum of all elements
tf.Tensor(42, shape=(), dtype=int32)
The sum of specific rows is
tf.Tensor([ 6 17 19], shape=(3,), dtype=int32)

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

解释

  • 导入所需的包并为其提供别名,以便于使用。

  • 使用 Numpy 包创建矩阵。

  • 使用“reduce_sum”函数查找矩阵所有值的总和。

  • 如果除了传递矩阵之外,还将特定值传递给“reduce_sum”,则它会计算每一行的总和。

  • 结果输出显示在控制台上。

更新于: 2021年1月19日

329 次查看

启动你的 职业生涯

通过完成课程获得认证

开始
广告