Tensorflow深度学习应用(筑基篇)

筑基篇

#coding=gbk
'''
1.张量    
用于描述数据,可以理解为多维数组,包含张量的名字,阶数,形状数值类型.    Tensor("Add:0", shape=(m,n,k), dtype=float32),表示节点名为Add,0代表第0个输出,shape表示为MxNxK维的数组,类型为float32。
   
2.张量的类型    tf.float32,tf.float64,tf.int8,tf.int16,tf.int32,tf.int64,tf.uint8,tf.bool,tf.complex64,tf.complex128,默认为int32(float32)
   
3.常量与变量    
constant ,无需初始化,运行过程中不会改变    
Variable,需要初始化,在运行过程中有可能改变。
name=tf.Variable(value,name)    init_op=name.initializer(),初始化变量name 				 init_op=tf.global_variables_initializer(),初始化前面定义的所有变量。这个操作是需要运行的。

sess=tf.Session()    
init=tf.global_variables_initializer() ,变量的初始化      
sess.run(init),需要运行才能初始化

4.变量的赋值    
var=tf.Variable(0,name='var',trainable=False),trainable=False指定某个变量在模型训练中不参加训练,默认为True.    
updata=tf.assign()variable_to_updated,new_value),人为更新变量的值
   
5.占位符(placeholder)    
对于定义时不知道其数值的变量,在程序运行过程中才知道值,这时候就需要用到占位符。    tf.placegolder(dtype,shape=None,name=None)
   
6.使用了占位符,在运行时我们通过Feed提交数据和Fetch提取运行数据
   
7.tensorBoard 可视化    
设置日志路径logdir的值,清除之前的计算图,写入计算图;    通过cmd窗口,输入命令:tensorboard --logdir=日志路径,然后通过该命令给出的链接,通过本机浏览器访问,即localhost:端口号。'''

#1.基本模型

#导入tensorflow 模块

import tensorflow.compat.v1 as tf
#创建一个常量,会作为一个节点加入计算图中
Model = tf.constant("Hello World")
#创建一个会话
sess = tf.Session()
#运行计算图,得到结果
print(sess.run(Model))
#关闭会话,释放资源
sess.close()
#tensorflow是通过计算图的形式表述计算的编程系统,每个计算都是计算图上的一个一个节点,节点之间的边描述了计算之间的关系。

node1=tf.constant(3.0,tf.float32,name="node1")
node2=tf.constant(3.0,tf.float32,name="node2")
node3 = tf.add(node1, node2)
sess = tf.Session()
print(node3)
print(sess.run(node3))
sess.close()

#创建一个张量,获取它的维度
scalar = tf.constant(50)
vector = tf.constant([1, 2, 3, 4, 5, 6, 7, 8, 9])
matrix = tf.constant([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

print(scalar.get_shape())#shape=()
print(vector.get_shape())#shape=(9,)
print(matrix.get_shape())#shape=(3, 3)

#获取张量的元素值,通过下标直接访问
sess = tf.Session()
print(sess.run(matrix[1][2]))
sess.close()

#清除缺省计算图
tf.reset_default_graph()
a = tf.Variable(1, name="a")
b = tf.add(a,2, name="b")
c = tf.multiply(b, 3, name="c")
d = tf.subtract(c, b, name="d")

#可视化计算图,并写入日志
logdir = "E:/VSCODE/"
if tf.gfile.Exists(logdir):
    tf.gfile.DeleteRecursively(logdir)
writer =tf.summary.FileWriter(logdir, tf.get_default_graph())
writer.close()


#为了保证系统资源的正常释放,即使出现错误,也会释放掉系统资源,保证稳定性
s=tf.constant([1,2,3,4,5,6,7,8,9])
sess=tf.Session()
try:
    print(sess.run(s))
except:
    print(" Process Exception. ")
#程序一点会执行这句,而释放资源
finally:
   sess.close()

#或者通过with来自动管理
s=tf.constant([1,2,3,4,5,6,7,8,9])
with tf.Session() as sess:
    print(sess.run(s))

r=tf.constant([1,2,3,4,5,6,7,8,9])
sess=tf.Session()
with sess.as_default():#手动指定默认的会话
    print(r.eval())#通过eval来计算张量的值


#InteractiveSession将生成的会话自动注册为默认会话
node1=tf.constant(3.0,tf.float32,name="node1")
node2=tf.constant(3.0,tf.float32,name="node2")
node3 = tf.add(node1, node2)

sess=tf.InteractiveSession()
print(node3.eval())
sess.close()

#常量与变量相关操作
value = tf.Variable(0, name="value")
one = tf.constant(1)
new_value = tf.add(value, one)
up_value = tf.assign(value, new_value)
init = tf.global_variables_initializer()

#打印,更新值
with tf.Session() as sess:
    sess.run(init)              #变量初始化
    for _ in range(10):
        sess.run(up_value)      #变量值更新
        print(sess.run(value))  #输出变量值

#为变量x占位,3x2矩阵,值为float32类型
x = tf.placeholder(tf.float32, [3, 2], name='X')

#数据的提交和提取(Feed/Fetch)
x1 = tf.placeholder(tf.float32, name='x1')
x2 = tf.placeholder(tf.float32, name='x2')
y = tf.multiply(x1, x2, name='y')
z = tf.subtract(x1, x2, name='z')

init = tf.global_variables_initializer()

with tf.Session() as sess:
    sess.run(init)
    r1 = sess.run(y, feed_dict={x1: 9.1, x2: 1.9})
    r2 = sess.run([y, z], feed_dict={x1: [1.0, 2.0, 3.0], x2: [4.0, 5.0, 6.0]})
    '''y,z = sess.run([y, z], feed_dict={x1: [1.0, 2.0, 3.0], x2: [4.0, 5.0, 6.0]})'''
    
    print("y=",r1)
    print("y=",r2[0])
    print("z=",r2[0])

在这里插入图片描述
cmd命令输入,注意切换到日志目录下
在这里插入图片描述
代码中设置的计算图如下
在这里插入图片描述
遇到的错误:
1.SyntaxError: Non-UTF-8 code starting with ‘\xd6’ in file e:\VS实验项目文件\Project\Python\main.py on line 4, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details

主要是编码的问题,vscode 默认的是gbk编码,设置#coding=gbk即可。
2.W0105 11:09:45.861135 9504 deprecation_wrapper.py:119] From e:\VS实验项目文件\Project\Python\main.py:77: The name tf.reset_default_graph is deprecated. Please use tf.compat.v1.reset_default_graph instead.
解决办法:import tensorflow.compat.v1 as tf
3.TypeError: Fetch argument <tensorflow.python.client.session.Session object at 0x0000026C0A7A9A20> has invalid type <class ‘tensorflow.python.client.session.Session’>, must be a string or Tensor. (Can not convert a Session into a Tensor or Operation.),有问题的代码如下:
Model = tf.constant(“Hello World”)
#创建一个会话
sess = tf.Session()
#运行计算图,得到结果
print(sess.run(sess))
#关闭会话,释放资源
sess.close()
这主要是print(sess.run(sess))写错了,只需要改为print(sess.run(Model )),注意运行的是计算模型。还有一些拼写错误,要是不注意啊,真的头疼。

附:本文章学习至中国大学mooc-深度学习应用开发-Tensorflow实战,感谢吴老师。

发布了89 篇原创文章 · 获赞 8 · 访问量 8873

猜你喜欢

转载自blog.csdn.net/TxyITxs/article/details/103840929