TensorFlow学习知识点总结

tf.equal()函数

tensorflow 中tf.equal()用法:

1
tf.equal(A, B,name=None)

  • 对于单个变量,如果A==B,则返回true,否则返回false;
  • 对于数组,会迭代的比较A[i]和B[i],对应相等的则返回true,否则返回false
      是对比这两个矩阵或者向量的相等的元素,如果是相等的那就返回True,否则返回False,返回的值的矩阵维度和A是一样的
      equal,相等的意思。顾名思义,就是判断,A, B 是不是相等,它的判断方法不是整体判断,
      而是逐个元素进行判断,如果相等就是True,不相等,就是False。
      由于是逐个元素判断,所以A,B 的维度要一致。
    1
    2
    3
    4
    5
    6
    7
    8
    import tensorflow as tf
    import numpy as np

    A = [[1,3,4,5,6]]
    B = [[1,3,4,3,2]]

    with tf.Session() as sess:
    print(sess.run(tf.equal(A, B)))

输出:
  [[ True True True False False]]

tf.cast()函数

tf.cast(a, dtype=tf.float32)
将a的类型转换成tf.float32

1
2
3
4
5
6
7
8
import tensorflow as tf
a = [1, 2, 3]
b = [1, 5, 3]
sess = tf.Session()
with sess.as_default():
acc = sess.run(tf.equal(a, b))
print(acc)  
print(sess.run(tf.reduce_mean(tf.cast(acc, dtype=tf.float32))))

运行结果如下图所示:

1
2
[True, False, True]
0.6666667

代码解释:
假设a是输入的y_hat, b是预测的y
  tf.equal(a, b)会比较每一个y和y_hat 是否相等
  tf.cast(acc, dtype=tf.float32)将比较的结果转换成tf.float32类型
  tf.reduce_mean()求所有tf.float32类型结果的均值

tf.argmax()函数

tf.argmax(vector, 1)

  返回的是vector中的最大值的索引号,如果vector是一个向量,那就返回一个值,如果是一个矩阵,那就返回一个向量,这个向量的每一个维度都是相对应矩阵行的最大值元素的索引号。

1
2
3
4
5
6
7
8
9
import tensorflow as tf
import numpy as np

A = [[1,3,4,5,6]]
B = [[1,3,4], [2,4,1]]

with tf.Session() as sess:
print(sess.run(tf.argmax(A, 1)))
print(sess.run(tf.argmax(B, 1)))

运行结果:

1
2
3
(tf14) zhangkf@Ubuntu2:~/lenet5$ python one.py 
[4]
[2 1]

tf.equal()

tf.equal(A, B)是对比这两个矩阵或者向量的相等的元素,如果是相等的那就返回True,否则返回False,返回的值的矩阵维度和A是一样的

1
2
3
4
5
6
7
8
import tensorflow as tf
import numpy as np

A = [[1,3,4,5,6]]
B = [[1,3,4,3,2]]

with tf.Session() as sess:
print(sess.run(tf.equal(A, B)))

运行结果:

1
2
(tf14) zhangkf@Ubuntu2:~/lenet5$ python one.py 
[[ True True True False False]]

1
2
3
4
5
6
7
8
import tensorflow as tf
import numpy as np

A = [[1,3,4,5,6],[1,2,3,4,5]]
B = [[1,3,4,3,2],[2,2,3,4,3]]

with tf.Session() as sess:
print(sess.run(tf.equal(A, B)))

运行结果:

1
2
3
(tf14) zhangkf@Ubuntu2:~/lenet5$ python one.py 
[[ True True True False False]
[False True True True False]]

二者结合起来

在测试模型的准确率的时候,通常二者结合在一起。

1
2
correct_prediction=tf.equal(tf.getmax(y,1),tf.getmax(y_,1))
accuracy=tf.reduce_mean(tf.cast(corrcet_prediction,tf.float32))#求平均获取准确率

tf.argmax 与 tf.arg_max

tf.argmax 与 tf.arg_max 用法相同,下面介绍 tf.argmax 用法

tf.argmax

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def argmax(input,
axis=None,
name=None,
dimension=None,
output_type=dtypes.int64)
numpy.argmax(a, axis=None, out=None)
返回沿轴axis最大值的索引。

Parameters:
input: array_like,数组
axis : int, 可选,默认情况下,索引的是平铺的数组,否则沿指定的轴。
out : array, 可选 如果提供,结果以合适的形状和类型被插入到此数组中。

Returns:
index_array : ndarray of ints
索引数组。它具有与a.shape相同的形状,其中axis被移除。

tf.argmax() 与 numpy.argmax() 方法的用法是一致的

axis = 0 的时候返回每一列最大值的位置索引
axis = 1 的时候返回每一行最大值的位置索引
axis = 2、3、4 …,即为多维张量时,同理推断

例子

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
>>> a = np.arange(6).reshape(2,3)
>>> a
array([[0, 1, 2],
[3, 4, 5]])
>>> np.argmax(a)
5
>>> np.argmax(a, axis=0) #0代表列
array([1, 1, 1])
>>> np.argmax(a, axis=1) #1代表行
array([2, 2])
>>>
>>> b = np.arange(6)
>>> b[1] = 5
>>> b
array([0, 5, 2, 3, 4, 5])
>>> np.argmax(b) #只返回第一次出现的最大值的索引
1

tf.arg_max()

  The following is the source code of argmax
  (from https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/ops/math_ops.py).

1
2
3
4
5
6
7
8
9
10
# pylint: disable=redefined-builtin
# TODO(aselle): deprecate arg_max
def argmax(input, axis=None, name=None, dimension=None):
if dimension is not None:
if axis is not None:
raise ValueError("Cannot specify both 'axis' and 'dimension'")
axis = dimension
elif axis is None:
axis = 0
return gen_math_ops.arg_max(input, axis, name)

  As you can see, argmax is using arg_max inside. Also from the code, I recommend using argmax because arg_max could be deprecated soon.

Python获取文件夹下的文件和子文件夹
笔者小白在写代码的时候遇到的这样的问题,就是说需要根据文件夹的路径获取该文件夹下面的所有的文件和子文件夹。这里就介绍python的os模块中的两个函数:os.walk() 、os.listdir()。

os.walk()

该函数的原型是:

1
os.walk(top, topdown=Ture, onerror=None, followlinks=False)

该函数没有返回值。

1
2
3
4
5
参数
1. top -- 根目录下的每一个文件夹(包含它自己), 产生3-元组 (dirpath, dirnames, filenames)【文件夹路径, 文件夹名字, 文件名】。
2. topdown --可选,为True或者没有指定, 一个目录的的3-元组将比它的任何子文件夹的3-元组先产生 (目录自上而下)。如果topdown为 False, 一个目录的3-元组将比它的任何子文件夹的3-元组后产生 (目录自下而上)。
3. onerror -- 可选,是一个函数; 它调用时有一个参数, 一个OSError实例。报告这错误后,继续walk,或者抛出exception终止walk。
4. followlinks -- 设置为 true,则通过软链接访问目录。

函数执行之后得到一个三元tupple(dirpath, dirnames, filenams。

  • dirpath:string,是当前目录的路径;
  • dirnames:list, 是当前路径下所有的子文件夹名字;
  • filenames:list, 是当前路径下所有的非目录子文件的名字。
    要获取完整的路径,dirnames和filenames是不包含路径信息的,可以使用
    1
    os.path.join(dirpath, dirnames)

获得文件的完整路径。
代码示例:

1
2
3
4
5
6
7
8
9
#!/usr/bin/python
# -*- coding: UTF-8 -*-

import os
for root, dirs, files in os.walk(".", topdown=False):
for name in files:
print(os.path.join(root, name))
for name in dirs:
print(os.path.join(root, name))

当需要特定类型的文件时,代码如下:

1
2
3
4
5
6
7
8
9
10
11
# -*- coding: utf-8 -*-   

import os

def file_name(file_dir):
L=[]
for dirpath, dirnames, filenames in os.walk(file_dir):
for file in filenames :
if os.path.splitext(file)[1] == '.jpg':
L.append(os.path.join(dirpath, file))
return L

其中os.path.splitext()函数将路径拆分为文件名+扩展名,例如os.path.splitext(“E:/lena.jpg”)将得到”E:/lena“+”.jpg”。

os.listdir()

os.listdir()函数返回指定路径下的文件和文件夹列表。
代码示例:

1
2
3
4
5
6
7
8
9
10
11
12
#!/usr/bin/python
# -*- coding: UTF-8 -*-

import os, sys

# 打开文件
path = "/var/www/html/"
dirs = os.listdir( path )

# 输出所有文件和文件夹
for file in dirs:
print file

python 遍历文件夹及子文件夹

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import os

def EnumPathFiles(path, callback):
if not os.path.isdir(path):
print('Error:"',path,'" is not a directory or does not exist.')
return
list_dirs = os.walk(path)

for root, dirs, files in list_dirs:
for d in dirs:
EnumPathFiles(os.path.join(root, d), callback)
for f in files:
callback(root, f)

def callbakc1(path, filename):
print(path+'\\'+filename)

if __name__ == '__main__':
EnumPathFiles(r'D:\Projects\python', callbakc1)

python 遍历目录(包括子目录)下所有文件

1
2
3
4
5
6
7
8
9
10
11
def list_all_files(rootdir):
import os
_files = []
list = os.listdir(rootdir) #列出文件夹下所有的目录与文件
for i in range(0,len(list)):
path = os.path.join(rootdir,list[i])
if os.path.isdir(path):
_files.extend(list_all_files(path))
if os.path.isfile(path):
_files.append(path)
return _files

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
_fs = list_all_files('./资料')
#将第一阶段的文件遍历出来
_k = filter(lambda x:re.compile(r'stage2.txt').search(x),_fs)
```

python 便利文件夹,返回所有文件夹及其子文件夹
``` python
# -*- coding: utf-8 -*-
# File Name:aa.py
# Author: biolxy
# E-mail:biolxy@aliyun.com
# Created Time:Wed 14 Mar 2018 07:06:03 PM PDT
# python getDir.py /home/user/soft 返回/home/user/soft 下所有文件夹及子文件夹名字
import os
import re
import sys

fistr_dir = os.path.abspath(sys.argv[1])
#print("fistr_dir is:\t{}".format(fistr_dir))
def get_all_dir_from_dir(dir):
# 遍历文件夹,输出文件夹及子文件夹
if os.path.exists(dir):
path_dir = os.path.abspath(dir)
for i in os.listdir(path_dir):
path_i = os.path.join(path_dir, i)
if os.path.isdir(path_i):
print(path_i)
get_all_dir_from_dir(path_i)

get_all_dir_from_dir(fistr_dir)
1
python getDir.py /home/user/soft

注意,如果你没有改文件夹的访问权限,改脚本无法显示该文件夹

来源:
从网上下载了一个听书课程,里边是按照时间顺序放在文件夹中,一级目录嵌套一级目录,具体的mp3文件放在三级目录中,通过编写py函数,实现对目录中文件的遍历并拷贝出指定的文件,此处是mp3文件。

编程思路:
人都是惰性了,刚想到这个问题,第一时间是简单的一层一层的遍历,但是问题是不知道多少层,同时希望程序有一定的健壮性。就想到了递归思想。

具体编程实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import os
import shutil

file = "D:/BaiduNetdiskDownload/2017-10"
todir = "C:/mp3File"

def searchMp3(path):
for item in os.listdir(path):
subFile = path+"/"+item
if os.path.isdir(subFile):
searchMp3(subFile)
else:
if os.path.splitext(subFile)[1] ==".mp3":
shutil.copy(subFile ,todir)
if __name__ == '__main__':
searchMp3(file)

假设FILE文件夹中有三个文件夹分别是file1,file2。file1中有文件夹sf1和sf2.file2中有sf3和sf4。sf1-4中分别各有一个MP3文件,分别是m1.mp3—-m4.mp3。

path是FILE路径。开始循环:

subFile = path/file1 因为subFile也是文件,此时把 subFile作为path传递给searchFile函数,记住,此时第一次循环还没有结束。此时path路径下面也有两个子文件,此时,subFile = path/file1/sf1。当然sf1也是文件,把此时的subFile当做参数传给searchMp3函数,记住,此时path/file下面还没有遍历完成。把path/file1/sf1当做path,此时,文件中有一个m1.mp3文件。不是文件夹,执行else语句,判断文件后缀是mp3则移动都指定目录。此时开始执行subFile = path/file1/sf2。同样的执行else语句。此时开始执行 subFile = path/file2同样的遍历过程。最后把所有的指定文件都遍历出来。如果还不理解,可以自己画图,更好的理解整个过程。

tf.one_hot()

tensorflow中tf.one_hot()函数的作用是将一个值化为一个概率分布的向量,一般用于分类问题。(参考地址)
具体用法以及作用见以下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
import numpy as np
import tensorflow as tf

SIZE=6
CLASS=8
label1=tf.constant([0,1,2,3,4,5,6,7])
sess1=tf.Session()
print('label1:',sess1.run(label1))
b = tf.one_hot(label1,CLASS,1,0)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
sess.run(b)
print('after one_hot',sess.run(b))

最后的输出为:

1
2
3
4
5
6
7
8
9
10
11
label1: [0 1 2 3 4 5 6 7]
after one_hot:

 [[1 0 0 0 0 0 0 0]
 [0 1 0 0 0 0 0 0]
 [0 0 1 0 0 0 0 0]
 [0 0 0 1 0 0 0 0]
 [0 0 0 0 1 0 0 0]
 [0 0 0 0 0 1 0 0]
 [0 0 0 0 0 0 1 0]
 [0 0 0 0 0 0 0 1]]

tf.one_hot()使用
(参考地址)tf.one_hot在看conditionGAN的时候注意到label的输入要把它转换成one-hot形式,再与噪声z进行tf.concat输入,之前看的时候忽略了,现在再看才算明白为什么。

1
2
3
4
5
6
7
8
9
tf.one_hot(
indices,#输入,这里是一维的
depth,# one hot dimension.
on_value=None,#output 默认1
off_value=None,#output 默认0
axis=None,#根据我的实验,默认为1
dtype=None,
name=None
)

代码示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import tensorflow as tf
import numpy as np
z=np.random.randint(0,10,size=[10])
y=tf.one_hot(z,10,on_value=1,off_value=None,axis=0)
with tf.Session()as sess:
print(z)
print(sess.run(y))


[5 7 7 0 5 5 2 0 0 0]
[[0 0 0 1 0 0 0 1 1 1]
[0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 1 0 0 0]
[0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]
[1 0 0 0 1 1 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]
[0 1 1 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 0]]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import tensorflow as tf
import numpy as np
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "2"
z=np.random.randint(0,10,size=[10])
y=tf.one_hot(z,10,on_value=1,off_value=None)
y1=tf.one_hot(z,10,on_value=1,off_value=None,axis=1)
with tf.Session()as sess:
print(z)
print(sess.run(y))
print("axis=1按行排", sess.run(y1))

[6 3 4 9 6 5 5 1 2 1]
[[0 0 0 0 0 0 1 0 0 0]
[0 0 0 1 0 0 0 0 0 0]
[0 0 0 0 1 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 1]
[0 0 0 0 0 0 1 0 0 0]
[0 0 0 0 0 1 0 0 0 0]
[0 0 0 0 0 1 0 0 0 0]
[0 1 0 0 0 0 0 0 0 0]
[0 0 1 0 0 0 0 0 0 0]
[0 1 0 0 0 0 0 0 0 0]]
axis=1按行排 [[0 0 0 0 0 0 1 0 0 0]
[0 0 0 1 0 0 0 0 0 0]
[0 0 0 0 1 0 0 0 0 0]
[0 0 0 0 0 0 0 0 0 1]
[0 0 0 0 0 0 1 0 0 0]
[0 0 0 0 0 1 0 0 0 0]
[0 0 0 0 0 1 0 0 0 0]
[0 1 0 0 0 0 0 0 0 0]
[0 0 1 0 0 0 0 0 0 0]
[0 1 0 0 0 0 0 0 0 0]]

感觉实际用的时候可以不传入axis值。可以看到经过one-hot的处理,输入的维度变成了10×depth,值也变成了0和1.

下面说在condition GAN中要输入标签信息y,怎样处理的。
y是mnist的标签值,0和10之间的整数,尺寸为[BATCH],经过one-hot处理后维度变成了[BATCH,10]值也是0和1,此时再与噪声z按列(axis=1)连接,变成条件GAN的输入。因此one-hot操作是必须的,这个处理在infoGAN中将z,categorical latent code、continuous latent code连接在一起输入也要用到。

1
2
3
y = tf.one_hot(y, 10, name='label_onehot')
z = tf.random_uniform([BATCH, 100], -1, 1, name='z_train')
tf.concat([z, y], 1)

参考3】tensorflow中将label索引转换成one-hot形式

1
2
3
4
5
6
7
8
import tensorflow as tf
index=[0,1,2,3]
one_hot=tf.one_hot(index,5)

with tf.Session() as sess:
sess.run(tf.global_variables_initializer())

print(sess.run(one_hot))

1
2
3
4
5
[[0. 1. 0. 0. 0.]
[0. 0. 1. 0. 0.]
[0. 0. 0. 1. 0.]
[0. 0. 0. 0. 1.]
]
------------------------ The End ------------------------
0%