CNTK icon indicating copy to clipboard operation
CNTK copied to clipboard

Prepare dataset similar to CIFAR-10 dataset

Open gsrungarapu opened this issue 9 years ago • 11 comments

I am referring to https://github.com/Microsoft/CNTK/wiki/Hands-On-Labs-Image-Recognition

Did anyone created their own images data into CIFAR-10 dataset?

gsrungarapu avatar May 04 '17 14:05 gsrungarapu

Did you get a chance to look at the scripts under: https://github.com/Microsoft/CNTK/tree/master/Examples/Image/DataSets/CIFAR-10

cha-zhang avatar May 08 '17 00:05 cha-zhang

Yes, I did. If I use that saveMean() function from the code it just generated 0's in the xml file as it uses dataMean input from saveTrainImages() method. dataMean = np.zeros(3, ImageSize, ImageSize)

I actually wanted to train using above tutorial on my own dataset(ie., just a collection of jpeg images) which are not in batch files, unlike CIFAR-10 dataset in the tutorial which has batch files.

So, I removed all the code where it calls the batch files and trying to run the code just with the meanFile.xml. But my concern is, this meanFile has no data as it generates all zeros in the file and the results are not correct.

Do you know how to create a correct mean file or is there a script that I can leverage to create batch files just like CIFAR data?

Thanks much!

gsrungarapu avatar May 10 '17 16:05 gsrungarapu

What do you mean by batch files? something like train_map.txt?

cha-zhang avatar May 10 '17 18:05 cha-zhang

no, I mean the CIFAR dataset comes with data_batch_1, data_batch_2, ..., data_batch_5, as well as test_batch each with 10000 images right? Each of these files is a Python "pickled" object https://www.cs.toronto.edu/~kriz/cifar.html

gsrungarapu avatar May 10 '17 18:05 gsrungarapu

You must have loaded the images incorrectly. If you already have a list of images, all you need to do is to put them in different folders, and create a train_map.txt file to specify the labels.

For most networks, you don't need the mean file. Just subtract a constant like 128 (see, e.g., AlexNet example) would be sufficient and the rest can be learned by the network.

cha-zhang avatar May 10 '17 18:05 cha-zhang

Oh, I see. Appreciate your inputs cha-zhang. Can you please point out the link for AlexNet example? I want to use CNTK to run the image recognition on my own set of images. Is there a direct link which I can follow - like the tutorials below?

Because I am right now following these two examples. In 201B example, create_reader() function takes two arguments map_file and mean_file. CIFAR-10 Examples: CNTK_201A_CIFAR-10_DataLoadeer.ipynb and CNTK_201B_CIFAR-10_ImageHandsOn.ipynb https://github.com/Microsoft/CNTK/tree/master/Tutorials

Thanks!

gsrungarapu avatar May 10 '17 19:05 gsrungarapu

Lots of image examples under: https://github.com/Microsoft/CNTK/tree/master/Examples/Image

cha-zhang avatar May 10 '17 21:05 cha-zhang

Just subtract a constant like 128 (see, e.g., AlexNet example) would be sufficient ---> does that mean I will subtract 128 from the image that we want to evaluate? image data is in numpy array format. We should do it on the image that I want to predict based on the model?

I also tried to run AlexNet model using python distribution by adjusting the image size (300x300x3)accordingly; but it throws below error: Looks like something to do with the parameters like minibatchsize/epochsize etc.., Do you have any suggestions? thanks!

alexneterror

gsrungarapu avatar May 10 '17 23:05 gsrungarapu

Hi I am using a basic model as below to train on my own data. However, the results does not get better. Do you think this is sufficient enough to reap the benefit of neural nets to classify images? I have train, test folders for images(300x300 size), map files and a mean file for all images (created by adding all image numpy arrays data and divided by total train size)

` def create_basic_model(input, out_dims):

     net = Convolution((5,5), 300, init=glorot_uniform(), activation=relu, pad=False)(input)
     net = MaxPooling((3,3), strides=(2,2))(net)

      net = Convolution((5,5), 300, init=glorot_uniform(), activation=relu, pad=False)(net)
      net = MaxPooling((3,3), strides=(2,2))(net)

      net = Convolution((5,5), 600, init=glorot_uniform(), activation=relu, pad=False)(net)
      net = MaxPooling((3,3), strides=(2,2))(net)

     net = Dense(600, init=glorot_uniform())(net)
     net = Dense(out_dims, init=glorot_uniform(), activation=None)(net)

    return net

def create_reader(map_file, mean_file, train):

# transformation pipeline for the features has jitter/crop only when training
transforms = []
if train:
    transforms += [xforms.crop(crop_type='randomside', side_ratio=0.8)] # train uses data augmentation (translation only)
    #print (transforms)
transforms += [
    xforms.scale(width=image_width, height=image_height, channels=num_channels, interpolations='linear'),
    xforms.mean(mean_file)
]
print (transforms)
# deserializer
return (ImageDeserializer(map_file, StreamDefs(
    features = StreamDef(field='image', transforms=transforms), # first column in map file is referred to as 'image'
    labels   = StreamDef(field='label', shape=num_classes)      # and second as 'label'
)))

def train_and_evaluate(reader_train, reader_test, max_epochs, model_func):

input_var = C.input((3,300,300))
label_var = C.input((2))
feature_scale = 1.0 / 256.0
input_var_norm = element_times(feature_scale, input_var)
z = model_func(input_var_norm, out_dims=2) #out_dims changed from 2 to 3
return softmax(z)

def eval(pred_op, image_path):

label_lookup = ["food", "menu"]
image_mean   = 133.0
image_data   = np.array(PIL.Image.open(image_path), dtype=np.float32)
image_data  -= image_mean
image_data   = np.ascontiguousarray(np.transpose(image_data, (2, 0, 1)))
result       = np.squeeze(pred_op.eval({pred_op.arguments[0]:[image_data]}))
print(result)

    reader_train = create_reader('train_map.txt',  'datamean.xml',True)

reader_test = create_reader('test_map.txt', 'datamean.xml',False) pred = train_and_evaluate(reader_train, reader_test, max_epochs=0, model_func=create_basic_model) eval(pred, "Sample.jpg") `

gsrungarapu avatar May 11 '17 18:05 gsrungarapu

This is how I replicated the CIFAR-10 dataset (available in batch format) and able to successfully train and evaluate my own image data for image classification problems.

Steps:

  1. Maintain a folder structure ex: batch_1 to batch_n. Each batch folder contains subfolders where each subfolder will contain images of a specific class.
  2. Write a python code for example: Process_batch_files() function that can process each batch folder, subfolders and outputs a single large 2-D numpy array of all images in that batch folder where each row contains the image information written in the RGB (CHW) channel sequence with row major order at each channel for the entire image. Also in the code, you can maintain the labels information in a separate list (each subfolder in a batch file will be assigned a class label and append to the list). Once, we have all the image data for each image (in a numpy array) and the label data for each image (in a list), just perform a horizontal stack operation on both these objects. Like it is mentioned in the 201A tutorial under readBatch().

res = np.hstack(complete_image_nparray , np.reshape(labels, (len(labels),1))) 3. Once we have the above code, you can alter the saveTrainImages() and saveTestImages() method in the tutorial to suit your needs like imageSize, trainsize, testsize etc.. When we run the 201A now, we can get the meanFile and map files for both train and test images.

  1. Now alter the 201B tutorial, with your needs and run the basic neural net model.

gsrungarapu avatar May 16 '17 15:05 gsrungarapu

Hi gsrungarapu,

I am new to python, was wondering if you could share your code

aench2023 avatar Sep 12 '17 21:09 aench2023