短小精悍算例:TensorFlow中placeholder的使用举例

TensorFlow中placeholder用于接收外部数据,见如下算例。

import tensorflow as tf
import numpy as np
# 定义变量
a = tf.Variable(np.ones([4, 4]))
# 定义placeholder,起到接受数据的作用
b = tf.placeholder(dtype=tf.float64, shape=[4, 4])
# 变量初始化(必不可少的环节)
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)

# 定义矩阵 z=a*b
z = tf.matmul(a, b)
print(sess.run(a),'\n')  # 输出b的结果
print(sess.run(b, feed_dict={
    
    b: np.eye(4)*2}),'\n')# 输出c的结果
print(sess.run(z, feed_dict={
    
    b: np.eye(4)*2}),'\n')# 输出z的结果

输出结果:(依次为a,b,z)
[[1. 1. 1. 1.]
 [1. 1. 1. 1.]
 [1. 1. 1. 1.]
 [1. 1. 1. 1.]] 

[[2. 0. 0. 0.]
 [0. 2. 0. 0.]
 [0. 0. 2. 0.]
 [0. 0. 0. 2.]] 

[[2. 2. 2. 2.]
 [2. 2. 2. 2.]
 [2. 2. 2. 2.]
 [2. 2. 2. 2.]] 

猜你喜欢

转载自blog.csdn.net/weixin_39464400/article/details/106140401
今日推荐