tensorflow 的矩阵运算
程序员文章站
2022-07-12 08:12:53
...
输出矩阵的基本信息
import tensorflow as tf
data1 = tf.constant([[6,6]])
data2 = tf.constant([[2],
[2]])
data3 = tf.constant([[3,3]])
data4 = tf.constant([[1,2],
[3,4],
[5,6]])
# 输出矩阵的维度
print("矩阵的维度:", data4.shape)
with tf.Session() as sess:
print("----------------------")
print("运行结果")
# 打印整个矩阵
print(sess.run(data4))
# 打印第一行
print(sess.run(data4[0]))
# 打印第一列
print(sess.run(data4[:,0]))
# 打印第一行第一列
print(sess.run(data4[0,0]))
矩阵的乘法
import tensorflow as tf
data1 = tf.constant([[6,6]])
data2 = tf.constant([[2],
[2]])
data3 = tf.constant([[3,3]])
data4 = tf.constant([[1,2],
[3,4],
[5,6]])
# 输出矩阵的维度
print("矩阵的维度:", data4.shape)
matMul = tf.matmul(data1,data2) # 矩阵1 乘以 矩阵2
matMul2 = tf.multiply(data1,data2) # 将矩阵中各个元素相乘
matAdd = tf.add(data1,data3) # 矩阵相加
with tf.Session() as sess:
print("运算结果")
print(sess.run(matMul))
print(sess.run(matAdd))
print(sess.run(matMul2))
print("中括号一次打印多个内容")
print(sess.run([matMul, matAdd]))
矩阵的维度: (3, 2)
运算结果
[[24]]
[[9 9]]
[[12 12]
[12 12]]
中括号一次打印多个内容
[array([[24]]), array([[9, 9]])]