您的位置:首页 > 编程语言 > Python开发

(Tensorflow之二)张量、会话、向前传播

2017-12-21 01:09 183 查看
一、张量

张量本身只是一个计算的过程,不会存储结果;例如:

a = tf.constant(30)

b = tf.constant(20)

c = a + b

print(c)

结果:Tensor(“add:0”, shape=(), dtype=int32)

二、会 话(session)

前面所说的张量只是一个过程,若要获得计算结果,则需创建会话,运行张量的流程:

sess = tf.Session()

d = sess.run(c)

print(d)

结果:50

三、向前传播

import tensorflowas tf

#输入层(设有3个输入变量1x3)

in_layer = tf.random_normal([1,3],mean=-1, stddev=4)

#设定输入层到隐含层随机权重(设隐含层有3个神经元3x3)

in_to_hd_w1 = tf.Variable(tf.random_normal([3,3],mean=-1, stddev=4))

#隐含层3个神经元的值(1x3)

hd_layer = tf.matmul(in_layer,in_to_hd_w1)

#隐含层到输出层随机权重(3x1)

hd_to_out_w2 = tf.Variable(tf.random_normal([3,1],mean=-1, stddev=4))

#仅有一个输出值(1x1)

out_layer = tf.matmul(hd_layer,hd_to_out_w2)

sess = tf.Session()

#注:变量必须要有初始值,in_to_hd_w1与in_to_hd_w2需初始话

sess.run(in_to_hd_w1.initializer);

sess.run(hd_to_out_w2.initializer);

#输出值

print(sess.run(out_layer))
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息