(Tensorflow之二十二)将mnist数据转变成图片格式

6 篇文章 0 订阅

在用mnist进行图片训练时,我们mnist的格式为.gz格式的,因此训练的过程并不直观。在此,将mnist的数据转变成图片格式,便于我们观察数据在训练过程中的变化。

step 1

将原.gz格式的数据进行解压

$gunzip train-images-idx3-ubyte.gz

解压后的文 件
这里写图片描述

step 2

采用如下代码解析图片,图片的训练集与测试集分开存放,图片名与图片分开存放,代码如下

import numpy as np  
import os  
import cv2  
import struct  

#get the image and lable set    
def load_mnist(path, kind='train'):  
    """Load MNIST data from `path`"""  
    labels_path = os.path.join(path, '%s-labels-idx1-ubyte' % kind)  
    images_path = os.path.join(path, '%s-images-idx3-ubyte' % kind)  
    with open(labels_path, 'rb') as lbpath:  
        magic, n = struct.unpack('>II', lbpath.read(8))  
        labels = np.fromfile(lbpath, dtype=np.uint8)  
    with open(images_path, 'rb') as imgpath:  
        magic, num, rows, cols = struct.unpack(">IIII", imgpath.read(16))  
        images = np.fromfile(imgpath, dtype=np.uint8).reshape(len(labels), 784)  
    return images, labels  

#print the train image number and shape    
X_train, y_train = load_mnist('', kind='train')  
print('Rows: %d, columns: %d' % (X_train.shape[0], X_train.shape[1])) 

#print the test image number and shape 
X_test, y_test = load_mnist('', kind='t10k')  
print('Rows: %d, columns: %d' % (X_test.shape[0], X_test.shape[1]))  

#save the train image and lable sperately    
count = np.zeros(10)  
nTrain = len(X_train)
train_labels =[]
fo1 = open('./train_lable/train_lable.txt',"w+")  
for i in xrange(nTrain):  
    label = y_train[i]
    train_labels.append(str(label)+'\n')  
    count[label] += 1  
    #filename = './train/' + str(label) + '/' + str(label) + '_' + str(int(count[label])) + '.png'
    filename = 'train_image/' + str(i) + '_' + str(label) + '.png'   
    img = X_train[i].reshape(28,28)  
    cv2.imwrite(filename, img)
for line in train_labels:  
    fo1.write(line)
fo1.close

#save the train image and lable sperately 
count = np.zeros(10)  
nTest = len(X_test)
test_labels = []
fo2 = open('test_lable/test_lable.txt',"w+")
for i in xrange(nTest):  
    label = y_test[i]
    test_labels.append(str(label) + '\n')  
    count[label] += 1  
    filename = 'test_image/' + str(i) + '.png'  
    img = X_test[i].reshape(28,28)  
    cv2.imwrite(filename, img)
for line in test_labels:
    fo2.write(str(line))
fo2.close

step 3 运行结果

这里写图片描述

这里写图片描述

这里写图片描述

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,以下是一个用 TensorFlow 实现对 MNIST 数据集进行分类的程序: ``` import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data # 加载数据mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) # 定义输入和输出的占位符 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])) y = tf.nn.softmax(tf.matmul(x, W) + b) # 定义损失函数和优化器 cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1])) train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) # 训练模型 sess = tf.InteractiveSession() tf.global_variables_initializer().run() for i in range(1000): batch_xs, batch_ys = mnist.train.next_batch(100) sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}) # 评估模型 correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels})) ``` 这个程序使用了 TensorFlow 的高级 API,可以在几行代码内实现一个简单的神经网络。它的基本思路是,将输入的 28x28 的图像展开成一个 784 维的向量,然后使用一个全连接层将其映射到一个 10 维的输出向量,最后使用 softmax 函数将输出向量转换为概率分布。损失函数使用交叉熵,优化器使用梯度下降算法。在训练过程中,每次从训练集中随机抽取一批数据进行训练,直到达到指定的迭代次数。最后,使用测试集对模型进行评估,输出分类的准确率。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值