Tensorflow(二):数据操作及管理机制

1、placeholder机制:解决了在有限的输入节点上实现高效地接收大量数据的问题。

用于在会话运行时动态提供输入数据;

import tensorflow as tf

a = tf.placeholder(tf.float32, shape=(2), name='input')
b = tf.placeholder(tf.float32, shape=(2), name='input')
result = a + b
print(result)

with tf.Session() as sess:
    sess.run(result, feed_dict={a:[1, 2], b:[3, 4]})
    print(result)

palceholder (dtype, shape, name)

run (self, fetches, feed_dict, options, run_metadata)

2、Variable创建变量:

1)、随机数设置:常用满足正态分布的随机数来初始化神经网络中的参数。

weight = tf.Variable(tf.random_normal([3,4], stddev=1))

#random_normal(shape, mean, stddev, dtype, seed, name) #正态分布
#truncted_normal(shape, mean, stddev, dtype, seed, name) #正态分布,但随机值偏离平均值超2个标准差,则重新随机
#random_uniform(shape, mean, stddev, dtype, seed, name) #平均分布
#random_gamma(shape, mean, stddev, dtype, seed, name) #Gamma分布

2)、常用生成函数:

tf.zeros([2,3], int32)
tf.ones([2,3], int32)
tf.fill([2,3], 4) #产生数组[[4, 4, 4], [4, 4, 4]]
tf.constant([1, 2, 3]) #产生数组[1, 2, 3]
 

3)、初始化:

init_op = tf.global_variables_initializer()

sess.run(init_op)

具体应用:

import tensorflow as tf

x = tf.constant([[1.0, 2.0]])

w1 = tf.Variable(tf.random_normal([2, 3], stddev=1, seed=1))
w2 = tf.Variable(tf.random_normal([3, 1], stddev=1, seed=1))

a = tf.matmul(x, w1)
y = tf.matmul(a, w2)

init_op = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init_op)
    print(sess.run(y))

3、管理变量空间:variable_scope()

1)、get_variable()

z = tf.get_variable("a", shape=[1], initializer=tf.constant_initializer(1.0))

get_variable(name, shape, dtype, initializer, ...)

 

2)、variable_scope()

import tensorflow as tf

a = tf.get_variable('a', [1], initializer=tf.constant_initializer(1.0))
print(a.name)
#a:0   0为生成这个变量运算的第一个结果

with tf.variable_scope('one'):
    a2 = tf.get_variable('a', [1], initializer=tf.constant_initializer(1.0))
    print(a2.name)
    #输出one/a:0 

with tf.variable_scope('one'):
    with tf.variable_scope('two'):
        a4 = tf.get_variable('a', [1])
        print(a4.name)
        
        #one/two/a:0

    b = tf.get_variable('b', [1])
    print(b.name)
    #退出了two的命名空间
    #one/b:0

with tf.variable_scope('', reuse=True):
    a5 = tf.get_variable('one/two/a', [1])
    print(a5 == a4)
    #True

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值