本章内容:
graph的三种声明和三种常用方法
Saver的使用:保存和恢复模型
tf.squeeze():用于压缩张量中为1的轴---除去张量中形状为1的轴
tf.expand_dims():增加一个维度
tf.image.decode_jpeg:图像解码---把图像还原成矩阵形式
tf.image.encode_jpeg:图像编码---把矩阵压缩保存成图像
set_shape()和reshape()的区别
tf.concat、tf.gather、tf.greater
set()、np.dot()、zip()、argmax
tf的等差数列、切片、生成矩阵
tf.norm、tf.truncated_normal、tf.random_normal、tf.nn.l2_loss
graph的三种定义:
1.直接用
2.先设定一个默认的,然后再调用
3.声明多个不同的graph,可以通过变量名分开调用
# #1.1 graph的定义1:直接出graph
# import tensorflow as tf
# c = tf.constant(4.0)
# sess = tf.Session()
# sess.run(tf.global_variables_initializer())
# c_out = sess.run(c)
# print(c_out)
# print(c.graph == tf.get_default_graph())
# print(c.graph)
# print(tf.get_default_graph())
# #1.2 graph的定义2:通过声明一个默认的,然后定义张量内容,在后面可以调用或保存
# import tensorflow as tf
# g = tf.Graph()
# with g.as_default():
# c = tf.constant(4.0)
# sess = tf.Session(graph=g)
# c_out = sess.run(c)
# print(c_out)
# print(g)
# print(tf.get_default_graph())
# #1.3 graph的定义3:通过声明一个默认的,然后定义张量内容,在后面可以调用或保存
# import tensorflow as tf
# g1 = tf.Graph()
# with g1.as_default():
# c1 = tf.constant(4.0)
# g2 = tf.Graph()
# with g2.as_default():
# c2 = tf.constant(20.0)
# with tf.Session(graph=g1) as sess1:
# print(sess1.run(c1))
# with tf.Session(graph=g2) as sess2:
# print(sess2.run(c2))
# #2.1 graph的常见用法1:保存
# import tensorflow as tf
# g1 = tf.Graph()
# with g1.as_default():
# # 需要加上名称,在读取pb文件的时候,是通过name和下标来取得对应的tensor的
# c1 = tf.constant(4.0, name='c1')
# g2 = tf.Graph()
# with g2.as_default():
# c2 = tf.constant(20.0)
# with tf.Session(graph=g1) as sess1:
# print(sess1.run(c1))
# with tf.Session(graph=g2) as sess2:
# print(sess2.run(c2))
# tf.train.write_graph(g1.as_graph_def(),'.','img/graph.pb',False) #把上面的计算流图,保存到一个pb文件中
# #2.2 graph的常见用法2:从pb文件中调用
# import tensorflow as tf
# from tensorflow.python.platform import gfile
# with gfile.FastGFile("img/graph.pb",'rb') as f: #可以从上面保存的pb文件中,调用刚才定义的c1
# 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)
# print(c1)
#2.3 graph的常见用法3:穿插调用
import tensorflow as tf
g1 = tf.Graph()
with g1.as_default():
c1 = tf.constant(4.0, name="c1")
g2 = tf.Graph()
with g2.as_default():
c2 = tf.constant(20.0, name="c2")
with tf.Session(graph=g2) as sess1:
# 通过名称和下标来得到相应的值,此处调用了g1中的c1
c1_list = tf.import_graph_def(g1.as_graph_def(), return_elements = ["c1:0"], name = '')
print(sess1.run(c1_list[0]+c2)) #把g1中的c1和g2的c2相加
Saver的使用:保存和恢复模型
恢复:可以选择载入迭代次数或者默认最新
import tensorflow as tf
#例1:没载入模型时,不必指定迭代次数,一般默认最新
saver = tf.train.Saver(max_to_keep=1)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
saver.restore(sess,checkpoint_path) # 自动恢复model_checkpoint_path保存模型一般是最新
#例2:载入时,指定想要载入模型的迭代次数
with tf.Session() as sess:
saver.restore(sess, './log/' + "model_savemodel.cpkt-" + str(111000))
sess.run(tf.global_variables_initializer())
#保存训练模型
with tf.Session() as sess:
save_path = saver.save(sess, checkpoints_dir + "/model.ckpt", global_step=step)
tf.squeeze():用于压缩张量中为1的轴---除去张量中形状为1的轴
tf.expand_dims():增加一个维度
#2.tf.squeeze
import tensorflow as tf
raw = tf.Variable(tf.random_normal(shape=(1, 3, 2)))
squeezed = tf.squeeze(raw)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(raw.shape)
print(sess.run(squeezed).shape)
#3.tf.expand_dims():维度增加一维
import tensorflow as tf
a=tf.constant([[1,2,5],[2,3,3]])
b=tf.expand_dims(a, -1)
with tf.Session() as sess:
sess.run(b)
print(a)
print(b)
tf.image.decode_jpeg:图像解码---把图像还原成矩阵形式
tf.image.encode_jpeg:图像编码---把矩阵压缩保存成图像
#4.图像编码解码
import matplotlib.pyplot as plt
import tensorflow as tf
image_raw_data = tf.gfile.FastGFile("img/a.jpg", "rb").read()
with tf.Session() as sess:
img_data = tf.image.decode_jpeg(image_raw_data)
print (img_data.eval())
plt.imshow(img_data.eval())
plt.show()
encoded_image = tf.image.encode_jpeg(img_data)
with tf.gfile.GFile("img/a2.jpg","wb") as f:
f.write(encoded_image.eval())
set_shape()和reshape()的区别:
set_shape:只能改变数值没办法直接改变维度值
reshape:可以改变原有tensor的shape
import tensorflow as tf
x1 = tf.placeholder(tf.int32)
x2 = tf.reshape(x1, [2,2]) #更新x1的维度,变成2*2的张量
print(x1.get_shape())
sess = tf.Session()
print(sess.run(tf.shape(x2), feed_dict={x1:[0,1,2,3]})) #设x1初始化为1*4的,经过x2的reshape后,更新变成了2*2
print(sess.run(tf.shape(x2), feed_dict={x1:[[0,1],[2,3]]})) #同上
#4.2 set_shape:只能改变数值,没办法直接改变维度值
import tensorflow as tf
x1 = tf.placeholder(tf.int32)
x1.set_shape([2,3])
print(x1.get_shape())
sess = tf.Session()
print(sess.run(tf.shape(x1), feed_dict={x1:[[0,1,1],[2,1,3]]})) #只能把2*3的数值进行更改,没办法改成其他维度的. 如:3*3
1.tf.concat:把一组向量从某一维上拼接起来
2.tf.gather:可以把向量中元素,按索引的形式提取出来,得到新的向量
ps:一维的话,按下标取元素 多维的,则是按下标取行数
3.tf.greater:判断函数。首先张量x和张量y的尺寸要相同,输出的tf.greater(x, y)也是一个和x,y尺寸相同的张量。如果x的某个元素比y中对应位置的元素大,则tf.greater(x, y)对应位置返回True,否则返回False。
#1.tf.concat——把一组向量从某一维上拼接起来
import tensorflow as tf
t1 = [[1, 2, 3], [4, 5, 6]] #2*3
t2 = [[7, 8, 9], [10, 11, 12]] #2*3
t3=tf.concat([t1, t2], 0) #横向拼接,4*3
t4=tf.concat([t1, t2], 1) #纵向拼接,2*6
with tf.Session() as sess:
print("t3:",sess.run(t3))
print("t4:",sess.run(t4))
#2.1 tf.gather——可以把向量中元素,按索引的形式提取出来,得到新的向量
#ps:一维的话,按下标取元素 多维的,则是按下标取行数
import tensorflow as tf
#多维的情况
a = tf.Variable([[1,2,3,4,5], [6,7,8,9,10], [11,12,13,14,15]]) #维度:3*5,三行五列
index_a = tf.Variable([0,2]) #提取下标为0、2的行,即第一行和第三行
#一维的情况
b = tf.Variable([1,2,3,4,5,6,7,8,9,10]) #共有10个元素
index_b = tf.Variable([2,4,6,8]) #提取下标为2、4、6、8的元素
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(sess.run(tf.gather(a, index_a)))
print(sess.run(tf.gather(b, index_b)))
#2.2 tf.gather_nd——多维情况下,取某个元素
import tensorflow as tf
a = tf.Variable([[1,2,3,4,5], [6,7,8,9,10], [11,12,13,14,15]]) #维度:3*5,三行五列
index_a = tf.Variable([[0,2], [0,4], [2,2]]) #提取第0行的第2、4个数,第2行的第2个数 (以下标为准)——[3 5 13]
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(sess.run(tf.gather_nd(a, index_a)))
#3.tf.greater 判断函数,对比两个矩阵的元素大小
#如果x的某个元素比y中对应位置的元素大,则tf.greater(x, y)对应位置返回True,否则返回False。
import tensorflow as tf
x = tf.Variable([[1,2,3], [6,7,8], [11,12,13]])
y = tf.Variable([[0,1,2], [5,6,7], [10,11,12]])
x1 = tf.Variable([[1,2,3], [6,7,8], [11,12,13]])
y1 = tf.Variable([[10,1,2], [15,6,7], [10,21,12]])
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print(sess.run(tf.greater(x, y)))
print(sess.run(tf.greater(x1, y1)))
1.tf.shape():获取目标的大小,包括array、list、tensor等
2.get_shape():获取张量的大小,并且只有tensor才可以使用这种方法,返回的是一个元组。
3.get_shape().as_list():用于把get_shape()的元组转化为list形式
# # 1.f.shape():获取目标的大小,包括array、list、tensor等
# import tensorflow as tf
# import numpy as np
# a_array=np.array([[1,2,3],[4,5,6]]) #array
# b_list=[[1,2,3],[3,4,5]] #list
# c_tensor=tf.constant([[1,2,3],[4,5,6]]) #tensor
# with tf.Session() as sess:
# print(sess.run(tf.shape(a_array)))
# print(sess.run(tf.shape(b_list)))
# print(sess.run(tf.shape(c_tensor)))
# 2.get_shape():获取张量的大小,只有tensor才可以使用这种方法,返回的是一个元组
# 3.get_shape().as_list():用于把get_shape()的元组转化为list形式
import tensorflow as tf
import numpy as np
a_array=np.array([[1,2,3],[4,5,6]]) #array
b_list=[[1,2,3],[3,4,5]] #list
c_tensor=tf.constant([[1,2,3],[4,5,6]]) #tensor
# print(a_array.get_shape()) #获取array的大小将会报错
# print(b_list.get_shape()) #获取list的大小将会报错
print(c_tensor.get_shape()) #获取tensor的大小,返回元组:(2,3)
print(c_tensor.get_shape().as_list()) #转化为list:[2,3]
1.set():创建一个无序不重复元素集; 可进行交集、并集、差集等操作
2.np.dot():主要有两个功能,向量点积和矩阵乘法
3.zip():把几个元组按列来打包压缩
4.argmax:可以返回最大值得索引值 多维度情况,axis=0代表按列寻找最大值的下标,axis=1是按行寻找
# 1.1 set():创建一个无序不重复元素集
list1=[1,2,3,4,3]
s=set(list1)
print(s)
s.add(4) #加一个元素
s.add(5) #加一个元素
print(s)
#1.2 :进行交集、并集、差集等操作
l1=set([1,2])
l2=set([2,3])
print(l1 & l2) #交集
print(l1 | l2) #并集
print(l1 - l2) #差集
#2.1 np.dot():向量点积---等于各个数相乘
import numpy as np
a = np.array([1, 2, 3, 4, 5])
b = np.array([6, 7, 8, 9, 10])
print(np.dot(a, b))
#2.2 np.dot():矩阵乘法-例1
import numpy as np
a = np.random.randint(0,10, size = (5,5))
b = np.array([1,2,3,4,5])
print("the shape of a is " + str(a.shape))
print("the shape of b is " + str(b.shape))
print("矩阵相乘得:",np.dot(a, b)) #[5,5]*[5,1]=[5*1]
#2.3 np.dot():矩阵乘法-例2
import numpy as np
a = np.random.randint(0, 10, size = (5, 5))
b = np.random.randint(0, 10, size = (5, 3))
print("the shape of a is " + str(a.shape))
print("the shape of b is " + str(b.shape))
print(np.dot(a, b)) #[5,5]*[5,3]=[5*3]
#3.1 zip():把几个元组按列来打包压缩
ta = [1,2,3]
tb = [9,8,7]
tc = ['a','b','c']
(a,b,c)=zip(ta,tb,tc)
print(a,b,c)
#3.2 zip()配合*号操作符,可以将已经zip过的列表对象解压
ta = [1,2,3]
tb = [9,8,7]
tc = ['a','b','c']
(a,b,c)=zip(ta,tb,tc)
print(zip(*(a,b,c)))
#4.1 argmax:可以返回最大值得索引值
import numpy as np
a = np.array([3, 1, 2, 4, 6, 1])
print(np.argmax(a))
#4.2 多维度情况,axis=0代表按列寻找最大值的下标,axis=1是按行寻找
import numpy as np
a = np.array([[1, 5, 5, 2],
[9, 6, 2, 8],
[3, 7, 9, 1]])
print(np.argmax(a, axis=0))
1.tf.range:生成等差数列
2.tf.linspace:把某一浮点数范围平均划分n份
3.tf.slice:切片,截取数组的一部分 tf.slice(a,m,n):从下标m开始,连续截取的n个数
4.tf.zeros:可以生成全0的矩阵,不指定类型时,默认为float32.
5.tf.ones:可以生成全1的矩阵
6.tf.fill:将矩阵全部设成一个值
# #1.range:生成等差数列
# import tensorflow as tf
# b11 = tf.range(1,100,1)
# with tf.Session() as sess:
# print(sess.run(b11))
#2.linspace:把某一浮点数范围平均划分n份
import tensorflow as tf
b11 = tf.linspace(1.0,100.0,4) #把1-100平均分成4份
with tf.Session() as sess:
print(sess.run(b11))
# #3.tf.slice:切片,截是取数组的一部分
# import tensorflow as tf
# b1 = tf.range(1,10,1)
# b2 = tf.slice(b1, [2],[3]) #从下标2开始,连续截取的3个数
# with tf.Session() as sess:
# print(sess.run(b2))
# #4.tf.zeros:可以生成全0的矩阵,不指定类型时,默认为float32.
# import tensorflow as tf
# gg = tf.zeros([4,5])
# with tf.Session() as sess:
# print(sess.run(gg))
# #5.tf.ones:可以生成全1的矩阵
# import tensorflow as tf
# gg = tf.ones([4,5])
# with tf.Session() as sess:
# print(sess.run(gg))
# #6.tf.fill:将矩阵全部设成一个值
# import tensorflow as tf
# gg = tf.fill([4,5],0.8)
# with tf.Session() as sess:
# print(sess.run(gg))
1.tf.norm:范数,即欧基里得距离 相当于:所有的值的平方和的平方根
2.tf.truncated_normal():产生服从正态分布的随机数字
3.tf.random_normal():产生服从正态分布的随机数字(截断了一些数值,而被删减的数值是均值加减两个标准差以外的数值)
4.tf.nn.l2_loss(t):利用 L2 范数来计算张量的误差值,但是没有开方并且只取 L2 范数的值的一半。
公式:output = sum(t ** 2) / 2
# #1.tf.norm:范数,即欧基里得距离 相当于:所有的值的平方的和的平方根
# import tensorflow as tf
# import numpy as np
# a = tf.constant([1,2,3,4],dtype=tf.float32)
# with tf.Session() as sess:
# print("欧基里得距离:",sess.run(tf.norm(a, ord='euclidean')))
# print("等价于:",np.sqrt(1*1+2*2+3*3+4*4))
# #2.tf.truncated_normal():产生服从正态分布的随机数字
# #3.tf.random_normal():产生服从正态分布的随机数字
# #ps:其实两个功能一样,但是前者(truncated_normal)截断了一些数值,被删减的数值是均值加减两个标准差以外的数值)
# import tensorflow as tf
#
# a = tf.Variable(tf.random_normal(shape=[3,3],mean=0.0, stddev=1.0))
# b = tf.Variable(tf.truncated_normal(shape=[3,3],mean=0.0, stddev=1.0))
# init = tf.global_variables_initializer()
# with tf.Session() as sess:
# sess.run(init)
# print("random_normal:")
# print(sess.run(a))
# print("truncated_normal:")
# print(sess.run(b))
# 4.tf.nn.l2_loss(t):利用 L2 范数来计算张量的误差值,但是没有开方并且只取 L2 范数的值的一半。
# 公式:output = sum(t ** 2) / 2
import tensorflow as tf
a=tf.constant([1,2,3],dtype=tf.float32)
b=tf.constant([[1,1],[2,2],[3,3]],dtype=tf.float32)
with tf.Session() as sess:
print('a:')
print(sess.run(tf.nn.l2_loss(a)))
print('b:')
print(sess.run(tf.nn.l2_loss(b)))
sess.close()