文章目录
一、机器学习开发流程
-
数据加载
-
数据清洗
-
数据划分、提取
-
数据的特征工程
-
模型构建
-
模型的执行
-
模型效果评估
-
模型持久化
二、深度学习开发流程
一、执行图的构建
-
数据的特征工程
-
模型构建
二、执行图的运行
-
数据加载
-
数据清洗
-
数据划分、提取
-
模型的训练
-
模型效果评估
-
模型持久化
三、常量和会话
常量
tf.constant(value, dtype, shape, name)
import numpy as np
import tensorflow as tf
def create_graph1():
"""
构建执行图
:return:
"""
print("当前图为:{}".format(tf.get_default_graph()))
# 1. 定义两个最原始的输入tensor对象
"""
def constant(value, dtype=None, shape=None, name="Const", verify_shape=False):
功能:定义一个值不允许修改的Tensor常量对象
参数:
value: 初始值,可以是任意的Python基本数据类型(数值型、布尔类型、字符串类型、数组、元祖)以及NumPy数组类型
dtype: 明确给定常量对象的数据类型,如果不给定的话,从value中获取数据类型
shape: 给定常量对象的形状,默认不给定的话,使用value对应的形状
"""
a = tf.constant(value=5.0, dtype=tf.float32, shape=None, name='a')
b = tf.constant(value=8.0)
# 2. 两个常数tensor对象分别加一个随机数
v1 = tf.add(x=a, y=np.random.random_sample(), name='v1')
v2 = tf.add(x=b, y=tf.random_normal(shape=[], dtype=tf.float32))
# 3. 两个tensor变量相乘
result = tf.multiply(x=v1, y=v2)
# (<tf.Tensor 'a:0' shape=() dtype=float32>, <tf.Tensor 'Const:0' shape=() dtype=float32>, <tf.Tensor 'v1:0' shape=() dtype=float32>, <tf.Tensor 'Add:0' shape=() dtype=float32>, <tf.Tensor 'Mul:0' shape=() dtype=float32>)
print((a, b, v1, v2, result))
return a, b, v1, v2, result
def create_graph2():
"""
构建执行图
:return:
"""
print("当前图为:{}".format(tf.get_default_graph()))
# 1. 定义两个最原始的输入tensor对象
a = tf.constant(value=5.0)
b = tf.constant(value=8.0)
# 2. 两个常数tensor对象分别加一个随机数
v1 = a + np.random.random_sample()
v2 = b + tf.random_normal(shape=[], dtype=tf.float32)
# 3. 两个tensor变量相乘
result = v1 * v2
# (<tf.Tensor 'Const_1:0' shape=() dtype=float32>, <tf.Tensor 'Const_2:0' shape=() dtype=float32>, <tf.Tensor 'add:0' shape=() dtype=float32>, <tf.Tensor 'add_1:0' shape=() dtype=float32>, <tf.Tensor 'mul:0' shape=() dtype=float32>)
print((a, b, v1, v2, result))
return result
def create_graph3():
"""
构建执行图
:return:
"""
print("当前图为:{}".format(tf.get_default_graph()))
# 1. 定义两个最原始的输入tensor对象
a = tf.constant(value=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
dtype=tf.float32, shape=[3, 5])
b = tf.constant(value=[10, 11, 12, 13, 14, 15, 5, 6, 1, 2, 7],
dtype=tf.float32, shape=[5, 3])
# 2. 两个常数tensor对象分别加一个随机数
v1 = a + np.random.random_sample()
v2 = b + tf.random_normal(shape=[], dtype=tf.float32)
# 3. 两个tensor变量相乘
result = tf.matmul(v1, v2)
# (<tf.Tensor 'Const:0' shape=(3, 5) dtype=float32>, <tf.Tensor 'Const_1:0' shape=(5, 3) dtype=float32>, <tf.Tensor 'add:0' shape=(3, 5) dtype=float32>, <tf.Tensor 'add_1:0' shape=(5, 3) dtype=float32>, <tf.Tensor 'MatMul:0' shape=(3, 3) dtype=float32>)
print((a, b, v1, v2, result))
return a, b, v1, v2, result
def create_graph4():
print("当前图为:{}".format(tf.get_default_graph()))
a = tf.constant(value=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
dtype=tf.float32, shape=[3, 5], name='a')
# 构建一个其它的图,使用
with tf.Graph().as_default():
"""
当前with语句块中的所有代码使用的图是刚刚新创建的这个图
"""
print("with语句块中的图:{}".format(tf.get_default_graph()))
b = tf.constant(value=[10, 11, 12, 13, 14, 15, 5, 6, 1, 2, 7, 8, 5, 6, 1],
dtype=tf.float32, shape=[5, 3], name='b')
# ValueError: Tensor("b:0", shape=(5, 3), dtype=float32) must be from the same graph as Tensor("a:0", shape=(3, 5), dtype=float32).
# 不允许对不同图中的tensor对象进行联合操作(不能合并不同图中的tensor对象)
result = tf.matmul(a, b)
a, b, v1, v2, result = create_graph1()
# create_graph2()
# a, b, v1, v2, result = create_graph3()
# create_graph4()
# 执行图
# # 1. 构建会话
# """
# def __init__(self, target='', graph=None, config=None)
# target: 一个字符串,先暂时不考虑
# graph: 指定这个会话可以运行那个图上的内容,如果不给定的时候,默认就是tf.get_default_graph()
# config: session相关配置信息,可以不给
# """
# sess = tf.Session()
#
# # 获取运行结果/获取tensor对象的结果
# """
# def run(self, fetches, feed_dict=None, options=None, run_metadata=None)
# fetches:给定具体获取那些tensor的值,可以是一个tensor也可以是多个tensor,当给定多个tensor的时候,执行图执行一次。
# feed_dict:如果定义的执行图需要输入数据,那么通过该参数给定。
# """
# print(sess.run(a))
# print(sess.run(v1))
# print(sess.run(v2))
# print(sess.run(result))
# a_, v1_, v2_, result_ = sess.run([a, v1, v2, result])
# print(a_)
# print(v1_)
# print(v2_)
# print(result_)
#
# # 关闭会话
# sess.close()
#
# # 继续使用该会话进行运行的话,会报错
# # RuntimeError: Attempted to use a closed Session.
# print(sess.run(result))
with tf.Session(config=tf.ConfigProto(log_device_placement=True, allow_soft_placement=True,
gpu_options=tf.GPUOptions(allow_growth=True))) as sess:
# Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2 警告,可以不处理,产生的原因是:你的CPU本来是支持AVX加速的,但是你安装的tensorflow不支持,解决问题:https://github.com/lakshayg/tensorflow-build
# 当前模型图
print("当前默认图:")
print(tf.get_default_graph())
print(sess.graph)
print("当前默认会话:")
print(tf.get_default_session())
a_, b_, v1_, v2_, result_ = sess.run([a, b, v1, v2, result])
print(a_)
print(b_)
print(v1_)
print(v2_)
print(result_)
# 第二种Tensor执行方式,当给定默认会话的时候,可以使用Tensor对象的eval方法或者操作对象的run方法进行执行
print(result.eval())
print("=" * 100)
# 普通会话
sess = tf.Session()
print("当前的默认会话:{}".format(tf.get_default_session()))
r1_ = sess.run(fetches=[result])
print("result1:\n{}".format(r1_))
# 交互式会话
sess = tf.InteractiveSession()
print(sess)
print("当前的默认会话:{}".format(tf.get_default_session()))
r1_ = sess.run(fetches=[result])
print("result1:\n{}".format(r1_))
# 一般单个tensor对象或者操作对象进行数据的执行(该代码区域默认会话是有值的)
# tensor对象调用eval方法,操作对象调用run方法
print("result1:\n{}".format(result.eval()))
# 实际写训练代码的时候一般结构为:
with tf.Graph().as_default():
# 1. 基于业务知识构建执行图对象
# 2. 运行
with tf.Session() as sess:
# 0. 加载数据
# 1. 图执行
# 2. 图效果查看
# 3. 持久化
pass
pass
# 加载持久化模型的应用代码结构
with tf.Graph().as_default():
# 1. 和训练过程完全一样构建执行图
# 2. 运行
with tf.Session() as sess:
# 0. 加载模型
# 1. 使用模型预测获取预测结果
pass
pass
# 加载持久化模型的应用代码结构
with tf.Graph().as_default():
with tf.Session() as sess:
# 0. 加载模型、同时加载执行图的信息
# 1. 使用模型预测获取预测结果
pass
pass
四、变量、占位符、可视化
占位符的作用
就是声明数据类型,在建立模型时申请内存。
tf.placeholder(shape,shape,name)
# -- encoding:utf-8 --
"""
线性回归:y=xw+b,
假定:
x = [
[1,2,3],
[4,5,6],
[7,8,9],
[10,11,12]
]
b = [3]
w = [
[-5],
[3],
[1.5]
]
---->
y1 = x1*w+b = 1 * -5 + 2 * 3 + 3 * 1.5 + 3 = 8.5
y2 = x2*w+b = 4 * -5 + 5 * 3 + 6 * 1.5 + 3 = 7.0
y3 = x3*w+b = 7 * -5 + 8 * 3 + 9 * 1.5 + 3 = 5.5
y4 = x4*w+b = 10 * -5 + 11 * 3 + 12 * 1.5 + 3 = 4.0
Create on 19/5/11 14:02
"""
import tensorflow as tf
def f1():
# 实际写训练代码的时候一般结构为:
with tf.Graph().as_default():
# 1. 基于业务知识构建执行图对象
# a. 定义三个源数据节点信息
x = tf.constant(value=[[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12]],
dtype=tf.float32, shape=[4, 3], name='x')
w = tf.constant(value=[[-5],
[3],
[1.5]],
dtype=tf.float32, shape=[3, 1], name='w')
b = tf.constant(value=[3],
dtype=tf.float32, shape=[1], name='b')
# b. 基于业务的规则(执行的顺序)调用tf中对应的操作
y_ = tf.matmul(x, w) + b
print((x, w, b, y_))
# 2. 运行
with tf.Session() as sess:
# 1. 图执行
y = sess.run(y_)
print(y)
def f2():
# 实际写训练代码的时候一般结构为:
with tf.Graph().as_default():
# 1. 基于业务知识构建执行图对象
# a. 定义三个源数据节点信息
x = tf.constant(value=[[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12]],
dtype=tf.float32, shape=[4, 3], name='x')
"""
def __init__(self,
initial_value=None, 给定的初始化的value值,可以是Python基本数据类型或者Tensor对象
trainable=True, 给定该变量是否参与模型训练,也就是在模型训练的时候是否会进行更新的操作
collections=None,
validate_shape=True, 在更新该变量的前后是否要求shape形状一致
caching_device=None,
name=None, 给定Tensor底层对应的名称
variable_def=None,
dtype=None, 给定数据类型
expected_shape=None,
import_scope=None,
constraint=None):
"""
w = tf.Variable(initial_value=[[-5],
[3],
[1.5]],
dtype=tf.float32, name='w')
b1 = tf.constant(value=[3],
dtype=tf.float32, shape=[1], name='b1')
b = tf.Variable(initial_value=b1, dtype=tf.float32, name='b')
# b. 基于业务的规则(执行的顺序)调用tf中对应的操作
y_ = tf.matmul(x, w) + b
print((x, w, b, y_))
# c. 获取变量初始化的操作
init_op = tf.global_variables_initializer()
# 2. 运行
with tf.Session() as sess:
# 0. 变量初始化操作
# FailedPreconditionError (see above for traceback): Attempting to use uninitialized value w
sess.run(init_op)
# 1. 图执行
y = sess.run(y_)
print(y)
def f3():
# 实际写训练代码的时候一般结构为:
with tf.Graph().as_default():
# 1. 基于业务知识构建执行图对象
# a. 定义三个源数据节点信息
"""
def placeholder(dtype, shape=None, name=None):
功能:定义一个占位符。具体的值等到运行的时候给定
def placeholder_with_default(input, shape, name=None):
功能:定义一个占位符,具体的值等到运行的时候给定,如果不给定的话,使用默认值input
"""
x = tf.placeholder(dtype=tf.float32, shape=[4, 3], name='x')
c = tf.placeholder_with_default(input=1.0, shape=[], name='c')
"""
def __init__(self,
initial_value=None, 给定的初始化的value值,可以是Python基本数据类型或者Tensor对象
trainable=True, 给定该变量是否参与模型训练,也就是在模型训练的时候是否会进行更新的操作
collections=None,
validate_shape=True, 在更新该变量的前后是否要求shape形状一致
caching_device=None,
name=None, 给定Tensor底层对应的名称
variable_def=None,
dtype=None, 给定数据类型
expected_shape=None,
import_scope=None,
constraint=None):
"""
w = tf.Variable(initial_value=[[-5],
[3],
[1.5]],
dtype=tf.float32, name='w')
b1 = tf.constant(value=[3],
dtype=tf.float32, shape=[1], name='b1')
b = tf.Variable(initial_value=b1, dtype=tf.float32, name='b')
# b. 基于业务的规则(执行的顺序)调用tf中对应的操作
y_ = tf.matmul(x, w) + b
y2_ = y_ + c
print((x, w, b, y_))
# c. 获取变量初始化的操作
init_op = tf.global_variables_initializer()
# 2. 运行
with tf.Session() as sess:
# 0. 变量初始化操作
# FailedPreconditionError (see above for traceback): Attempting to use uninitialized value w
sess.run(init_op)
# 1. 图执行
y1, y2 = sess.run([y_, y2_], feed_dict={
x: [[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
[10, 11, 12]],
c: 2.0
})
print(y1)
print(y2)
print("=" * 10)
# ValueError: Cannot feed value of shape (3, 3) for Tensor 'x:0', which has shape '(4, 3)'
y1, y2 = sess.run([y_, y2_], feed_dict={
x: [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]],
c: 2.0
})
print(y1)
print(y2)
def f4():
# 实际写训练代码的时候一般结构为:
with tf.Graph().as_default():
# 1. 基于业务知识构建执行图对象
# a. 定义三个源数据节点信息
"""
def placeholder(dtype, shape=None, name=None):
功能:定义一个占位符。具体的值等到运行的时候给定
参数说明:
dtype: 给定数据类型
shape: 给定数据的形状,如果中间为None其实等价于numpy中的-1
def placeholder_with_default(input, shape, name=None):
功能:定义一个占位符,具体的值等到运行的时候给定,如果不给定的话,使用默认值input
"""
x = tf.placeholder(dtype=tf.float32, shape=[None, 3], name='x')
c = tf.placeholder_with_default(input=1.0, shape=[], name='c')
"""
def __init__(self,
initial_value=None, 给定的初始化的value值,可以是Python基本数据类型或者Tensor对象
trainable=True, 给定该变量是否参与模型训练,也就是在模型训练的时候是否会进行更新的操作
collections=None,
validate_shape=True, 在更新该变量的前后是否要求shape形状一致
caching_device=None,
name=None, 给定Tensor底层对应的名称
variable_def=None,
dtype=None, 给定数据类型
expected_shape=None,
import_scope=None,
constraint=None):
"""
w = tf.Variable(initial_value=[[-5],
[3],
[1.5]],
dtype=tf.float32, name='w')
b1 = tf.constant(value=[3],
dtype=tf.float32, shape=[1], name='b1')
b = tf.Variable(initial_value=b1, dtype=tf.float32, name='b')
# b. 基于业务的规则(执行的顺序)调用tf中对应的操作
y_ = tf.matmul(x, w) + b
y2_ = y_ + c
print((x, w, b, y_))
# c. 获取变量初始化的操作
init_op = tf.global_variables_initializer()
# 2. 运行
with tf.Session() as sess:
# 0. 变量初始化操作
# FailedPreconditionError (see above for traceback): Attempting to use uninitialized value w
sess.ru