tensorflow中的placeholder()以及tf.initialize_all_variables()函数的理解

本文围绕TensorFlow展开,介绍了placeholder()函数的作用,它在神经网络构建graph时占位,运行模型时用feed_dict()传入数据,还说明了其参数含义。同时解释了tf.initialize_all_variables()函数用于初始化神经网络变量,最后提及TensorFlow编程思维与正常编程不同,语句在会话开启时才执行。

为什么要用placeholder?

tensorflow的设计理念就是先构造整个计算过程,也就是在编写程序时,先构造整个系统的graph,代码不会立即的生效,而是在运行的时候,启动一个Session,程序才会真正的运行.所以placeholder()函数的作用就是在神经网络在构建graph的时候占位,这个时候并没有把要输入的数据传入到模型,只是通过占位来分配了必要的内存,等建立会话之后,在运行模型的时候使用feed_dict()函数来向占位符传入数据.

tf.placeholder(
dtype,
shape=None,
name=None
) #函数具体形式
参数:
dtype:数据类型。常用的是tf.float32,tf.float64等数值类型
shape:数据形状。默认是None,就是一维值,也可以是多维(比如[2,3] 两行3列, [None, 3]表示列是3,行不定)
name:名称(可定义可不定义)

tf.initialize_all_variables()函数具体初始化的是什么

初始化的是神经网络中的变量,只有在定义了变量之后才要求是必须加的,没有定义变量就不用加这条语句进行初始化

个人理解

  1. TensorFlow与我们正常的编程思维略有不同:TensorFlow中的语句不会立即执行;而是等到开启会话session的时候,才会执行session.run()中的语句。如果run中涉及到其他的节点,也会执行到。
  2. Tesorflow模型中的所有的节点都是可以视为运算操作op或tensor
帮我整段修改一下,改成TensorFlow2.11版本可用的:“ def TGCN(_X, _weights, _biases): ### cell_1 = tgcnCell(cell=custom_cell,gru_units=gru_units, adj=adj, num_nodes=num_nodes) cell = tf.nn.rnn_cell.MultiRNNCell([cell_1], state_is_tuple=True) _X = tf.unstack(_X, axis=1) outputs, states = tf.nn.static_rnn(cell, _X, dtype=tf.float32) m = [] for i in outputs: o = tf.reshape(i,shape=[-1,num_nodes,gru_units]) o = tf.reshape(o,shape=[-1,gru_units]) m.append(o) last_output = m[-1] output = tf.matmul(last_output, _weights['out']) + _biases['out'] output = tf.reshape(output,shape=[-1,num_nodes,pre_len]) output = tf.transpose(output, perm=[0,2,1]) output = tf.reshape(output, shape=[-1,num_nodes]) return output, m, states ###### placeholders ###### # 使用 tf.placeholder inputs = tf.compat.v1.placeholder(tf.float32, shape=[None, seq_len, num_nodes]) labels = tf.compat.v1.placeholder(tf.float32, shape=[None, pre_len, num_nodes]) # Graph weights weights = { 'out': tf.Variable(tf.random.normal([gru_units, pre_len], mean=1.0), name='weight_o')} biases = { 'out': tf.random.normal(shape=[pre_len],name='bias_o')} if model_name == 'tgcn': pred,ttts,ttto = TGCN(inputs, weights, biases) y_pred = pred ###### optimizer ###### lambda_loss = 0.0015 Lreg = lambda_loss * sum(tf.nn.l2_loss(tf_var) for tf_var in tf.trainable_variables()) label = tf.reshape(labels, [-1,num_nodes]) ##loss loss = tf.reduce_mean(tf.nn.l2_loss(y_pred-label) + Lreg) ##rmse error = tf.sqrt(tf.reduce_mean(tf.square(y_pred-label))) optimizer = tf.train.AdamOptimizer(lr).minimize(loss) ###### Initialize session ###### variables = tf.global_variables() saver = tf.train.Saver(tf.global_variables()) #sess = tf.Session() gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.333) sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options)) sess.run(tf.global_variables_initializer())”
最新发布
04-05
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值