主要概念
- Graph
- Session
- Tensor
- Operation
- Feed
- Fetch
- TensorFlow高层封装与常用API
Graph
描述计算的过程,通过tensorboard图形化流程结构
声明
import tensorflow as tf
# 声明
g = tf.Graph()
g = tf.get_default_graph()
x = tf.constant(0) # 利用变量直接获取graph
g = x.graph
声明并交叉使用多个Graph
# 声明并交叉使用多个Graph
g1 = tf.Graph()
with g1.as_default():
x1 = tf.constant(1.0, name="x1")
g2 = tf.Graph()
with g2.as_default():
x2 = tf.constant(2.0, name="x2")
with tf.Session(graph=g2) as sess1:
x1_list = tf.import_graph_def(g1.as_graph_def(),
return_elements=["x1:0"], name='')
print(sess1.run(x1_list[0] + x2))
保存pb
# 保存pb
g1 = tf.Graph()
tf.train.write_graph(g1.as_graph_def(), '.', 'graph.pb', False)
从pb中恢复Graph
# 从pb中恢复Graph
with tf.gfile.FastGFile("graph.pb", 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
tf.import_graph_def(graph_def, name='')
sess = tf.Session()
c1_tensor = sess.graph.get_tensor_by_name("c1:0")
c1 = sess.run(c1_tensor)
使用tensorboard可视化计算图结构
# 使用tensorboard可视化计算图结构
a = tf.constant(1, name='input_a')
b = tf.constant(2, name='input_b')
c = tf.multiply(a, b, name='maltiply_c')
d = tf.add(a, b, name='add_d')
e = tf.add(d, c, name='add_e')
sess = tf.Session()
sess.run(e)
writer = tf.summary.FileWriter('graph', sess.graph)
Session(会话)
- 图必须在"会话"的上下文中执行
- 会话将图的op操作分发到CPU或GPU之类的设备上执行
- Session完成前端和后端的沟通
会话包括四个环节
- 创建关闭
- 注入机制
- 指定设备
- 资源分配
创建和关闭Session
三种创建方法
sess = tf.Session()
sess = tf.InteractiveSession()
with tf.Session() as Sess:
...
sess.close()
注入机制
sess.run(...)
sess.run(tf.global_variables_initializer())
a = tf.placeholder(dtype=tf.float32) # 表示一个占位符
b = tf.placeholder(dtype=tf.float32)
add = a + b
add_val = sess.run(add, feed_dict={a:1, b:2}) # feed完成数据注入
其中,feed就是数据注入的过程
指定资源设备
a = tf.placeholder(dtype=tf.float32)
b = tf.placeholder(dtype=tf.float32)
add = a + b
with tf.Session() as sess:
with tf.device("/cpu:0"):
print(sess.run(add, feed_dict={a:1, b:2}))
资源分配-控制GPU资源使用率
config = tf.ConfigProto()
config.gpu_options.allow_growth = True # 配置GPU资源使用率,系统根据任务大小分配资源
session = tf.Session(config=config, ...)
按需分配资源
Tensor
- 在计算图中,节点之间传递的数据都是Tensor对象
- N维数组
Tensor的定义
- tf.constant()
- tf.Variable()
- tf.placeholder()
- tf.SparseTensor()
前三个为重点
cons = tf.constant(value=[1, 2], dtype=tf.float32, shape=(1, 2),
name='testconst', verify_shape=False)
X = tf.placeholder(dtype=tf.float32, shape=[144, 10], name='X')
# 占位符用于占位,可以知道shape,也可以不知道
X = tf.placeholder(dtype=tf.float32, shape=[None, None], name='X')
W = tf.Variable(tf.zeros([3, 10]), dtype=tf.float64, name='W')
# W是变量,可以通过学习进行变化
Operation
- TensorFlow Graph中的计算节点,输入输出均为Tensor
- 调用Session.run(tensor)或者tensor.eval()方法可获取该Tensor的值
Feed
- 通过feed为计算图注入值
a = tf.placeholder(tf.float32)
b = tf.placeholder(tf.float32)
c = tf.add(a, b)
with tf.Session() as sess:
result = sess.run(c, feed_dict{a:3, b:4})
print(result)
Fetch
- 上面计算中的 c 实际上就是Fatch
- 使用Fetch获取计算结果
tf.Session.run(fetches, feed_dict=None)
举例
x = tf.placeholder(tf.float32, shape=(1, 2))
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)
with tf.Session() as sess:
# 变量运行前必须做初始化操作
init_op = tf.global_variables_initializer()
sess.run(init_op)
print(sess.run(y, feed_dict={x:[[0.7, 0.5]]}))
TensorFlow中的核心API
TensorFlow在深度学习中使用的API
- 基本运算
- 搭建网络
- 训练优化
- 数据相关
基本运算
tf.expand_dims(input, dim, name=None)
tf.split(split_dim, num_split, value, name='split')
tf.concat(concat_dim, values, name='concat')
tf.cast()
tf.reshape()
tf.equal()
tf.matmul(a, b)
tf.argmax()
tf.squeeze()
搭建网络 tf.nn
tf.nn.conv2d
tf.nn.max_pool
tf.nn.avg_pool
tf.nn.relu
tf.nn.dropout
tf.nn.l2_normalize
tf.nn.batch_normalization
tf.nn.l2_loss
tf.nn.softmax_cross_entropy_with_logits
训练优化 tf.train
tf.train.Saver.save
tf.train.Saver.restore
tf.train.GradientDescentOptimizer(0.01).minimize(loss)
tf.train.exponential_decay(1e-2, global_step, decay_steps=sample_size/batch, decay_rate=0.98, staircase=True)
数据读取相关 tf.train 和 tf.data
tf.train.string_input_producer(filenames, num_epoches=num_epoches, shuffle=True)
tf.train.shuffle_batch([example, label], batch_size=batch_size, capacity=capacity, min_after_dequeue=min_after_dequeue)
tf.train.Coordinator()
tf.train.start_queue_runners(sess=sess, coord=coord)
TensorFlow中的数据操作
- TensorFlow提供了TFRecord的格式来统一存储数据
- TFRecord 将图像数据和标签放在一起的二进制文件(protocol buffer),能更好地利用内存,实现快速的复制,移动,读取,存储
- 数据读取:tf.train.string_input_producer
- 数据解析:tf.TFRecordReader、tf.parse_single_example
- 数据写入:tf.python_io.TFRecordWriter
数据写入相关的API方法
writer = tf.io.TFRecordWriter()
example = tf.train.Example() # 可以定义具体数据,Feature中的label,图像的宽高等
writer.write(example.SerializeToString()) # 将数据序列化写入到TFRecord文件中
writer.close()
example = tf.train.Example(features=tf.train.Features(feature={
'label': tf.train.Feature(int64_list=
tf.train.Int64List(value=[index])),
'img_raw': tf.train.Feature(bytes_list=
tf.train.BytesList(value=[img_raw]))
}))
# 还有float型,定义和int是一样的
TFRecord数据写入例子
使用TensorFlow实现TFRecord图像数据打包
以cifar10图像数据为打包的对象
import tensorflow as tf
import cv2
import numpy as np
classification = ['airplane',
'automobile',
'bird',
'cat',
'deer',
'dog',
'frog',
'horse',
'ship',
'truck']
import glob
idx = 0
im_data = []
im_labels = []
for path in classification:
path = "data/image/train/" + path
im_list = glob.glob(path + "/*")
im_label = [idx for i in range(im_list.__len__())]
idx += 1
im_data += im_list
im_labels += im_label
print(im_labels)
print(im_data)
tfrecord_file = "data/train.tfrecord"
# writer = tf.python_io.TFRecordWriter(tfrecord_file)
writer = tf.io.TFRecordWriter(tfrecord_file)
index = [i for i in range(im_data.__len__())]
np.random.shuffle(index)
for i in range(im_data.__len__()):
im_d = im_data[index[i]]
im_l = im_labels[index[i]]
data = cv2.imread(im_d)
#data = tf.gfile.FastGFile(im_d, "rb").read()
ex = tf.train.Example(
features = tf.train.Features(
feature = {
"image": tf.train.Feature(
bytes_list=tf.train.BytesList(
value=[data.tobytes()])),
"label": tf.train.Feature(
int64_list=tf.train.Int64List(
value=[im_l])),
}
)
)
writer.write(ex.SerializeToString())
writer.close()
TensorFlow数据读取机制
通常设定一个epoch是将所有训练样本训练完一遍的循环,通常训练的过程要有n个epoch
假设训练样本有10000个图像,1个batch是100张,也就是每次训练100张图像,训练100次才是一个epoch,然后还要训练n个epoch
文件名队列的作用:假设要循环3次所有图像,epoch=3,A、B、C分别为这三个epoch中的数据,每个数据都经过了shuffle,因此是不一样的。假设一个epoch里只有三张图像,分别为a,b,c,那么在"文件名队列"中他们的排列可能就是 [a, b, c, b, c, a, c, b, a],分别对应着epoch A,epoch B,epoch C。之后会依次按照这个队列中的顺序写入内存队列,再进行训练计算
数据读取相关的API方法
- 直接从文件中读取图片
- 从TF-Record中解析打包的图片数据
- tf.train.string_input_producer(较后面那个常用)、tf.train.slice_input_producer:文件队列的构造
- tf.data库(动态图机制)
TFRecord数据读取示例
直接从文件中读取图片(cifar10)
import tensorflow as tf
images = ['image1.jpg', 'image2.jpg', 'image3.jpg', 'image4.jpg']
labels = [1, 2, 3, 4]
[images, labels] = tf.train.slice_input_producer([images, labels],
num_epochs=None,
shuffle=True)
with tf.Session() as sess:
sess.run(tf.local_variables_initializer())
tf.train.start_queue_runners(sess=sess)
for i in range(10):
print(sess.run([images, labels]))
从TF-Record中解析图片数据
reader_cifar10.py
import tensorflow as tf
filelist = ['data/train.tfrecord']
# 定义文件队列
file_queue = tf.train.string_input_producer(filelist,
num_epochs=None,
shuffle=True)
reader = tf.TFRecordReader()
# ex需要解码
_, ex = reader.read(file_queue)
feature = {
'image': tf.FixedLenFeature([], tf.string),
'label': tf.FixedLenFeature([], tf.int64)
}
batchsize = 2
batch = tf.train.shuffle_batch([ex], batchsize, capacity=batchsize*10,
min_after_dequeue=batchsize*5)
example = tf.parse_example(batch, features=feature)
image = example['image']
label = example['label']
image = tf.decode_raw(image, tf.uint8)
image = tf.reshape(image, [-1, 32, 32, 3])
with tf.Session() as sess:
sess.run(tf.local_variables_initializer())
tf.train.start_queue_runners(sess=sess)
for i in range(1):
image_bth, _ = sess.run([image,label])
import cv2
cv2.imshow("image", image_bth[0,...])
cv2.waitKey(0)
TensorFlow在深度学习中的高级封装
- TF-Slim(此例中用Slim搭建网络结构)
- TFLearn
- Keras(更方便一些)
- TensorLayer
slim相关的接口函数
- slim layers
- slim.arg_scope
- slim.data
- slim.evaluation
- slim.learning
- slim.losses
- slim.nets
- slim.variables
- slim.metrics
slim layers
slim.arg_scope——参数作用域,精简代码
arg_scope(list_ops_or_scope, **kwargs)
- list_ops_or_scope:操作列表或作用域列表
- kwargs:参数,以keyword=value方式显示
- 共同参数
BatchNorm层使用技巧
slim.batch_norm()函数
- normalizer_fn = slim.batch_norm
- normalizer_params = batch_norm_params
batch_norm_params
训练时,将is_training 设为 True,测试时设为False
slim net
slim loss
slim learn 学习率
优化器
slim metrics
slim evaluation
slim data
TensorFlow中的数据增强方法
Tensorboard调试技巧
localhost:6060
tf.summary
总体上来说,tensorflow 1 和 tensorflow 2 两个版本的差别还是很大的,现在可能更多的用的是2版本的,但是现在学习用到了1,就记录一下当个笔记吧。
Original: https://blog.csdn.net/m0_51738700/article/details/122107295
Author: 糖公子没来过
Title: TensorFlow1基本概念介绍
相关阅读
Title: Anaconda安装TensorFlow2及在Jupyter Notebook使用
1.卸载原来的tensorflow环境
2.创建新的虚拟环境
3.安装tensorflow并验证
4.安装ipython
5.安装jupyter
6. 安装python kernel for Tensroflow
上面是错误示范(直接复制了别人的语句忘加自己的了),后面是自己的环境:
7.打开jupyter验证
import tensorflow as tf
tf.compat.v1.disable_eager_execution()
sess = tf.compat.v1.Session() #经查资料,安装的是tensorflow2,所以不能直接使用.session
hello=tf.constant('Hello Tensorflow!')
print(sess.run(hello).decode()) #这里的输出结果是一个字节字符串。要删除字符串引号和"b"(表示字节,byte)只保留单引号内的内容,可以使用 decode() 方法。
a = tf.constant(1)
b = tf.constant(2)
print(sess.run(a+b))
8.遇到的一些 问题
一个是,直接使用了以下的代码
import tensorflow as tf
#定义一个常量
hello = tf.constant('hello,tensorflow')
#建立一个session
session = tf.Session()
#通过session中的run函数运行hello这个变量
print(session.run(hello))
#注意如果单纯的使用 print(hello) 的话,是不会输出 hello,tensorflow 的
#关闭session
session.close()
会报:
ERROR:root:Internal Python error in the inspect module.
Below is the traceback from this internal error.
ERROR:root:Internal Python error in the inspect module.
Below is the traceback from this internal error.
ERROR:root:Internal Python error in the inspect module.
Below is the traceback from this internal error.
Traceback (most recent call last):
File "E:\Anaconda\envs\tensorflow\lib\site-packages\IPython\core\interactiveshell.py", line 3343, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-1-1d20fdd37a67>", line 4, in <module>
sess = tf.Session()
AttributeError: module 'tensorflow' has no attribute 'Session'
</module></ipython-input-1-1d20fdd37a67>
原因是TensorFlow2中已经取消了1中的sesison,用我上面7里的代码即可。
9.遇到的一些问题
有可能在安装时会报(别人的图,我没拍)
我的做法是把
虚拟环境里的E:\Anaconda\envs\tensorflow\Library\bin\pythoncom36.dll,用
E:\Anaconda\Library\bin\pythoncom36.dll替换掉了。
如果这样不行,直接把这两个pythoncom36.dll都删掉,可以提前备份一份。
参考:
Anaconda上安装Tensorflow并在jupyter上运行 - BMDACM - 博客园 (cnblogs.com)
(1条消息) 利用Anaconda搭建TensorFlow环境并在Jupyter Notebook使用_寻梦梦飞扬的博客-CSDN博客_jupyter使用tensorflow
tensorflow2.4中使用session和graph_Keras深度学习的博客-CSDN博客 【Python】如何解决:无法定位程序输入点XXX于动态链接库D:Anaconda\ibrarnybin\pythoncom38.dll上_赶不上明天的博客-CSDN博客_python 无法定位程序输入点
Original: https://blog.csdn.net/m0_55931547/article/details/124075706
Author: 不琂而玉
Title: Anaconda安装TensorFlow2及在Jupyter Notebook使用