如何使用Python使用Tensorflow来乘以两个矩阵?
Tensorflow是谷歌提供的一种机器学习框架。它是与Python一起实现算法、深度学习应用程序等的开源框架。它用于研究和生产目的。它具有优化技术,帮助快速执行复杂的数学运算。
这是因为它使用NumPy和多维数组。这些多维数组也称为“张量”。该框架支持使用深度神经网络。它高度可扩展,并配备了许多流行的数据集。它使用GPU计算并自动管理资源。它配备了众多机器学习库,并且得到了良好的支持和说明文件。该框架具有运行深度神经网络模型、训练它们并创建预测相应数据集相关特征的应用程序的能力。
可以使用以下代码在Windows上安装“tensorflow”软件包 −
pip install tensorflow
张量是TensorFlow中使用的数据结构。它有助于在流程图中连接边缘。此流程图称为“数据流图”。张量无非是多维数组或列表。
我们将使用Jupyter Notebook运行此代码。可以使用“pip install tensorflow”在Jupyter Notebook上安装TensorFlow。

以下是一个示例 −
更多Python相关文章,请阅读:Python 教程
示例
import tensorflow as tf
import numpy as np
matrix_1 = np.array([(1,2,3),(3,2,1),(1,1,1)],dtype = 'int32')
matrix_2 = np.array([(0,0,0),(-1,0,1),(3,3,4)],dtype = 'int32')
print("The first matrix is ")
print (matrix_1)
print("The second matrix is ")
print (matrix_2)
print("The product is ")
matrix_1 = tf.constant(matrix_1)
matrix_2 = tf.constant(matrix_2)
matrix_prod = tf.matmul(matrix_1, matrix_2)
print((matrix_prod))
输出
The first matrix is
[[1 2 3]
[3 2 1]
[1 1 1]]
The second matrix is
[[ 0 0 0]
[−1 0 1]
[ 3 3 4]]
The product is
tf.Tensor(
[[ 7 9 14]
[ 1 3 6]
[ 2 3 5]], shape=(3, 3), dtype=int32)
解释
-
导入所需的包并为它提供别名以便更易于使用。
-
使用Numpy包创建了两个矩阵。
-
将它们从Numpy数组转换为Tensorflow中的常量值。
-
使用Tensorflow中的“matmul”函数来乘以矩阵中的值。
-
将得到的乘积显示在控制台上。
极客教程