深度学习入门-线性代数(TensorFlow实现)

一  使用常量定义,实现一个矩阵相乘

#矩阵乘法
#引入库
import tensorflow as tf
import numpy as np

#定义常量并用 numpy 进行初始化
a1 = tf.constant(np.ones([4, 4]))
a2 = tf.constant(np.ones([4, 4]))

#矩阵乘法
a1_dot_a2 = tf.matmul(a1, a2)

#定义会话用于执行计算
sess = tf.Session()

#执行并输出
print(sess.run(a1_dot_a2))

二  使用变量定义,实现一个矩阵相乘

#矩阵乘法
#引入库
import tensorflow as tf
import numpy as np

#定义变量并用 numpy 进行初始化
a1 = tf.Variable(np.ones([4, 4]))
a2 = tf.Variable(np.ones([4, 4]))

#矩阵乘法
a1_dot_a2 = tf.matmul(a1, a2)

#variable 需要初始化
init = tf.global_variables_initializer()


sess = tf.Session()
sess.run(init)
print(sess.run(a1_dot_a2))

此时,虽然使用了变量,但是无法实现外部输入,由此,引入placeholder方式

三 使用placeholder,实现矩阵乘法

#矩阵乘法
#引入库
import tensorflow as tf
import numpy as np

#定义变量并用 numpy 进行初始化
a1 = tf.Variable(np.ones([4, 4]))

#定义 placeholder 用于从外部接收数据
a2 = tf.placeholder(dtype=tf.float64, shape=[4, 4])

#矩阵乘法
a1_dot_a2 = tf.matmul(a1, a2)

#variable 需要初始化
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)

# 需要给 placeholder 提供数据
print(sess.run(a1_dot_a2, feed_dict={a2:np.ones([4,4])}))

此时,通过placeholder方式,我们可以对变量喂入任意我们希望输入的数据

源自:如是的Git达人课

猜你喜欢

转载自blog.csdn.net/qq_14822691/article/details/83051177
今日推荐