tensorflow中很多函数是对神经网络中用到的一些功能的封装,通过查看这些函数参数的设置,以及返回值可以了解这些函数的使用方法,对神经网络的过程也能更加清楚,写代码的时候也能更好的使用这些函数和模型的参数调节。
tf.nn.softmax_cross_entropy_with_logits(logits,labels,name=None)函数,用来计算交叉熵损失。
参数logits:神经网络最后一层的输出
参数labels:实际的标签,真实值
函数先将logits归一化,然后和真实值做交叉熵,-y'i*log(yi)。其中y'i是真实值中的第i个分量,yi是logits归一化之后第i个分量。预测值越准确,结果越小。
函数返回值是一个向量,求和(tf.reduce_sum)之后是交叉熵,求均值(tf.reduce_mean)后是loss
该函数的使用参考博文点击打开链接
------------------------------------------------------------------------------------------------------
tf.nn.conv2d(input,filter,strides,padding,use_cudnn_on_gpu=None,name=None)函数,用在卷积神经网络中进行卷积操作。
参数input: 4维张量(batch,in_height,in_width,in_channels) 用于输入图片的batch大小,高,宽,以及输入通道(对于图像而言有可能是rgb三个颜色通道)。
参数filter: 4维张量(heigh,width,in_channels,out_channels) 用于确定卷积核的高,宽,输入通道(与input中的输入通道参数一致),输出通道。
参数strides:长度为4的列表,代表步长。
参数padding:string类型(SAME,VALID)用于填充
结果:返回一个张量和input类型相同,通常作为池化的输入。
tf.nn.max_pool(value,ksize,strides,padding,data_format='NHWC',name=None)函数,用来进行池化操作。
参数value:4维张量(batch,heigh,width,channels) 和conv2d中input类似。
参数ksize:长度大于等于4,每个维度的窗格大小。
参数strides:与conv2d类似。
参数padding:同上。
结果:返回池化的输出张量。
---------------------------------------------------------------------------
tf.pack(values,name='pack')函数对张量进行打包。将秩为r的tensor打包成秩为r+1的tensor。
用法:
x = tf.constant([1,2,3])
y = tf.constant([2,4,6])
z = tf.constant([7,8,9])
p = tf.pack([x,y,z])
sess = tf.Session()
print sess.run(tf.shape(p))
print sess.run(p)
print sess.run(tf.unpack(p,3))
结果:
[3 3]
[[1 2 3]
[2 4 6]
[7 8 9]]
[array([1, 2, 3], dtype=int32), array([2, 4, 6], dtype=int32), array([7, 8, 9], dtype=int32)]
---------------------------------------------------------------------------
tf.sign()
x<0,-1
x=0,0
x>0,1
---------------------------------------------------------------------------
tf.cast(x,dtype)
dtype=tf.int32时用于取整
---------------------------------------------------------------------------
后续遇到一些重要函数会继续更新,有错误希望指出。
另外看了一个tensorflow的多层感知机,手写数字识别
#两个隐藏层的神经网络
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("./MNIST_data/",one_hot=True)
#设置参数
learning_rate = 0.001
training_epochs = 30
batch_size = 100
n_hidden_1 = 300
n_hidden_2 = 300
n_input = 784
n_classes = 10
x = tf.placeholder("float",[None,n_input])
y = tf.placeholder("float",[None,n_classes])
weights = {
'h1':tf.Variable(tf.random_normal([n_input,n_hidden_1])),
'h2':tf.Variable(tf.random_normal([n_hidden_1,n_hidden_2])),
'out':tf.Variable(tf.random_normal([n_hidden_2,n_classes]))
}
biases = {
'b1':tf.Variable(tf.random_normal([n_hidden_1])),
'b2':tf.Variable(tf.random_normal([n_hidden_2])),
'out':tf.Variable(tf.random_normal([n_classes]))
}
def multilayer_perceptron(x,weights,biases):
layer_1 = tf.add(tf.matmul(x,weights['h1']),biases['b1'])
layer_1 = tf.nn.relu(layer_1)
layer_2 = tf.add(tf.matmul(layer_1,weights['h2']),biases['b2'])
layer_2 = tf.nn.relu(layer_2)
out_layer = tf.matmul(layer_2,weights['out']) + biases['out']#tf.matmul矩阵相乘
return out_layer
pred = multilayer_perceptron(x,weights,biases)
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(pred,y))#交叉熵损失函数
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)#
init = tf.initialize_all_variables()
with tf.Session()as sess:
sess.run(init)
for epoch in range(training_epochs):#整个数据训练15遍
avg_cost = 0
total_batch = int(mnist.train.num_examples/batch_size)#分批训练
for i in range(total_batch):
batch_x,batch_y = mnist.train.next_batch(batch_size)
_,c = sess.run([optimizer,cost],feed_dict={x:batch_x,y:batch_y})
avg_cost += c #
print "Epoch:", '%04d' % (epoch+1), "cost=","{:.9f}".format(avg_cost)
print "finished!"
correct_prediction = tf.equal(tf.argmax(pred,1),tf.argmax(y,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction,"float"))
print accuracy.eval({x: mnist.test.images, y: mnist.test.labels})
print sess.run(accuracy,feed_dict={x: mnist.test.images, y: mnist.test.labels})#这里sess.run()的功能和eval类似
运行的时候改了参数的一些设定得到不同的结果:training_epochs n_hidden_1 n_hidden_2 accuracy
15 300 300 0.9459
20 300 300 0.9527
20 500 500 0.9562
25 300 300 0.9552
30 300 300 0.9564