tensorflow实现简单的感知机

 1 # 感知机
 2 
 3 #导入相关库并载入数据
 4 from tensorflow.examples.tutorials.mnist import input_data
 5 import tensorflow as tf
 6 mnist = input_data.read_data_sets("MNIST_data/",one_hot = True)
 7 sess = tf.InteractiveSession()
 8 
 9 #对隐含层参数进行初始化
10 in_units = 784
11 h1_units = 300
12 w1 = tf.Variable(tf.truncated_normal([in_units,h1_units],stddev=0.1))
13 b1 = tf.Variable(tf.zeros([h1_units]))
14 w2 = tf.Variable(tf.zeros([h1_units,10]))
15 b2 = tf.Variable(tf.zeros([10]))
16 
17 # 定义输入x及dropout比率
18 x = tf.placeholder(tf.float32,[None,in_units])
19 keep_prob = tf.placeholder(tf.float32)
20 
21 
22 #定义模型结构
23 hidden1 = tf.nn.relu(tf.matmul(x,w1) + b1)
24 hidden1_drop = tf.nn.dropout(hidden1, keep_prob)
25 y = tf.nn.softmax(tf.matmul(hidden1_drop,w2) + b2)
26 
27 
28 #定义损失函数和优化器
29 y_ = tf.placeholder(tf.float32, [None,10])
30 cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y),reduction_indices=[1]))
31 train_step = tf.train.AdagradOptimizer(0.3).minimize(cross_entropy)
32 
33 
34 #训练
35 tf.global_variables_initializer().run()
36 for i in range(3000):
37     batch_xs, batch_ys = mnist.train.next_batch(100)
38     train_step.run({x:batch_xs,y_:batch_ys,keep_prob:0.75})
39 
40 
41 #对模型进行准确率评测
42 correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))
43 accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
44 print(accuracy.eval({x:mnist.test.images,y_:mnist.test.labels,keep_prob:1.0}))

 

参考书籍:

1.《Tensorflow实战》黄文坚  唐源 著

作者:舟华520

出处:https://www.cnblogs.com/xfzh193/

本文以学习,分享,研究交流为主,欢迎转载,请标明作者出处!

posted on 2020-10-28 12:12  舟华  阅读(215)  评论(0编辑  收藏  举报

导航