Tensorflow的基本使用

基本使用

  • 安装:要仅为CPU安装当前版本:
    • $ pip install tensorflow
    • 将GPU包用于 支持CUDA的GPU卡:
    • $ pip install tensorflow-gpu
  • 使用 TensorFlow, 你必须明白 TensorFlow:
    • 使用图 (graph) 来表示计算任务.
    • 在被称之为 会话 (Session) 的上下文 (context) 中执行图.
    • 使用 tensor 表示数据.
    • 通过 变量 (Variable) 维护状态.
    • 使用 feed 和 fetch 可以为任意的操作(arbitrary operation) 赋值或者从其中获取数据.
  • 一个 TensorFlow 图描述了计算的过程. 为了进行计算, 图必须在 Session里被启动. Session将图的 op(operation 的缩写,图中的节点) 分发到诸如 CPU 或 GPU 之类的 设备 上, 同时提供执行 op 的方法. 这些方法执行后, 将产生的 tensor 返回. 在 Python 语言中, 返回的 tensor 是 numpy ndarray 对象; 在 C 和 C++ 语言中, 返回的 tensor 是 tensorflow::Tensor 实例.
  • TensorFlow 程序通常被组织成一个构建阶段和一个执行阶段. 在构建阶段, op 的执行步骤 被描述成一个图. 在执行阶段, 使用会话执行执行图中的 op.
    例如, 通常在构建阶段创建一个图来表示和训练神经网络, 然后在执行阶段反复执行图中的训练 op.

TensorFlow的常量(constant)

  • jupyter notebook 下操作
#消除警告
import warnings
warnings.filterwarnings("ignore")
# 导包
import tensorflow as tf
#定义常量
a = tf.constant(value=10,dtype=tf.float32)
b = tf.constant(value = 3.14)
c = tf.constant(value = [2,4,6])
d = tf.constant(value = np.random.randint(0,20,size = (3,5)))
print(a,b,c)	==>
Tensor("Const_3:0", shape=(), dtype=float32) Tensor("Const_4:0", shape=(), dtype=float32) Tensor("Const_5:0", shape=(3,), dtype=int32)

# 获取tensor对象中的值
sess = tf.Session()
#sess.run(fetches, feed_dict=None, options=None, run_metadata=None)
# 参数:fetches 获取值   feed_dict 赋值
sess.run(fetches=a)
#获取多个值
sess.run(fetches=[a,b,c])	==>[10.0, 3.14, array([2, 4, 6])]
#获取常量的运算结果
sess.run(fetches = a + b)

#tf的运算
sess.run(tf.reduce_sum(d,axis = 0))
sess.run(tf.reduce_mean(d,axis = 0))
sess.run(tf.reduce_max(d,axis = 0))
sess.run(tf.reduce_min(d,axis = 0))
sess.run(tf.reduce_prod(d,axis = 0))
#幂运算
sess.run(tf.pow(4.0,0.5))
#乘法
sess.run(tf.multiply(3,5))
#矩阵积
sess.run(tf.matmul(A,B))

TensorFlow的变量(Variable)

# tf.Variable(*args, **kwargs)
# 定义变量
v = tf.Variable(dtype = tf.float32,initial_value = 10)
v2 = tf.Variable(dtype = tf.float32,initial_value = np.random.normal(size = [3,3]))

# 变量需要进行初始化(初始化一次就好)
sess.run(tf.global_variables_initializer())
sess.run(v)	==>10

# 变量,可以改变(使用assion方法)
assign = tf.assign(v,20)
# 变为实际,运行
sess.run(assign)


占位符placeholder

# 占位符(此时只是构建出A,并没有赋值)
# None 数据形状未知,赋值的时候,给定,灵活
A = tf.placeholder(dtype = np.float32,shape = [3,4],name = 'A')
B = tf.placeholder(dtype = np.float32,shape = [4,5],name = 'B')
C = tf.placeholder(dtype = np.float32,shape = [None,4],name = 'C')
D = tf.placeholder(dtype = np.float32,shape = [4,None],name = 'D')



# matrix multipy 矩阵积
C = tf.matmul(A,B)


#给占位符赋值
sess.run(fetches=C,feed_dict={A:np.random.randint(0,10,size = (3,4)),                              B:np.random.randint(0,10,size = (4,5))})

Sess的使用

# Using the `close()` method.
sess = tf.Session()
sess.run(...)
sess.close()

# Using the context manager.
with tf.Session() as sess:
    ret = sess.run(fetches=C,feed_dict={A:np.random.randint(0,10,size = (1,4)),B:np.random.randint(0,10,size = (4,3))})
    print(ret)

tensorflow的原理

动态了解tensorflow

在这里插入图片描述

  • 图中每个神经元之间的连线可以获取到一个权重,即为线性方程的系数
    第一个神经元,方程 x,y
    x ----> -0.59
    y ----> -0.70
    x*-0.59 - 0.70y = 0
    第二个神经元,方程 x,y
    x ----->-0.33
    y ----->-0.53
    x
    -0.33 - 0.53*y = 0

结合到第三个神经元 方程 x,y
x*-0.59 - 0.70y = 0 -----> -0.89
x
-0.33 - 0.53y = 0 -----> -0.53
x
(0.590.89 + 0.330.53 ) + y*(0.700.89 + 0.530.53) = 0

最终得到x和y的关系
0.7x + 0.9039y = 0
y = -0.774*x

import numpy as np
x = np.linspace(-6,6,100)
y = -0.774*x
plt.figure(figsize=(6,6))
plt.plot(x,y)
plt.axis([-6,6,-6,6])
_ = plt.yticks(np.arange(-6,7))
#得到分割线

在这里插入图片描述

线性回归

  • 求解线性方程的斜率和斜距
# 1、导包
import warnings
warnings.filterwarnings('ignore')
import tensorflow as tf
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
from sklearn.linear_model import LinearRegression

# 2、获取样本数据
X = np.linspace(0,12,20).reshape(-1,1)
w = np.random.randint(1,5,size = 1)[0]
b = np.random.randint(1,5,size = 1)[0]
y = X*w + b + np.random.randn(20,1)*1.8
plt.scatter(X,y)

#3、使用线性回归模型训练数据(作为复习)
lr = LinearRegression()
lr.fit(X,y)
#系数
lr.coef_
#截距
lr.intercept_

# 4、使用Tensorflow求解
# 构建阶段
X_train = tf.placeholder(dtype = tf.float32,shape = [20,1],name = 'X')
# 占位符,真实y,运算时,将y赋值给占位符----->真实值
y_train = tf.placeholder(dtype = tf.float32,shape = [20,1],name = 'y')
# X_train,y_train 之间关系,线性关系,系数和截距,求解w,b-----> 变量 先随机给定一个值
w = tf.Variable(dtype = tf.float32,initial_value = np.random.randn(1,1),name = 'W')
# 这里定义值可以用numpy 也可以使用 tensorflow
b = tf.Variable(dtype = tf.float32,initial_value = tf.random_normal(shape = [1]),name = 'bias')

# 线性方程(预测)
y_predict = tf.matmul(X_train,w) + b

# 利用二乘法求解平均误差
loss = tf.reduce_mean(tf.pow(y_train - y_predict,2))
# 优化算法,梯度下降,牛顿法,最速下降法
#learning_rate 学习率 不要太大也不要太小
gdOptimizer = tf.train.GradientDescentOptimizer(learning_rate = 0.01)
opt = gdOptimizer.minimize(loss)


# 在Session中运行Tensorflow的操作
# Tensroflow中所有的操作,都是在session运算
with tf.Session() as sess:
  sess.run(tf.global_variables_initializer()) 
    for i in range(1000):    
        w_,b_ = sess.run(fetches = [w,b])
        opt_,loss_ = sess.run(fetches = [opt,loss],feed_dict = {X_train:X,y_train:y})
        print('第%d次运算,求解的斜率是:%0.2f。截距是:%0.2f。损失是:%0.2f'%(i+1,w_,b_,loss_))

===>1000次运算,求解的斜率是:1.02。截距是:2.03。损失是:2.64

逻辑斯蒂回归(分类)

#1、导包
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

#2、读取数据
mnist = input_data.read_data_sets('./',one_hot=True)

# 3、分析数据
mnist.train.images.shape
mnist.train.labels.shape
#获取一组500个数据的 随机样本和标签
batch = mnist.train.next_batch(500)
batch[0].shape	==>样本(500, 784)
batch[1].shape  ==>标签(500, 10)
#展示图片
plt.figure(figsize=(2,2))
index = np.random.randint(0,55000,size = 1)[0]
digit = images[index].reshape(28,28)
plt.imshow(digit)
print(labels[index])

#4、构建Tensorflow
# 占位符
X = tf.placeholder(dtype = tf.float64,shape = [None,784])
y = tf.placeholder(dtype = tf.float64,shape = [None,10])
# X,y之间有关系,线性关系,系数w,b
w = tf.Variable(dtype = tf.float64,
                initial_value = tf.random_normal(shape = [784,10],dtype = tf.float64),
                name = 'W')
# 截距,有多少个方程,就有多少个截距
b = tf.Variable(dtype = tf.float64,
                initial_value = tf.random_normal(shape = [10],dtype = tf.float64),
                name = 'bias')
y_predict = tf.matmul(X,w) + b
# 将预测数据转热数据
y_ = tf.nn.softmax(y_predict)
# 交叉熵,tf.log 底数是自然底数。求解损失是,必须是数,大小比较,数组,对象,不能比较
loss = tf.reduce_mean(tf.reduce_sum(tf.multiply(y,tf.log(1/y_)),axis = -1))
#图中节点
opt = tf.train.GradientDescentOptimizer(0.01).minimize(loss)
#保存模型(下次接着这次训练)
saver = tf.train.Saver()

# 5、执行Session 
with tf.Session() as sess:
   sess.run(tf.global_variables_initializer())
	#假如接着上次训练结果继续  则使用下面代码
	saver.restore(sess,save_path='./model/digit-100')
    for i in range(1,101):
        cost = 0
        for j in range(100):
            X_train,y_train = mnist.train.next_batch(550)
            opt_,loss_ = sess.run(fetches = [opt,loss],feed_dict = {X:X_train,y:y_train})
            cost += loss_/100
#         预测
        X_test,y_test = mnist.test.next_batch(1000) 
#         预测的结果,和y_test 比较
        y_pred = sess.run(y_,feed_dict = {X:X_test})
        y_test = tf.argmax(y_test,axis = -1)
        y_pred = tf.argmax(y_pred,axis = -1)       
        result = tf.equal(y_test,y_pred) # 返回boolean 相等True,不相等False        
        result = tf.cast(result,dtype = tf.float64) # [0,1,1,0,1,1,1]        
        accuracy = tf.reduce_mean(result)        
        accuracy = sess.run(accuracy)      
        print('第%d次运算,损失是:%0.4f。准确率:%0.4f'%(i,cost,accuracy))
        if i%10 == 0:
            saver.save(sess,save_path='./model/digit',global_step=i)
            print('模型保存成功')


# 获取全部变量
tf.global_variables()

#重置变量
tf.reset_default_graph()

高级用法

卷积

卷积神经网络中的卷积操作可以看做是输入和卷积核的内积运算。

  • 原型
# 算法原型
tf.nn.conv2d(input, filter=None, strides=None, padding=None, use_cudnn_on_gpu=True, data_format='NHWC', dilations=[1, 1, 1, 1], name=None, filters=None)
# 参数
ARGS:
input:A Tensor。必须是以下类型之一:float32,float64。
filter:A Tensor。必须与input类型相同。
strides:列表ints。1-D长度4.每个尺寸的滑动窗口的步幅input。
padding:string来自:"SAME"(填充0使输出和input维度相同), "VALID(不填充0)"。要使用的填充算法的类型。
	
use_cudnn_on_gpu:可选bool。默认为True。
name:操作的名称(可选)。

  • 简单使用
import warnings
warnings.filterwarnings('ignore')
import tensorflow as tf
import numpy as np
inputs = np.random.randint(0,5,size = (11,11))
# 卷积操作时,需要给一个系数
filters = np.random.randint(-1,2,size = (3,3))

# input [batch, height, width, channels]
inputs = inputs.reshape(1,11,11,1).astype(np.float32)

# filter = [filter_height, filter_width, in_channels, out_channels]
filters = filters.reshape(3,3,1,1).astype(np.float32)
conv = tf.nn.conv2d(input = inputs,filter = filters,strides = [1,1,1,1],padding = 'SAME')

with tf.Session() as sess:
    result = sess.run(conv)
    print(result.reshape(11,11))

卷积层操作图片


import tensorflow as tf
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
image = plt.imread('./1.png')[:,:,0]
image.shape
plt.imshow(image,cmap = 'gray')

# 浮雕效果
filters = np.array([[-1,-1,0],[-1,0,1],[0,1,1]])
# input = [batch, in_height, in_width, in_channels]
inputs = image.reshape(1,332,444,1)

# [filter_height, filter_width, in_channels, out_channels]
filters = filters.reshape(3,3,1,1).astype(np.float32)
conv = tf.nn.conv2d(input = inputs,filter = filters,strides = [1,1,1,1],padding = 'SAME')

with tf.Session() as sess:
    result = sess.run(conv)
    img = result.reshape(332,444)
    plt.imshow(img,cmap = plt.cm.gray)

# 边缘强化
filters = np.array([[1,1,1],[1,-7,1],[1,1,1]])
# input = [batch, in_height, in_width, in_channels]
inputs = image.reshape(1,332,444,1)

# [filter_height, filter_width, in_channels, out_channels]
filters = filters.reshape(3,3,1,1).astype(np.float32)
conv = tf.nn.conv2d(input = inputs,filter = filters,strides = [1,1,1,1],padding = 'SAME')

with tf.Session() as sess:
    result = sess.run(conv)
    img = result.reshape(332,444)
    plt.imshow(img,cmap = plt.cm.gray)

# 边缘检测
filters = np.array([[-1,-1,-1],[-1,5,-1],[-1,-1,-1]])
# input = [batch, in_height, in_width, in_channels]
inputs = image.reshape(1,332,444,1)

# [filter_height, filter_width, in_channels, out_channels]
filters = filters.reshape(3,3,1,1).astype(np.float32)
conv = tf.nn.conv2d(input = inputs,filter = filters,strides = [1,1,1,1],padding = 'SAME')

with tf.Session() as sess:
    result = sess.run(conv)
    img = result.reshape(332,444)
    plt.imshow(img,cmap = plt.cm.gray)

卷积实现图片模糊背景

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
# 读取照片
image = plt.imread('./2.jpg')
plt.figure(figsize=(9,12))
plt.imshow(image)

# 卷积处理
# 红绿蓝 当成了三个样本 [3,1182,836,1]
inputs = (image.reshape(1,1182,836,3).astype(np.float32)).transpose(3,1,2,0)

# 卷积作用,求平均,虚化,不清晰
filters = np.full(shape = [7,7,1,1],fill_value=1/49,dtype=np.float32)

conv = tf.nn.conv2d(input = inputs,filter = filters,strides = [1,1,1,1],padding = 'SAME')
# 

with tf.Session() as sess:
    result = sess.run(conv)
    print('------------------------',result.shape)
#     [1,1182,836,3]
    img= (result.reshape(3,1182,836).astype(np.uint8)).transpose(1,2,0)
    
    img[180:950,420:580] = image[180:950,420:580]
    plt.figure(figsize=(9,12))
    plt.imshow(img)

卷积神经网络的构建

权重初始化

为了创建这个模型,我们需要创建大量的权重和偏置项。这个模型中的权重在初始化时应该加入少量的噪声来打破对称性以及避免0梯度。由于我们使用的是ReLU神经元,因此比较好的做法是用一个较小的正数来初始化偏置项,以避免神经元节点输出恒为0的问题(dead neurons)。为了不在建立模型的时候反复做初始化操作,我们定义两个函数用于初始化。

def weight_variable(shape):
  initial = tf.truncated_normal(shape, stddev=0.1)
  return tf.Variable(initial)

def bias_variable(shape):
  initial = tf.constant(0.1, shape=shape)
  return tf.Variable(initial)

卷积和池化

TensorFlow在卷积和池化上有很强的灵活性。我们怎么处理边界?步长应该设多大?在这个实例里,我们会一直使用vanilla版本。我们的卷积使用1步长(stride size),0边距(padding size)的模板,保证输出和输入是同一个大小。我们的池化用简单传统的2x2大小的模板做max pooling。为了代码更简洁,我们把这部分抽象成一个函数。

def conv2d(x, W):
  return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')

def max_pool_2x2(x):
  return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
                        strides=[1, 2, 2, 1], padding='SAME')

第一层卷积

现在我们可以开始实现第一层了。它由一个卷积接一个max pooling完成。卷积在每个5x5的patch中算出32个特征。卷积的权重张量形状是[5, 5, 1, 32],前两个维度是patch的大小,接着是输入的通道数目,最后是输出的通道数目。而对于每一个输出通道都有一个对应的偏置量。

W_conv1 = weight_variable([5, 5, 1, 32])
b_conv1 = bias_variable([32])

为了用这一层,我们把x变成一个4d向量,其第2、第3维对应图片的宽、高,最后一维代表图片的颜色通道数(因为是灰度图所以这里的通道数为1 ,如果是rgb彩色图,则为3)。

x_image = tf.reshape(x, [-1,28,28,1])

We then convolve x_imagewith the weight tensor, add the bias, apply the ReLU function, and finally max pool.我们把x_image和权值向量进行卷积,加上偏置项,然后应用ReLU激活函数,最后进行max pooling。

#激活
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
# 池化
h_pool1 = max_pool_2x2(h_conv1)

第二层卷积

为了构建一个更深的网络,我们会把几个类似的层堆叠起来。第二层中,每个5x5的patch会得到64个特征。

W_conv2 = weight_variable([5, 5, 32, 64])
b_conv2 = bias_variable([64])

h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 = max_pool_2x2(h_conv2)

密集连接层

现在,图片尺寸减小到7x7,我们加入一个有1024个神经元的全连接层,用于处理整个图片。我们把池化层输出的张量reshape成一些向量,乘上权重矩阵,加上偏置,然后对其使用ReLU。

W_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])

h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64])
h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)

Dropout

为了减少过拟合,我们在输出层之前加入dropout。我们用一个placeholder来代表一个神经元的输出在dropout中保持不变的概率。这样我们可以在训练过程中启用dropout,在测试过程中关闭dropout。TensorFlow的tf.nn.dropout操作除了可以屏蔽神经元的输出外,还会自动处理神经元输出值的scale。所以用dropout的时候可以不用考虑scale。

rate = tf.placeholder("float")
# dropout,将一部分神经元掩盖,并不是真的删除
h_fc1_drop = tf.nn.dropout(h_fc1, rate)

训练与评估模型

为了进行训练和评估,我们使用与之前简单的单层SoftMax神经网络模型几乎相同的一套代码,只是我们会用更加复杂的ADAM优化器来做梯度最速下降,在feed_dict中加入额外的参数keep_prob来控制dropout比例。然后每100次迭代输出一次日志。

# 交叉熵计算损失
cross_entropy = -tf.reduce_sum(y_*tf.log(y_conv))
# 梯度下降求最优解
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
#计算正确率
correct_prediction = tf.equal(tf.argmax(y_conv,axis=1), tf.argmax(y_,axis=1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))

sess.run(tf.initialize_all_variables())
for i in range(20000):
  batch = mnist.train.next_batch(50)
  if i%100 == 0:
    train_accuracy = accuracy.eval(feed_dict={
        x:batch[0], y_: batch[1], keep_prob: 1.0})
    print "step %d, training accuracy %g"%(i, train_accuracy)
  train_step.run(feed_dict={x: batch[0], y_: batch[1], rate: 0.5})

print "test accuracy %g"%accuracy.eval(feed_dict={
    x: mnist.test.images, y_: mnist.test.labels, rate: 1.0})

详细讲解

卷积、反卷积、池化、反池化
深度学习详解

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值