【TensorFlow】基础函数总结

数据定义

占位符

x = tf.placeholder(dtype=tf.float32,shape)

变量

W = tf.Variable(tf.zeros(shape))

常数变量

tf.Variable(tf.constant(0.1,shape=shape))
tf.zeros(shape,dtype)
tf.ones(shape,dtype)
#生成一个全部为给定数字的数组
tf.fill(shape,number)

随机数

从均匀分布中返回随机值

tf.random_uniform(shape,minval=low,maxval=high,dtype=tf.float32)

返回一个(0,x)之间的整数

np.random.randint(0,x)

正态分布

tf.random_normal(shape,stddev)

截断正态分布

tf.truncated_normal(shape,stddev)

激活函数

Relu激活函数

tf.nn.relu(tf.matmul(x,W1)+b1)

softmax激活函数

 tf.nn.softmax(tf.matmul(hidden1_drop,W2)+b2)

优化方法

随机失活

keep_prob = tf.placeholder(tf.float32)
hidden1_drop = tf.nn.dropout(hidden1,keep_prob)

局部响应归一化

tf.nn.lrn(conv2,4,bias=1.0,alpha=0.001/9.0,beta=0.75)

损失函数

交叉熵损失函数

cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_*tf.log(y),reduction_indices=[1]))

平方损失函数

cross_entropy = tf.reduce_mean(tf.square(y_-y))

训练器

 tf.train.GradientDescentOptimizer(learning_rate).minimize(cross_entropy)
tf.train.AdagradOptimizer(learning_rate).minimize(cross_entropy)

卷积

stride前后两位通常为1,即[1,x,x,1],‘SAME’表示对数据填充

tf.nn.conv2d(x,W,strides=[1,1,1,1],padding='SAME')

池化

tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')

其他函数

#argmax()表示返回最大值下标,1代表的是行内比较,0代表列内比较
correct_prediction = tf.equal(tf.argmax(y,1),tf.arg_max(y_,1))
#统计全部样本预测的arruracy,先用tf.cast将之前correct_prediction输出的bool值转换为float32
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))

将不同部分的损失函数累加

tf.add_to_collection('losses',cross_entropy_mean)
#实现各列表元素的对应维度的相加
tf.add_n(tf.get_collection('losses',name='total_loss'))

变量初始化

init_op = tf.initialize_all_variables()
sess.run(init_op)

tf.greater的输入是两个张量,比较张量中每一个元素的大小,并返回比价结果。tf.select判定第一个参数的值,若为True,选择第二个参数的值,否则使用第三个参数的值。

loss_less = 10
loss_more = 1
loss = tf.reduce_sum(tf.select(tf.greater(y,y_),(y-y_)*loss_more,(y_-y)*loss_less))

猜你喜欢

转载自blog.csdn.net/qq_28193895/article/details/81114912