簡體   English   中英

MNIST上的Tensorflow教程

[英]Tensorflow tutorial on MNIST

這個 Tensorflow教程將已經存在的數據集(MNIST)加載到代碼中。 相反,我想插入自己的訓練和測試圖像。

def main(unused_argv):
# Load training and eval data
mnist = tf.contrib.learn.datasets.load_dataset("mnist")
train_data = mnist.train.images # Returns np.array      
train_labels = np.asarray(mnist.train.labels, dtype=np.int32)
eval_data = mnist.test.images # Returns np.array
eval_labels = np.asarray(mnist.test.labels, dtype=np.int32)

它說它返回一個原始像素值的np數組。

我的問題:

1.如何為自己的圖像集創建這樣的numpy數組? 我想這樣做,所以我可以直接用numpy數組代替示例代碼中的MNIST數據,並根據我的數據(0-9和AZ)訓練模型。

編輯:在進一步分析中,我已經意識到mnist.train.imagesmnist.test.images中的像素值已從0到255歸一化為0到1(我想)。

文件夾結構:培訓和測試文件夾位於同一文件夾中

Training folder:
--> 0
    -->Image_Of_0.png
--> 1
    -->Image_Of_1.png
.
.
.
--> Z
    -->Image_Of_Z.png

Testing folder:
--> 0
    -->Image_Of_0.png
--> 1
    -->Image_Of_1.png
.
.
.
--> Z
    -->Image_Of_Z.png

我寫的代碼:

Names = [['C:\\Users\\xx\\Project\\training-images', 'train',9490], ['C:\\Users\\xx\\Project\\test-images', 'test',3175]]

#9490 is the number of training files in total (All the PNGs)
#3175 is the number of testing files in total (All the PNGs)
for name in Names:
FileList = []
for dirname in os.listdir(name[0]):
    path = os.path.join(name[0], dirname)
    for filename in os.listdir(path):
        if filename.endswith(".png"):
            FileList.append(os.path.join(name[0], dirname, filename))
print(FileList) 


## Creates list of all PNG files in training and testing folder

x_data = np.array([np.array(cv2.imread(filename)) for filename in FileList])
pixels = x_data.flatten().reshape(name[2], 2352)   #2352 = 28 * 28 * 3 image
print(pixels)

是否可以將創建的像素數組作為訓練和測試數據提供,即它與示例代碼中提供的數據具有相同的格式嗎?

2.同樣,必須為所有標簽創建哪個numpy數組? (文件夾名稱)

1.如何為自己的圖像集創建這樣的numpy數組?

TensorFlow以多種方式(tf.data,feed_dict,QueueRunner)接受數據。 您應該使用的是TFRecord,可通過tf.data API進行訪問。 也是推薦的格式 假設您有一個包含圖像的文件夾,並且想要將其轉換為tfrecord文件。

import tensorflow as tf 
import numpy as np
import glob
from PIL import Image

# Converting the values into features
# _int64 is used for numeric values

def _int64_feature(value):
return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))

# _bytes is used for string/char values

def _bytes_feature(value):
return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))
tfrecord_filename = 'something.tfrecords'

# Initiating the writer and creating the tfrecords file.

writer = tf.python_io.TFRecordWriter(tfrecord_filename)

# Loading the location of all files - image dataset
# Considering our image dataset has apple or orange
# The images are named as apple01.jpg, apple02.jpg .. , orange01.jpg .. etc.

images = glob.glob('data/*.jpg')
for image in images[:1]:
  img = Image.open(image)
  img = np.array(img.resize((32,32)))
label = 0 if 'apple' in image else 1
feature = { 'label': _int64_feature(label),
              'image': _bytes_feature(img.tostring()) }

#create an example protocol buffer
 example = tf.train.Example(features=tf.train.Features(feature=feature))

#writing the serialized example.
 writer.write(example.SerializeToString())
writer.close() 

現在閱讀此tfrecord文件並做一些事情

import tensorflow as tf 
import glob
reader = tf.TFRecordReader()
filenames = glob.glob('*.tfrecords')
filename_queue = tf.train.string_input_producer(
   filenames)
_, serialized_example = reader.read(filename_queue)
feature_set = { 'image': tf.FixedLenFeature([], tf.string),
               'label': tf.FixedLenFeature([], tf.int64)
           }

features = tf.parse_single_example( serialized_example, features= feature_set )
label = features['label']

with tf.Session() as sess:
  print sess.run([image,label]) 

這是tensorflow /示例中的MNIST示例

干杯!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM