1.tf.cond()用法
cond (
pred ,
true_fn = None ,
false_fn = None ,
strict = False ,
name = None ,
fn1 = None ,
fn2 = None
)
如果断言 pred 为 true 则返回 true_fn() ,否则返回 false_fn().
true_fn 和 false_fn 都返回输出张量的列表.true_fn 和 false_fn 必须具有相同的非零数和输出类型.
import tensorflow as tf
a = tf.placeholder(dtype=bool)
def true_fn():
return True
def false_fn():
return False
b = tf.cond(a,true_fn,false_fn)
print(b)
with tf.Session() as sess:
print(sess.run(b,feed_dict={a:False}))
2.tf.where()用法
2.1 tf.where(tensor,a,b)
a,b为和tensor相同维度的tensor,将tensor中的true位置元素替换为a中对应位置元素,false的替换为b中对应位置元素
处理numpy数组
import tensorflow as tf
import numpy as np
sess=tf.Session()
a=np.array([[1,0,0],[0,1,1]])
a1=np.array([[3,2,3],[4,5,6]])
print(sess.run(tf.equal(a,1)))
print(sess.run(tf.where(tf.equal(a,1),a1,1-a1)))
>>[[true,false,false],[false,true,true]]
>>[[3,-1,-2],[-3,5,6]]
处理TensorFlow 张量
import tensorflow as tf
a = tf.constant([0])
b = tf.constant([1])
c = tf.where(True,a,b)
print(c)
with tf.Session() as sess:
print(sess.run(c))
output:
Tensor("Select:0", shape=(1,), dtype=int32)
[0]
3.tf.equal()用法
equal(x, y, name=None)
逐个元素进行判断,如果相等就是True,不相等,就是False。
由于是逐个元素判断,所以x,y 的维度要一致。
import tensorflow as tf
a = [[1,2,3],[4,5,6]]
b = [[1,0,3],[1,5,1]]
with tf.Session() as sess:
print(sess.run(tf.equal(a,b)))
output:
[[ True False True]
[False True False]]
4.tf.nn.conv2d()的用法
tf.nn.conv2d(input, filter, strides, padding, use_cudnn_on_gpu=True, data_format=“NHWC”, dilations=[1, 1, 1, 1], name=None)
第一个参数input:指需要做卷积的输入图像,它要求是一个Tensor,具有[batch, in_height, in_width, in_channels]这样的shape,具体含义是[训练时一个batch的图片数量, 图片高度, 图片宽度, 图像通道数],注意这是一个4维的Tensor,要求类型为float32和float64其中之一
第二个参数filter:相当于CNN中的卷积核,它要求是一个Tensor,具有[filter_height, filter_width, in_channels, out_channels]这样的shape,具体含义是[卷积核的高度,卷积核的宽度,图像通道数,卷积核个数],要求类型与参数input相同,filter的通道数要求与input的in_channels一致,有一个地方需要注意,第三维in_channels,就是参数input的第四维
第三个参数strides:卷积时在图像每一维的步长,这是一个一维的向量,长度4,strides[0]=strides[3]=1 ,例如strides = [1,2,2,1]
5.tensorboard可视化
import tensorflow as tf
import numpy as np
def add_layer(inputs,in_size,out_size,n_layer,activation_function=None): #activation_function=None线性函数
layer_name="layer%s" % n_layer
with tf.name_scope(layer_name):
with tf.name_scope('weights'):
Weights = tf.Variable(tf.random_normal([in_size,out_size])) #Weight中都是随机变量
tf.summary.histogram(layer_name+"/weights",Weights) #可视化观看变量
with tf.name_scope('biases'):
biases = tf.Variable(tf.zeros([1,out_size])+0.1) #biases推荐初始值不为0
tf.summary.histogram(layer_name+"/biases",biases) #可视化观看变量
with tf.name_scope('Wx_plus_b'):
Wx_plus_b = tf.matmul(inputs,Weights)+biases #inputs*Weight+biases
tf.summary.histogram(layer_name+"/Wx_plus_b",Wx_plus_b) #可视化观看变量
if activation_function is None:
outputs = Wx_plus_b
else:
outputs = activation_function(Wx_plus_b)
tf.summary.histogram(layer_name+"/outputs",outputs) #可视化观看变量
return outputs
#创建数据x_data,y_data
x_data = np.linspace(-1,1,300)[:,np.newaxis] #[-1,1]区间,300个单位,np.newaxis增加维度
noise = np.random.normal(0,0.05,x_data.shape) #噪点
y_data = np.square(x_data)-0.5+noise
with tf.name_scope('inputs'): #结构化
xs = tf.placeholder(tf.float32,[None,1],name='x_input')
ys = tf.placeholder(tf.float32,[None,1],name='y_input')
#三层神经,输入层(1个神经元),隐藏层(10神经元),输出层(1个神经元)
l1 = add_layer(xs,1,10,n_layer=1,activation_function=tf.nn.relu) #隐藏层
prediction = add_layer(l1,10,1,n_layer=2,activation_function=None) #输出层
#predition值与y_data差别
with tf.name_scope('loss'):
loss = tf.reduce_mean(tf.reduce_sum(tf.square(ys-prediction),reduction_indices=[1])) #square()平方,sum()求和,mean()平均值
tf.summary.scalar('loss',loss) #可视化观看常量
with tf.name_scope('train'):
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss) #0.1学习效率,minimize(loss)减小loss误差
init = tf.initialize_all_variables()
sess = tf.Session()
#合并到Summary中
merged = tf.summary.merge_all()
#选定可视化存储目录
writer = tf.summary.FileWriter("Desktop/",sess.graph)
sess.run(init) #先执行init
#训练1k次
for i in range(1000):
sess.run(train_step,feed_dict={xs:x_data,ys:y_data})
if i%50==0:
result = sess.run(merged,feed_dict={xs:x_data,ys:y_data}) #merged也是需要run的
writer.add_summary(result,i) #result是summary类型的,需要放入writer中,i步数(x轴)
6.增加维度和张量扩张
import tensorflow as tf
a = tf.constant([[1,2],[3,4]])
b = tf.expand_dims(a,axis=1)#增加维度
c = tf.tile(b,[1,4,1])#张量扩张
with tf.Session() as sess:
print(sess.run(a).shape)
print(sess.run(b).shape)
print(sess.run(c).shape)
# print(sess.run(a))
#print(sess.run(b))
print(sess.run(c))
output:
(2, 2)
(2, 1, 2)
(2, 4, 2)
[[[1 2]
[1 2]
[1 2]
[1 2]]
[[3 4]
[3 4]
[3 4]
[3 4]]]
7.tf.reduce_sum( ) 函数用法
reduce_sum( ) 是求和函数,在 tensorflow 里面,计算的都是 tensor,可以通过调整 axis =0,1 的维度来控制求和维度。
8.tf.subtract减法操作
tf.subtract(
x,
y,
name=None
)
参数说明:
X:一个张量。必须是下列类型之一:bfloat16, half, float32, float64, uint8, int8, uint16, int16, int32, int64, complex64, complex128
y:一个张量。类型同x.
name:张量操作的名字,可选参数。
返回值:x-y 一个张量,类型同x
9.tf.add() 将参数相加
10.tf.reduce_mean的用法
tf.reduce_mean 函数用于计算张量tensor沿着指定的数轴(tensor的某一维度)上的的平均值,主要用作降维或者计算tensor(图像)的平均值。
reduce_mean(input_tensor,
axis=None,
keep_dims=False,
name=None,
reduction_indices=None)
第一个参数input_tensor: 输入的待降维的tensor;
第二个参数axis: 指定的轴,如果不指定,则计算所有元素的均值;
第三个参数keep_dims:是否降维度,设置为True,输出的结果保持输入tensor的形状,设置为False,输出结果会降低维度;
第四个参数name: 操作的名称;
第五个参数 reduction_indices:在以前版本中用来指定轴,已弃用;
以一个维度是2,形状是[3,3]的tensor举例:
import tensorflow as tf
x = [[1,2,3],
[1,2,3]]
xx = tf.cast(x,tf.float32)
mean_all = tf.reduce_mean(xx, keep_dims=False)
mean_0 = tf.reduce_mean(xx, axis=0, keep_dims=False)
mean_1 = tf.reduce_mean(xx, axis=1, keep_dims=False)
with tf.Session() as sess:
m_a,m_0,m_1 = sess.run([mean_all, mean_0, mean_1])
print m_a # output: 2.0
print m_0 # output: [ 1. 2. 3.]
print m_1 #output: [ 2. 2.]
如果设置保持原来的张量的维度,keep_dims=True ,结果:
print m_a # output: [[ 2.]]
print m_0 # output: [[ 1. 2. 3.]]
print m_1 #output: [[ 2.], [ 2.]]
10.tf.scatter_sub的用法
将ref中特定位置的数分别进行减法运算。
示例如下:
ref = tf.Variable([1, 2, 3, 4, 5, 6, 7, 8],dtype = tf.int32)
indices = tf.constant([4, 3, 1, 7],dtype = tf.int32)
updates = tf.constant([9, 10, 11, 12],dtype = tf.int32)
sub = tf.scatter_sub(ref, indices, updates)
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
print sess.run(sub)
输出:
[ 1 -9 3 -6 -4 6 7 -4]
(多维用tf.scatter_nd_sub)