参数数量及其作用
tf.layers.dense用于添加一个全连接层。
函数如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
tf.layers.dense( inputs, #层的输入 units, #该层的输出维度 activation = None , #激活函数 use_bias = True , kernel_initializer = None , # 卷积核的初始化器 bias_initializer = tf.zeros_initializer(), # 偏置项的初始化器 kernel_regularizer = None , # 卷积核的正则化 bias_regularizer = None , # 偏置项的正则化 activity_regularizer = None , kernel_constraint = None , bias_constraint = None , trainable = True , name = None , # 层的名字 reuse = None # 是否重复使用参数 ) |
部分参数解释:
inputs:输入该层的数据。
units:该层的输出维度。
activation:激活函数。
use_bias:是否使用偏置项。
trainable=True : 表明该层的参数是否参与训练。
示例
手写体例子,利用两个dense可以构成一个单层网络,在下面例子中,网络的神经元个数为200。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
|
import numpy as np import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data def compute_accuracy(x_data,y_data): global dense2 y_pre = sess.run(dense2,feed_dict = {xs:x_data}) correct_prediction = tf.equal(tf.arg_max(y_data, 1 ),tf.arg_max(y_pre, 1 )) #判断是否相等 accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32)) #赋予float32数据类型,求平均。 result = sess.run(accuracy,feed_dict = {xs:batch_xs,ys:batch_ys}) #执行 return result mnist = input_data.read_data_sets( "MNIST_data" ,one_hot = "true" ) xs = tf.placeholder(tf.float32,[ None , 784 ]) ys = tf.placeholder(tf.float32,[ None , 10 ]) dense1 = tf.layers.dense( xs, 200 , activation = tf.nn.tanh, kernel_initializer = tf.random_normal_initializer(mean = 0 , stddev = 0.3 ), bias_initializer = tf.constant_initializer( 0.1 ), name = 'fc1' ) dense2 = tf.layers.dense( dense1, 10 , activation = tf.nn.softmax, kernel_initializer = tf.random_normal_initializer(mean = 0 , stddev = 0.3 ), bias_initializer = tf.constant_initializer( 0.1 ), name = 'fc2' ) loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = dense2, labels = ys),name = 'loss' ) #label是标签,logits是预测值,交叉熵。 train = tf.train.GradientDescentOptimizer( 0.5 ).minimize(loss) init = tf.initialize_all_variables() with tf.Session() as sess: sess.run(init) for i in range ( 5001 ): batch_xs,batch_ys = mnist.train.next_batch( 100 ) sess.run(train,feed_dict = {xs:batch_xs,ys:batch_ys}) if i % 1000 = = 0 : print ( "训练%d次的识别率为:%f。" % ((i + 1 ),compute_accuracy(mnist.test.images,mnist.test.labels))) |
实验结果为:
训练1次的识别率为:0.107400。
训练1001次的识别率为:0.805200。
训练2001次的识别率为:0.822800。
训练3001次的识别率为:0.829400。
训练4001次的识别率为:0.833100。
训练5001次的识别率为:0.835300。
以上就是python人工智能tensorflow函数tf.layers.dense使用方法的详细内容,更多关于tensorflow函数tf.layers.dense的资料请关注服务器之家其它相关文章!
原文链接:https://blog.csdn.net/weixin_44791964/article/details/99685428