1、tf.shape()和x.get_shape().as_list()的使用
(1) tf.shape()
先说tf.shape()很显然这个是获取张量的大小的,用法无需多说,直接上例子吧!
import tensorflow as tf
import numpy as np
a_array=np.array([[1,2,3],[4,5,6]])
b_list=[[1,2,3],[3,4,5]]
c_tensor=tf.constant([[1,2,3],[4,5,6]])
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)x.get_shape().as_list()
这个简单说明一下,x.get_shape(),只有tensor才可以使用这种方法,返回的是一个元组。
import tensorflow as tf
import numpy as np
a_array=np.array([[1,2,3],[4,5,6]])
b_list=[[1,2,3],[3,4,5]]
c_tensor=tf.constant([[1,2,3],[4,5,6]])
print(c_tensor.get_shape())
print(c_tensor.get_shape().as_list())
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)))
结果:可见只能用于tensor来返回shape,但是是一个元组,需要通过as_list()的操作转换成list.
2、tf.get_variable()和tf.Variable()的区别
tf.get_variable(name, shape, initializer): name就是变量的名称,shape是变量的维度,initializer是变量初始化的方式,
3、tf.nn.bias_add和tf.add、tf.add_n
Args:
x: A `Tensor`. Must be one of the following types: `bfloat16`, `half`, `float32`, `float64`, `uint8`, `int8`, `int16`, `int32`, `int64`, `complex64`, `complex128`, `string`.
y: A `Tensor`. Must have the same type as `x`.
name: A name for the operation (optional).
Returns:
A `Tensor`. Has the same type as `x`.
2) tf.nn.bias_add(value, bias, data_format=None, name=None)
Adds `bias` to `value`.
This is (mostly) a special case of `tf.add` where `bias` is restricted to 1-D. Broadcasting is supported, so `value` may have any number of dimensions. Unlike `tf.add`, the type of `bias` is allowed to differ from `value` in the case where both types are quantized.
Args:
value: A `Tensor` with type `float`, `double`, `int64`, `int32`, `uint8`, `int16`, `int8`, `complex64`, or `complex128`.
bias: A 1-D `Tensor` with size matching the last dimension of `value`. Must be the same type as `value` unless `value` is a quantized type, in which case a different quantized type may be used.
data_format: A string. 'NHWC' and 'NCHW' are supported.
name: A name for the operation (optional).
Returns:
A `Tensor` with the same type as `value`.
3)tf.add_n(inputs,name=None)
函数是实现一个列表的元素的相加。就是输入的对象是一个列表,列表里的元素可以是向量,
4)tf.add 和 tf.nn.bias_add 的区别
- tf.nn.bias_add 是 tf.add 中的一个特例,tf.nn.bias_add 中 bias 一定是 1 维的张量;
- tf.nn.bias_add 中 value 最后一维长度和 bias 的长度一定得一样;
- tf.nn.bias_add 中,当 value 是 quantized type 时,bias 可以取不同的 quantized type。但什么是 quantized type?TensorFlow API 中 tf.DType 页面显示,’tf.qint8’、’tf.quint8’、’tf.qint16’、’tf.quint16’、’tf.qint32’类型就是Quantized type。但这些类别具体如何使用并不知晓。
- tf.add(tf.matmul(x, w), b)
- tf.matmul(x, w) + b
4、tf.nn.bias_add和tf.add、tf.add_n
tf.nn.relu(features, name = None)
max(features, 0)将矩阵中每行的非最大值置0
5、tf.nn.bias_add和tf.add、tf.add_n
tf.nn.max_pool(value, ksize, strides, padding, name=None)
参数是四个,和卷积很类似:
第一个参数value:需要池化的输入,一般池化层接在卷积层后面,所以输入通常是feature map,依然是[batch, height, width, channels]这样的shape
第二个参数ksize:池化窗口的大小,取一个四维向量,一般是[1, height, width, 1],因为我们不想在batch和channels上做池化,所以这两个维度设为了1
第三个参数strides:和卷积类似,窗口在每一个维度上滑动的步长,一般也是[1, stride,stride, 1]
第四个参数padding:和卷积类似,可以取'VALID' 或者'SAME'
返回一个Tensor,类型不变,shape仍然是[batch, height, width, channels]这种形式
6、 tf.reshape
源码:x_image = tf.reshape(x, [-1, 28, 28, 1])这里是将一组图像矩阵x重建为新的矩阵,该新矩阵的维数为(a,28,28,1),其中-1表示a由实际情况来定。
例如,x是一组图像的矩阵(假设是50张,大小为56×56),则执行x_image = tf.reshape(x, [-1, 28, 28, 1])可以计算a=50×56×56/28/28/1=200。即x_image的维数为(200,28,28,1)。
7、tf.nn.softmax(logits,axis=None,name=None,dim=None)
通过Softmax回归,将logistic的预测二分类的概率的问题推广到了n分类的概率的问题。通过公式
可以看出当月分类的个数变为2时,Softmax回归又退化为logistic回归问题。
下面的几行代码说明一下用法
import tensorflow as tf
A = [1.0,2.0,3.0,4.0,5.0,6.0]
with tf.Session() as sess:
print sess.run(tf.nn.softmax(A))
结果
[ 0.00426978 0.01160646 0.03154963 0.08576079 0.23312201 0.63369131]
其中所有输出的和为1
softmax = tf.exp(logits) / tf.reduce_sum(tf.exp(logits), axis)
- logits:
A non-empty Tensor. 一个非空张量
Must be one of the following types: half, float32, float64.必须是以下类型之一:half, float32, float64 - axis:
The dimension softmax would be performed on. 将被执行的softmax维度
The default is -1 which indicates the last dimension.默认值是-1,表示最后一个维度。 - name:
A name for the operation (optional).操作的名称(可选)。 - dim:
Deprecated alias for axis. 弃用,axis的别名
8、 tf.argmax() 函数, tf.equal()函数, tf.cast()函数, tf.truncated_normal()
1). tf.argmax()函数
tf.argmax可以认为就是np.argmax。tensorflow使用numpy实现的这个API。
简单的说,tf.argmax就是返回最大的那个数值所在的下标。tf.argmax(array,axis)
当axis=1时返回每列最大值的下标,当axis=0时返回每行最大值的下班。
2). tf.equal()函数
tf.equal(A,B)是对比这两个矩阵或者向量的相等的元素,如果是相等的那就返回True,反正返回False,返回的值的矩阵维度和A是一样的
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]]
3). tf.cast()函数
tf.cast(x, dtype)将x的数据格式转化成dtype.
cast(x,dtype,name=None)
将x的数据格式转化成dtype.例如,原来x的数据格式是bool,
那么将其转化成float以后,就能够将其转化成0和1的序列。反之也可以
a = tf.Variable([1,0,0,1,1])
b = tf.cast(a,dtype=tf.bool)
sess = tf.Session()
a = tf.Variable([1,0,0,1,1])
b = tf.cast(a,dtype=tf.bool)
sess = tf.Session()
sess.run(tf.global_variables_initializer())
print(sess.run(b))
[ True False False True True]
4). tf.truncated_normal()
tf.truncated_normal(shape, mean, stddev):shape表示生成张量的维度,mean是均值,stddev是标准差。这个函数产生正太分布,均值和标准差自己设定。这是一个截断的产生正太分布的函数,就是说产生正太分布的值如果与均值的差值大于两倍的标准差,那就重新生成。和一般的正太分布的产生随机数据比起来,这个函数产生的随机数与均值的差距不会超过两倍的标准差,但是一般的别的函数是可能的。
import tensorflow as tf;
import numpy as np;
import matplotlib.pyplot as plt;
c = tf.truncated_normal(shape=[10,10], mean=0, stddev=1)
with tf.Session() as sess:
print(sess.run(c))
[[ 0.56077307 1.74287605 -0.15655719 0.87136668 -0.4219175 0.94079614
-1.31186545 1.94287431 0.70748854 1.15509737]
[ 0.32469562 -0.91890186 -0.44398952 1.25986481 -1.07295966 0.21889997
0.19389877 -1.22909117 1.34865403 0.87812191]
[-0.83542323 -0.05598836 -1.05256093 -1.16475403 -0.17121609 -0.55075479
-0.37847248 0.14151201 0.36596569 0.55171227]
[ 0.45216689 0.12429248 -0.4333829 -0.00368057 -0.20933141 0.5465408
1.06096387 1.47238612 -1.99268937 1.28203201]
[ 0.36932501 0.30012983 1.94679129 0.59601396 -0.16721351 -0.42786792
0.917597 -1.6504811 -0.81060582 -0.35126168]
[-1.48954999 -0.42889833 0.31517059 1.00009787 0.26073182 1.26285052
-1.80997884 0.51399821 -0.27673215 0.15389352]
[ 0.8669793 -0.28650126 1.39484227 -0.4041909 -1.70028269 0.58513969
0.75772232 -0.47386578 -0.34529254 -0.71658897]
[ 0.74709773 -0.0835886 1.14453304 0.70367438 0.07037418 -0.15808868
0.23158503 -0.67268801 0.55869597 0.12777361]
[-0.52604282 0.64181858 -0.04147881 0.78596973 0.69087744 0.56500375
-1.12409449 -0.42864376 0.30804652 1.33116138]
[-1.36940789 -0.4526186 -0.87445366 0.19748467 -0.06541829 -0.2672275
0.63084471 0.76155263 0.83874393 0.91775542]]
9、tf.reduce_max(),tf.reduce_mean()
求最大值tf.reduce_max(input_tensor, reduction_indices=None, keep_dims=False, name=None)
求平均值tf.reduce_mean(input_tensor, reduction_indices=None, keep_dims=False, name=None)
参数1--input_tensor:待求值的tensor。
参数2--reduction_indices:在哪一维上求解。
参数(3)(4)可忽略
import tensorflow as tf
X = [[1., 2.],
[3., 4.]]
re1 = tf.reduce_mean(x) ==> 2.5 #如果不指定第二个参数,那么就在所有的元素中取平均值
re2 = tf.reduce_mean(x, 0) ==> [2., 3.] #指定第二个参数为0,则第一维的元素取平均值,即每一列求平均值
#re2 = tf.reduce_mean(x, reduction_indices = 0)
re3 = tf.reduce_mean(x, 1) ==> [1.5, 3.5] #
#re3 = tf.reduce_mean(x, reduction_indices = 1)
with tf.Session() as sess:
print(sess.run(re1))
print(sess.run(re2))
print(sess.run(re3))
tf.nn.sparse_softmax_cross_entropy_with_logits(_sentinel=None, labels=None, logits=None, name=None)
10、tf.app.flags函数
tf定义了tf.app.flags,用于支持接受命令行传递参数,相当于接受argv。
import tensorflow as tf
#第一个是参数名称,第二个参数是默认值,第三个是参数描述
tf.app.flags.DEFINE_string('str_name', 'def_v_1',"descrip1")
tf.app.flags.DEFINE_integer('int_name', 10,"descript2")
tf.app.flags.DEFINE_boolean('bool_name', False, "descript3")
FLAGS = tf.app.flags.FLAGS
#必须带参数,否则:'TypeError: main() takes no arguments (1 given)'; main的参数名随意定义,无要求
def main(_):
print(FLAGS.str_name)
print(FLAGS.int_name)
print(FLAGS.bool_name)
if __name__ == '__main__':
tf.app.run() #执行main函数
执行:
[root@AliHPC-G41-211 test]# python tt.py
def_v_1
10
False
[root@AliHPC-G41-211 test]# python tt.py --str_name test_str --int_name 99 --bool_name True
test_str
99
True
11、python glob模块
glob.glob
返回所有匹配的文件路径列表。它只有一个参数pathname,定义了文件路径匹配规则,这里可以是绝对路径,也可以是相对路径。下面是使用glob.glob的例子:
import glob
#获取指定目录下的所有图片
print glob.glob(r"E:\Picture\*\*.jpg")
#获取上级目录的所有.py文件
print glob.glob(r'../*.py') #相对路径
12、Python中split()和os.path.split()两个分割函数
函数:split()
Python中有split()和os.path.split()两个函数,具体作用如下:
split():拆分字符串。通过指定分隔符对字符串进行切片,并返回分割后的字符串列表(list)
os.path.split():按照路径将文件名和路径分割开
1)、函数说明
1、split()函数
语法:str.split(str="",num=string.count(str))[n]
参数说明:
str:表示为分隔符,默认为空格,但是不能为空('')。若字符串中没有分隔符,则把整个字符串作为列表的一个元素
num:表示分割次数。如果存在参数num,则仅分隔成 num+1 个子字符串,并且每一个子字符串可以赋给新的变量
[n]:表示选取第n个分片
注意:当使用空格作为分隔符时,对于中间为空的项会自动忽略
2、os.path.split()函数
语法:os.path.split('PATH')
参数说明:
1.PATH指一个文件的全路径作为参数:
2.如果给出的是一个目录和文件名,则输出路径和文件名
3.如果给出的是一个目录名,则输出路径和为空文件名
2)、分离字符串
string = "www.gziscas.com.cn"
1.以'.'为分隔符
print(string.split('.'))
['www', 'gziscas', 'com', 'cn']
2.分割两次
print(string.split('.',2))
['www', 'gziscas', 'com.cn']
3.分割两次,并取序列为1的项
print(string.split('.',2)[1])
gziscas
4.分割两次,并把分割后的三个部分保存到三个文件
u1, u2, u3 =string.split('.',2)
print(u1)—— www
print(u2)—— gziscas
print(u3) ——com.cn
3)、分离文件名和路径
import os
print(os.path.split('/dodo/soft/python/'))
('/dodo/soft/python', '')
print(os.path.split('/dodo/soft/python'))
('/dodo/soft', 'python')
4)、实例
str="hello boy<[www.baidu.com]>byebye"
print(str.split("[")[1].split("]")[0])
www.baidu.com