tensorflow学习笔记 + 程序 (二)简单神经网络及MNIST数据集

1 回归问题简单神经网络

import tensorflow as tf 
import numpy as np 
import matplotlib.pyplot as plt 

# 生成随机点 
x_data = np.linspace(-0.5,0.5,200)[:,np.newaxis]
# [:,np.newaxis] 将x_data增加一个维度,原数据和原类型不变
noise = np.random.normal(0,0.02,x_data.shape)
y_data = np.square(x_data) + noise

# 定义两个placeholder(占位符)
x =  tf.placeholder(tf.float32,[None,1])  # [None,1] 行为none时可以为任意形状,列为1
y =  tf.placeholder(tf.float32,[None,1])

# 构建神经网络(中间层为10个神经元)
# 定义神经网络中间层(利用随机值初始化网络参数)
Weights_L1 = tf.Variable(tf.random.normal([1,10])) # 对应一个输入十个输出
biases_L1 = tf.Variable(tf.random.normal([1,10]))
Wx_plus_b_L1 = tf.matmul(x,Weights_L1) + biases_L1
# L1为中间层的输出,并采用双曲正切函数为接口函数
L1 = tf.nn.tanh(Wx_plus_b_L1)

# 定义神经网络输出层(利用随机值初始化网络参数)
Weights_L2 = tf.Variable(tf.random.normal([10,1]))
biases_L2 = tf.Variable(tf.random.normal([1,1]))
Wx_plus_b_L2 = tf.matmul(L1,Weights_L2) + biases_L2
# L2为最终的输出,并采用双曲正切函数为接口函数
prediction = tf.nn.tanh(Wx_plus_b_L2)

# 定义代价函数及训练方法
# 二次代价函数
loss = tf.reduce_mean(tf.square(y - prediction))
# 梯度下降法及最小化代价函数
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)

with tf.Session() as sess: 
    # 变量初始化
    sess.run(tf.global_variables_initializer())
    for _ in range(2000):
        sess.run(train_step,feed_dict = {x:x_data,y:y_data})
    
    # 获得预测值
    prediction_value = sess.run(prediction,feed_dict = {x:x_data})

    # 绘图
    plt.figure(figsize=(6,6))
    plt.scatter(x_data,y_data)
    plt.plot(x_data,prediction_value,'r-',lw = 5)
    plt.show() 

效果:
在这里插入图片描述

2 MNIST数据集

下文中所用的部分数据集链接(百度网盘):
链接:https://pan.baidu.com/s/1_Y0rWLj9wuJefzT9JME5Ug
提取码:6fho
将其置于存放程序的文件夹里即可

2.1 程序

import tensorflow as tf 
from tensorflow.examples.tutorials.mnist import input_data

# 载入数据集
mnist = input_data.read_data_sets("MNIST_data",one_hot=True)
# one_hot=True 将其标签转化为只有0和1的形式

# 定义变量_每个批次的大小
batch_size = 100
# 计算一共多少批次
n_batch = mnist.train.num_examples // batch_size # 整除

# 定义placeholder
x = tf.placeholder(tf.float32,[None,784])
y = tf.placeholder(tf.float32,[None,10])

# 创建简单的神经网络
W = tf.Variable(tf.zeros([784,10]))
b = tf.Variable(tf.zeros([10]))
prediction = tf.nn.softmax(tf.matmul(x,W) + b)

# 定义代价函数(二次)
loss = tf.reduce_mean(tf.square(y - prediction))
# 使用梯度下降法并最小化代价函数
train_step = tf.train.GradientDescentOptimizer(0.2).minimize(loss)

# 初始化变量
init = tf.global_variables_initializer()

# 定义求准确率的方法
correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(prediction,1))
''' #注释# 
    (1).tf.equal()比较其中两个参数是否相同,相同为True,不同为False
    返回值存放在一个bool型列表中
    (2).tf.argmax(input,axis) axis为0时比较每一列元素,为1时比较每一行元素   
    最后返回每行最大元素的索引数组
'''

# 求准确率
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))
''' #注释# 
    (1).tf.cast()将布尔类型转化为32位浮点型,True为1.0,False为0
    (2).tf.reduce_mean()求平均数
    比如说转化为的列表中有9个True1个False,则经过tf.cast()后有9个1,1个0,易得其准确率为90%
'''

with tf.Session() as sess:
    sess.run(init)
    for epoch in range(21):
        for batch in range(n_batch):
            batch_xs,batch_ys = mnist.train.next_batch(batch_size)
            ''' #注释# 
                (1).调用mnist.train.next_batch()获取图片
                (2).图片数据保存在batch_xs中,标签保存在batch_ys中
            '''
            sess.run(train_step,feed_dict = {x:batch_xs,y:batch_ys})
        
        # 测试下准确率
        acc = sess.run(accuracy,feed_dict = {x:mnist.test.images,y:mnist.test.labels})
        print("Iter " + str(epoch) + ".Testing Accuracy " + str(acc))


# 输出结果: 
'''
Iter 0.Testing Accuracy 0.8316
Iter 1.Testing Accuracy 0.871
Iter 2.Testing Accuracy 0.8819
Iter 3.Testing Accuracy 0.889
Iter 4.Testing Accuracy 0.8943
Iter 5.Testing Accuracy 0.8972
Iter 6.Testing Accuracy 0.9007
Iter 7.Testing Accuracy 0.9024
Iter 8.Testing Accuracy 0.9028
Iter 9.Testing Accuracy 0.9043
Iter 10.Testing Accuracy 0.9064
Iter 11.Testing Accuracy 0.9075
Iter 12.Testing Accuracy 0.9086
Iter 13.Testing Accuracy 0.9091
Iter 14.Testing Accuracy 0.9103
Iter 15.Testing Accuracy 0.911
Iter 16.Testing Accuracy 0.9112
Iter 17.Testing Accuracy 0.9126
Iter 18.Testing Accuracy 0.9128
Iter 19.Testing Accuracy 0.9128
Iter 20.Testing Accuracy 0.9142
'''

2.2 模型优化方法建议

(1).每个批次的大小
(2).l初始化权值的值
(3).神经网络隐藏层及其拓扑结构
(4).激活函数可以使用tanh()等其他..
(5).代价函数的选取
(6).神经网络学习率
(7).不再使用梯度下降法而转而采用其他的优化方式
(8).训练次数
发布了6 篇原创文章 · 获赞 0 · 访问量 234

猜你喜欢

转载自blog.csdn.net/k903161661/article/details/104232228
今日推荐