图像处理的应用:
最常用的框架当数TensorFlow和Pytorch,而 Caffe 和 Caffe2 次之。
PyTorch 和 Torch 更适用于学术研究(research);TensorFlow,Caffe,Caffe2 更适用于工业界的生产环境部署(industrialproduction)
Caffe,适用于处理静态图像(static graph);Torch 和 PyTorch 更适用于动态图像(dynamic graph);TensorFlow 在两种情况下都很实用。
Tensorflow 和 Caffe2 可在移动端使用。
python 原生加法
def tensorflow_demo():
a = 2
b = 3
c = a + b
print('加法的结果:', c)
return None
if __name__ == "__main__":
# 代码1:tensorflow的基本结构
tensorflow_demo()
2 TensorFlow结构分析
TensorFlow 程序通常被组织成一个构建图阶段和一个执行图阶段。
在构建阶段,数据与操作的执行步骤被描述成一个图。
在执行阶段,使用会话执行构建好的图中的操作。
图和会话:
图:这是 TensorFlow 将计算表示为指令之间的依赖关系的一种表示法。
会话:TensorFlow 跨一个或多个本地或远程设备运行数据流图的机制。
张量:TensorFlow 中的基本数据对象节点:提供图当中执行的操作。
总结: tensorflow:构建图 + 执行图 流程图:定义数据(张量Tensor)和操作(节点Op) 调用各方资源,将定义好的数据和操作运行起来
图属性
def graph_demo():
'''
图的演示
:return:
'''
# 自定义图
new_g = tf.Graph()
with new_g.as_default():
a_new = tf.constant(20)
b_new = tf.constant(30)
c_new = a_new + b_new
print('a_new:', a_new)
print('b_new:', b_new)
print('c_new:', c_new)
with tf.compat.v1.Session(graph=new_g) as new_sess:
c_new_value = new_sess.run(c_new)
print("c_new_value in custom graph:", c_new_value)
return None
if __name__ == "__main__":
# 代码2:图的演示
graph_demo()
一个操作对象(Operation)是TensorFlow图中的一个节点,可以接收0个或者多个输入Tensor,并且可以输出0个或者多个Tensor,Operation对象是通过op构造函数(如tf.matmul())创建的。
# 更新/改变静态形状
# 定义占位符
# 没有完全固定下来的静态形状
# 更新形状未确定的部分
@tf.function(input_signature=[tf.TensorSpec(shape=[None, None], dtype=tf.float32)])
def process_input(input_tensor):
print('input_tensor', input_tensor)
print('input_tensor', input_tensor.shape) # input_tensor (None, None)
# 在这里执行一些操作
return input_tensor * 2
# 更新/改变静态形状
# 定义占位符
# 没有完全固定下来的静态形状
# 更新形状未确定的部分
@tf.function(input_signature=[tf.TensorSpec(shape=[None, None], dtype=tf.float32)])
def process_input(input_tensor):
print('input_tensor', input_tensor)
print('input_tensor', input_tensor.shape) # input_tensor (None, None)
# 在这里执行一些操作
return input_tensor * 2
# 传递符合占位符规格的输入
input_data = tf.constant([[1.0, 2.0], [3.0, 4.0],[3.0, 4.0]], dtype=tf.float32)
output = process_input(input_data)
print("output:\n", output)
# 动态形状修改
output_reshape = tf.reshape(output, shape=[1, 6, 1])
print("output:\n", output)
print("output_reshape:\n", output_reshape)
if __name__ == "__main__":
# 代码3:张量的演示
tensor_demo()
def variable_demo():
"""
变量的演示
:return:
"""
# 创建变量
a = tf.Variable(initial_value=50)
b = tf.Variable(initial_value=40)
c = tf.add(a, b)
print("a:\n", a)
print("b:\n", b)
print("c:\n", c)
# 打印变量的值
print("a的value:\n", a.numpy())
print("b的value:\n", b.numpy())
print("c的value:\n", c.numpy())
return None