您的位置:首页 > 理论基础 > 计算机网络

Tensorflow基础知识与神经网络构建--step by step 入门TensorFlow(一)

2017-08-24 13:28 716 查看

Tensorflow基础知识与神经网络构建–step by step 入门TensorFlow(一)

标签: Tensorflow

我们将采用Jupyter notebook交互式编程的方式,通过一步步代码的讲解,学习Tensorflow编程。推荐使用Jupyter notebook作为开发环境按照文中的代码step by step 的学习。

文章列表:

Tensorflow基础知识与神经网络构建–step by step 入门TensorFlow(一)

深层神经网络实现–step by step 入门TensorFlow(二)

MNIST 数字识别和数据持久化–step by step 入门TensorFlow(三)

计算图

tensorflow程序一般分为2部分:1、构造计算图 2、执行计算

一般不用指定计算图,系统会维护一个默认的计算图

下面关于a、b、c的定义都是构造图,并且使用的是默认

下面的程序演示的就是图的构造

import tensorflow as tf

print(a.graph is tf.get_default_graph())


True


可以构造新图,但图上的变量不会共享

import tensorflow as tf

g1 = tf.Graph()
with g1.as_default():
v = tf.get_variable("v",shape=[1], initializer=tf.zeros_initializer())

g2 = tf.Graph()
with g2.as_default():
v = tf.get_variable("v",shape=[1], initializer=tf.ones_initializer())

with tf.Session(graph=g1) as sess:
sess.run(tf.global_variables_initializer())
with tf.variable_scope("",reuse=True):
print(sess.run(tf.get_variable("v")))
with tf.Session(graph=g2) as sess:
sess.run(tf.global_variables_initializer())
with tf.variable_scope("",reuse=True):
print(sess.run(tf.get_variable("v")))


[ 0.]
[ 1.]


还可以指定运算设备

g = tf.Graph()
with g.device('/gpu:0'):
result = a + b
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(sess.run(result))


[ 5.  7.]


张量

tensorflow中所有数据都有张量表示,张量不存储数据,存储的是如何获得数据

如我们输出张量时,得到的是一个对张量的引用,如未命名,它会以 运算名_当前第几次 命名

从输出可看出张量只保存名字、维度、类型3个属性

import tensorflow as tf
a = tf.constant([1.0, 4.0], name='a')
b = tf.constant([3.0, 4.0], name='b')
c = tf.add(a, b, name='c')
d = a+b
print(c)
print(d)


Tensor("c:0", shape=(2,), dtype=float32)
Tensor("add_5:0", shape=(2,), dtype=float32)


若a、b类型不匹配,将会运算错误。tensorflow支持14种不同类型,包括tf.float32,tf.float64,tf.int8,tf.int16,tf.int32,tf.int64,tf.uint8,tf.bool,tf.complex64,tf.complex128

%xmode Plain
e = tf.constant([1,2], name='e')
f = a + e
print(f)


Exception reporting mode: Plain

Traceback (most recent call last):

File "<ipython-input-25-e87db19d2077>", line 3, in <module>
f = a + e

...

ValueError: Tensor conversion requested dtype float32 for Tensor with dtype int32: 'Tensor("e_1:0", shape=(2,), dtype=int32)'


张量有2类用途,一类是对中间结果的引用,一类是对最后结果的引用。之前的a、b都是对中间结果的应用,下面我们将通过对话的介绍,来展示对最后结果的引用

会话

会话(session)拥有和管理tensorflow程序的所有资源,程序通过会话来执行运算。

会话有两种模式,一种需要明确调用生成函数和关闭函数,另一种python的上下文管理器来管理。可以用sess.run()来执行会话,也可以用变量.eval(session=sess)来执行

import tensorflow as tf
a = tf.constant([3.0,4.0], name='a')
b = tf.constant([2.0, 3.0], name='b')
result = a + b
sess = tf.Session()
print(sess.run(result))
sess.close()


[ 5.  7.]


with tf.Session() as sess:
print(sess.run(result))
print(result.eval(session=sess))


[ 5.  7.][ 5.  7.]


tensorflow不会生成默认的session,需要自己指定,而指定后该session将会被当作默认的session

sess = tf.Session()
with sess.as_default():
print(result.eval())


[ 5.  7.]


在python脚本或Jupyter编辑器上,可以通过tf.InteractiveSession()构造默认会话,以供全局使用

print(result.eval())
sess.close()


[ 5.  7.]


同时可通过ConfigProto()进行会话的配置,当第一个参数为true时,在缺少GPU资源或有定义在CPU上的计算时会把计算放到CPU上。当第二个参数为true时,将把运算的设备也记录日志,以便调试。

config = tf.ConfigProto(allow_soft_placement=True, log_device_placement=True)
sess1 = tf.InteractiveSession(config=config)
sess2 = tf.Session(config=config)


tensorflow变量

tensorflow中的变量tf.Variable用以存储和更新神经网络参数,变量定义的时候需要初始化,一般用下列随机函数进行初始化

w1 = tf.Variable(tf.random_normal([3,4], mean=0, stddev=0.8))#生成3*4的矩阵,矩阵中的元素未平均值0,标准差0.8的随机数
w2 = tf.Variable(tf.truncated_normal([3,4], mean=0, stddev=0.8))#随机分布,若值超过平均数2个标准差将,重新生成
w3 = tf.Variable(tf.random_uniform([3,4], minval=-0.7, maxval=0.6)) #平均分布
w4 = tf.Variable(tf.random_gamma([3,4], alpha=0.1, beta=0.4)) # gamma分布


tensorflow中的变量也有设为常数值,比如b一般初始化为常数

import tensorflow as tf
b1 = tf.Variable(tf.zeros([2,3], tf.int32))
b2 = tf.Variable(tf.ones([3,4],tf.int32))
b3 = tf.Variable(tf.fill([2,3], 8))
b4 = tf.Variable(tf.constant([2,4,6]))


下面是一个简单的前向神经网络

import tensorflow as tf
w1 = tf.Variable(tf.random_normal([2,3],stddev=0.8, seed=1)) # seed为随机种子
w2 = tf.Variable(tf.random_normal([3,1],stddev=0.8, seed=1))
b1 = tf.Variable(tf.constant([0.1,0.2,0.3]))
b2 = tf.Variable(tf.constant([0.4]))
x = tf.constant([[0.5, 0.6]]) # 1*2矩阵->列向量
l1=tf.matmul(x, w1)+b1
y = tf.matmul(l1, w2) +b2
init_op = tf.global_variables_initializer() # 初始化所有全局变量
with tf.Session() as sess:
sess.run(init_op)
print(sess.run(y))


[[ 2.33802915]]


神经网络实现

下面我们将实现一个完整的神经网络,具体解析见注释。

import tensorflow as tf
from numpy.random import RandomState

batch_size = 8

x = tf.placeholder(tf.float32, shape=[None, 2], name='x_input')
y_label = tf.placeholder(tf.float32, shape=[None, 1], name='y_output')
# 定义网络结构
w1 = tf.Variable(tf.random_normal([2,3],stddev=1, seed=1)) # seed为随机种子
w2 = tf.Variable(tf.random_normal([3,1],stddev=1, seed=1))
b1 = tf.Variable(tf.constant([0.1,0.2,0.3]))
b2 = tf.Variable(tf.constant([0.1]))
l1=tf.matmul(x, w1)+b1
y = tf.matmul(l1, w2) +b2

# 定义损失函数和反向传播算法
cross_entroy = -tf.reduce_mean(y_label*tf.log(tf.clip_by_value(y, 1e-10, 1.0)))

train_step = tf.train.AdamOptimizer(0.001).minimize(cross_entroy)

# 通过随机数生成一个模拟数据集
ram = RandomState(1)
dataset_size = 200
X = ram.rand(dataset_size, 2) # 随机生成X
Y = [[int(x1+x2<1)] for (x1, x2) in X] # x1+x2小于1的为正样本

init_op = tf.global_variables_initializer() # 初始化所有全局变量
with tf.Session() as sess:
sess.run(init_op)
print(sess.run([w1,w2,b1,b2]))
#print(sess.run(w2))
steps = 1000
for i in range(steps):
start = batch_size * i % dataset_size
end = min(batch_size + start, dataset_size)
sess.run(train_step, feed_dict={x:X[start:end], y_label:Y[start:end]})
if i%100==0:
entroy = sess.run(cross_entroy, feed_dict={x:X, y_label: Y})
print("after %d step entroy is %g" % (i, entroy))
print(sess.run([w1,w2,b1,b2]))


[array([[-0.81131822,  1.48459876,  0.06532937],
[-2.4427042 ,  0.0992484 ,  0.59122431]], dtype=float32), array([[-0.81131822],
[ 1.48459876],
[ 0.06532937]], dtype=float32), array([ 0.1       ,  0.2       ,  0.30000001], dtype=float32), array([ 0.1], dtype=float32)]
after 0 step entroy is 0.0109935
after 100 step entroy is 0.00414283
after 200 step entroy is 0.00180442
after 300 step entroy is 0.00119243
after 400 step entroy is 0.000892674
after 500 step entroy is 0.000589411
after 600 step entroy is 0.000288374
after 700 step entroy is -0
after 800 step entroy is -0
after 900 step entroy is -0
[array([[-0.8940888 ,  1.56725895,  0.17195038],
[-2.50734305,  0.16374315,  0.68157411]], dtype=float32), array([[-0.88425207],
[ 1.61494493],
[ 0.19808137]], dtype=float32), array([-0.02715978,  0.32707116,  0.46436408], dtype=float32), array([ 0.22417794], dtype=float32)]



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