TensorFlow常用函数

常用tensorflow函数

常量

t_1 = tf.constant(4)	#4
t_2 = tf.constant([4,3,2])	#向量[4,3,2]
zero_t = tf.zeros([2,3],tf.int32)	#两行三列类型为int32的全0矩阵
ones_t = tf.ones([2,3],tf.int32)	#两行三列类型为int32的全1矩阵
range_t = tf.range(10)		#Result:[0 1 2 3 4 5 6 7 8 9],默认起始为0,增量为1。

占位符

#float为数据类型,shape为数据未知行,784列
x = tf.placeholder("float", shape=[None, 784])

截尾正态分布随机值定义

stddev为标准差
initial = tf.truncated_normal(shape, stddev=0.1)

卷积

#x为输入量,W为卷积核
#strides,表示在height和width维度上的步长都为1
#padding填充(same考虑边缘,并填充为0,valid则不考虑填充)
tf.nn.conv2d(x, W, strides=[1,1,1,1], padding="SAME")

池化

#ksize表示pool窗口大小为2x2,也就是高2,宽2
#strides,表示在height和width维度上的步长都为2
tf.nn.max_pool(x, ksize=[1,2,2,1],strides=[1,2,2,1], padding="SAME")

重新定义形状

#-1表示自动推测这个维度的size
#将x变成28*28*(1深度)的张量,并且自动推算个数
x_image = tf.reshape(x, [-1,28,28,1])

激活函数

#ReLU激活函数,(小于0输出0,大于0不变)
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)

减小或防止过拟合

h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)

softma输出概率

y_conv = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)

计算

#tf.log计数自然对数        
#tf.reduce_sum求沿着某一维度的和
cross_entropy = -tf.reduce_sum(y_ * tf.log(y_conv))

#判断两个值是否相等	tf.equal()
correct_predict = tf.equal(tf.argmax(y_conv, 1), tf.argmax(y_, 1))

#tf.cast把布尔值转换成浮点数
#tf.reduce_mean求平均值
accuracy = tf.reduce_mean(tf.cast(correct_predict, "float"))

梯度下降优化器

train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
posted @ 2020-12-04 14:50  slyuan  阅读(116)  评论(0)    收藏  举报