MNIST 全连接网络实现

全连接网络

最近在编写tensorflow的相关代码,实现了一下全连接网络实现mnist的代码,具体代码如下

相关函数说明

tf.argmax(y,1)
#返回数组y中最大值的索引,如果y是多维数组,只在当前数组中比较,按行比较
tf.argmax(y,0)
如果是0,比较当前列,也就是多个数组的相同位置,按列比较

code

import tensorflow as tf
import os
import time
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
#设置相关的显卡,可以是单独一个设置,也可以是多个设备
#os.environ["CUDA_VISIBLE_DEVICES"] = "0,1"
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
tf_config = tf.ConfigProto()
#动态申请显存
tf_config.gpu_options.allow_growth = True
mnist = input_data.read_data_sets("mnist",one_hot=True)
#适当的增加batch_size,会提高模型训练的时间
batch_size = 128
n_batch = mnist.train.num_examples // batch_size
x = tf.placeholder(tf.float32,[None,784])
y = tf.placeholder(tf.float32, [None,10])
keep_prob = tf.placeholder(tf.float32)

w1 = tf.Variable(tf.truncated_normal([784,1024],stddev=0.1))
b1 = tf.Variable(tf.random_normal([1024]))
L1 = tf.nn.tanh(tf.matmul(x,w1) + b1)
L1_drop = tf.nn.dropout(L1,keep_prob)

w2 = tf.Variable(tf.truncated_normal([1024,1024],stddev=0.1))
b2 = tf.Variable(tf.random_normal([1024]))
L2 = tf.nn.relu(tf.matmul(L1_drop,w2) + b2)
L2_drop = tf.nn.dropout(L2,keep_prob)


w3 = tf.Variable(tf.truncated_normal([1024,10],stddev=0.1))
b3 = tf.Variable(tf.random_normal([10]))


prediction = tf.matmul(L2_drop,w3) + b3

loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y, logits=prediction))

train_step = tf.train.AdamOptimizer(0.001).minimize(loss)
#train_step = tf.train.GradientDescentOptimizer(1e-3).minimize(loss)

init = tf.global_variables_initializer()

correct_prediction = tf.equal(tf.argmax(y,1),tf.argmax(prediction,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))

start = time.time()
with tf.Session(config = tf_config) as sess:
    sess.run(init)
    for epoch in range(50):
        epoch_start = time.time()
        for batch in range(n_batch):
            batch_xs,batch_ys = mnist.train.next_batch(batch_size)
            sess.run(train_step,feed_dict={x:batch_xs,y:batch_ys,keep_prob:0.75})
        epoch_end = time.time()
        epoch_time = epoch_end - epoch_start
        test_acc = sess.run(accuracy, feed_dict={x:mnist.test.images,y:mnist.test.labels,keep_prob:1.0})
        train_acc = sess.run(accuracy, feed_dict={x: mnist.train.images, y: mnist.train.labels,keep_prob:1.0})
        print("Iter:" + str(epoch) + ", Test Acc:" + str(test_acc) + ",Train Acc:" + str(train_acc) + ",Time:"+ str(epoch_time))
end = time.time()
print("Total Time:"+str(end - start) + "s")
print("success")

Trick

增加batch_size,会提高训练的速度,减少训练的时间
stable epoch指的是acc稳定到0.98所需要的epoch数量

batch_sizetimeepochaccstable epochmem
32290s500.981371132m
64154s500.983281132m
12896s500.982231132m
25667s500.985101132m

设置GPU设备的时候是有优先级的

os.environ["CUDA_VISIBLE_DEVICES"] = "0,1"

os.environ["CUDA_VISIBLE_DEVICES"] = "1,0"

这两个 是不一样的,在前面的会优先使用

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
全连接网络实现MNIST代码的关键部分包括数据的预处理、网络模型的构建、损失函数的定义、优化算法的选取以及训练过程的实现。 首先,需要对MNIST数据进行预处理。预处理包括加载数据集、标准化数据、对标签进行独热编码等操作。 接下来,构建全连接神经网络模型。全连接网络由多层全连接层组成,每层都包括权重参数和偏置项。可以选择使用不同的激活函数,如ReLU激活函数。 定义损失函数。在MNIST中,常用的损失函数是交叉熵损失函数。该损失函数度量实际输出与期望输出之间的差距。可以使用TensorFlow的交叉熵函数来定义损失函数。 选择优化算法。常用的优化算法是随机梯度下降算法(SGD)。SGD以一定的学习率不断更新模型的参数,使得损失函数最小化。在TensorFlow中,可以使用优化器来实现SGD算法。 实现训练过程。训练过程是通过不断迭代来优化模型的参数。每次迭代中,选择一批样本进行前向传播和反向传播,更新模型的参数。可以设置每批训练样本的大小、迭代次数等参数。 在训练过程中,可以通过验证集来监控模型的性能以及防止过拟合。最后,可以用测试集来评估模型的性能和泛化能力。 综上所述,全连接网络实现MNIST代码的关键部分包括数据的预处理、网络模型的构建、损失函数的定义、优化算法的选择以及训练过程的实现。这些步骤是实现一个基本的全连接网络分类器的关键。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值