TensorFlow入门(三)多层 CNNs 实现 mnist分类

欢迎转载,但请务必注明原文出处及作者信息。

深入MNIST

refer: http://wiki.jikexueyuan.com/project/tensorflow-zh/tutorials/mnist_pros.html
@author: huangyongye
@date: 2017-02-24

之前在keras中用同样的网络和同样的数据集来做这个例子的时候。keras占用了 5647M 的显存(训练过程中设了 validation_split = 0.2, 也就是1.2万张图)。

但是我用 tensorflow 自己写的 batch=50 来测试发现呀只有529的占用显存!!!只是在最后做测试的时候因为是对10000多张图片一次性做预测才占用了 8721M 的显存这里的测试集是 1 万张。如果把预测时候的 batch 也设得比较小的话,那么整个网络只需要很小的显存了。

import numpy as np
import tensorflow as tf

# 设置按需使用GPU
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
sess = tf.InteractiveSession(config=config)

1.导入数据,用 tensorflow 导入

# 用tensorflow 导入数据
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('MNIST_data', one_hot=True)
Extracting MNIST_data/train-images-idx3-ubyte.gz
Extracting MNIST_data/train-labels-idx1-ubyte.gz
Extracting MNIST_data/t10k-images-idx3-ubyte.gz
Extracting MNIST_data/t10k-labels-idx1-ubyte.gz
# 看看咱们样本的数量
print mnist.test.labels.shape
print mnist.train.labels.shape
(10000, 10)
(55000, 10)

或者从keras中导入数据

# 注意: keras 中导入数据形式不一样哦,需要根据具体情况调整
from keras.datasets import mnist
(X_train, y_train), (X_test, y_test) = mnist.load_data()
print 'X_train.shape=', X_train.shape
print 'y_train.shape=', y_train.shape

# TensorFlow 类别需要使用 one-hot 类型
from keras.utils import np_utils
y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)
print X_train.shape
print y_train.shape
X_train.shape= (60000, 28, 28)
y_train.shape= (60000,)
(60000, 28, 28)
(60000, 10)

2. 构建网络

# 权值初始化
def weight_variable(shape):
    # 用正态分布来初始化权值
    initial = tf.truncated_normal(shape, stddev=0.1)
    return tf.Variable(initial)

def bias_variable(shape):
    # 本例中用relu激活函数,所以用一个很小的正偏置较好
    initial = tf.constant(0.1, shape=shape)
    return tf.Variable(initial)

# 定义卷积层
def conv2d(x, W):
    # 默认 strides[0]=strides[3]=1, strides[1]为x方向步长,strides[2]为y方向步长
    return tf.nn.conv2d(x, W, s
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值