ImageReader does not support regression
Hi,
First of all some context: I am trying to do landmark detection for faces, so I have several output labels with a SquareError loss. I got to run CNTK perfectly for this task using the UCIFastReader, but when I tried to use the ImageReader, I found that it does not support regression, i.e., it does not read more than 1 label because classification is automatically assumed in the code, the label is represented as "size_t m_classId" in ImageDataDeserializer, etc. Maybe even worse: it does so silently, so it took me a while to figure out why the regression did not work.
Landmark detection is the most likely scenario I can think of where this is an issue. But there are probably other regression tasks on images.
In the long run, it is no good option for me to use the TextReaders because I have frequently-changing datasets. Just changing the label file for the ImageReader would be much faster and also saves disk space. I need sub-pixel accuracy, so trying some discrete softmax workaround is futile.
The code which reads multiple labels for regression and the code which reads images (and crops them, etc.) is obviously all there. Still it seems like the architecture of the ImageReader differs greatly from the architecture of the UCIFastReader, for example, so bringing these parts together in a consistent and concise way is a little more involved than simple copy+paste. I know that UCIFastReader is deprecated, but I have not taken a closer look at the TextFormatReader, yet.
The good news: I am willing to implement the necessary changes myself and post a pull request. I already checked some of the CNTK source and got it all set up in Visual Studio. However, I am not very familiar with the project source, so I might need a few hints about where to start and how to best tackle the problem. Otherwise, I fear that it might become some messy workaround which nobody but me can use :-)
For example, would it be better to adapt the ImageReader to account for regression, or rather adapt either of the TextReaders to account for image data (or maybe inherit from it)? Which classes would be involved apart from ImageReader? Very likely ImageDataDeserializer, probably ImageConfigHelper. ImageTransformers should also have a way to apply their transformations to the labels as well (that's probably a follow-up issue). How about other classes/files? Is there maybe even some work in progress on this (I didn't find anything)?
I would appreciate any advice.
Best, Daniel
hello,
coincidentally i tried to use cntk ucifastreader for regression for face landmarks, i try many times but the output of the model always was the mean of the level position, in other words the model learned the mean and dont work. your model with ucifastreader works?
Could you share the cntk configuration or the dataset, please?
my email is [email protected]... thank you so much for the help, i have to make this regressor for academic porpouse
Hi Daniel,
Thank you very much for your desire to contribute!
UCIFastReader is deprecated, so it is better to have your changes in the ImageReader and CNTKTextFormat. Please take into account that CNTKTextFormatReader does not support binary format, so if you need to use images as input data you should pick up the ImageReader.
Could you please describe your scenario in more detail - are labels just single floats? or sequences? or other images? Currently we are working on the composition of the deserializers, so that you effectivly can combine different deserializers as soon as they share common logical sequence keys.
When the work is finished (will take couple of weeks to lend) you will be able to combine different deserializers. For the sample of the config how it will look like please can have a look Tests/EndToEndTests/Speech/ExperimentalHtkmlfReader/LSTM/FullUtterance/cntk.cntk, we already impelmented this feature for HTK and MLF deserializers and currently working on the image deserializer.
The idea is that if you need a new functionality you will only have to add/adapt the corresponding deserializer or transformers. As you correctly pointed out the only class you potentially will need to change is the ImageDataDeserializer.
If you need to support labels as simple floats/doubles (not categories), here is the proper way to change the ImageDataDeseriazlier:
- introduce a new config for the label section in the config, i.e. type="regression" | "category", default is category in order to not break current behavior
- adapt the ImageConfigHelper to return this information
- you have to adapt CreateSequenceDescriptions, when the file is parsed you need to remember corresponding value of the label
- you have to adapt GetSequence to return a sequence for the label that contains the value, not the category
Thanks!
@rodrigoalor Sure. I uploaded a set of example files: https://www.dropbox.com/sh/uicrtl1hetf361r/AAC598RYxEppHRol57Oktedna?dl=0 . The data is from Kaggle Facial Keypoint detection challenge with just a little preprocessing (replace comma by spaces and handle missing labels in the data). Basically, the file structure needed in this case is: 2x15 = 30 (xy) floating point landmark positions (space-separated) immediately followed by 96x96 = 9216 grayscale pixel values (space-separate, 0 to 255). Note: The file(s) should not end with a newline "\n" because otherwise the last entry will not be read by the reader. Further note: I am not entirely sure whether the labels are actually read as floating point (opposed to some int type). I did not debug it, but I think they are.
@eldakms Thank you for the information. It already helps a lot!
Concerning the scenario: each image is labeled with a vector of floats (x and y coordinates of each landmark in the image). So for 10 landmarks, e.g., there would be 20 floating point labels per image. For example, [x1 y1 x2 y2 ... x10 y10]. The actual order does not matter.
I noticed the "KeyType" composition of deserializers that you mentioned. From what I see in the example you referenced, it is also planned to be able to combine the readers to, say, read features from fileA with Reader1 but labels from fileB with Reader2. Is that correct? This would allow to read the images with the ImageReader and the labels by a TextFormatReader, for example. My guess is that the implemented versions for HTK and MLF deserializers are included in trunk, given that the test is there already. Or are they currently in a separate branch?
I will see if I can figure out how the "KeyType"-thing is supposed to work from the example and try to consider it while adapting the ImageReader. This week is a busy one for me, but starting from next week, I will be able to work on this close to full time (I'm a PhD student). I am confident that I can make some progress now with the information you provided. Thanks a lot.
Hi Daniel,
Yes, we plan to allow combining different deserializers (i.e. Image and FormatText) using logical keys (KeyType), but this is not yet supported, i.e. Image reader works with file names, and has no idea about logical keys of these files/data as of yet (even though the interface is there).
Regarding HTKMLF sample, the code is already in master. The mentioned deserializers are in Source/Readers/ExperimentalHTKMLF.
Thank you!
Hi again,
I got a basic version working now. The current tests still pass. I have not yet written a test for the new ImageReader though. Furthermore, my solution right now is still slightly "hacky" in a way I will elaborate shortly.
First of all: is it desired that I write one or several Tests for the new code before submitting a pull request? If so, what should I test against? How would a unit test look like compared to an end-to-end test? I could try to validate the ImageReader by comparing the output to the (same) UCIFastReader that I got to work already. Since the randomization interface is different, I would have to disable randomization for this, but I am not sure whether it's a clever idea at all to compare the results of new code to the results of depricated old code.
Concerning the "hacky" solution: When accounting for the new label type (vector < float/double > instead of size_t), some of the current (abstract) interfaces do not work anymore and cannot be changed easily. For example, the LabelGenerator expects some SparseSequenceData&, SSD, (which derives from SequenceDataBase, SDB) as argument in order to call some SSD-specific members. Therefore, the LabelGenerator is unsuitable for DenseSequenceData, DSD, even though it shares the SDB Interface.
A similar situation appears in ImageDataDeserializer::CreateSequenceDescriptions where the SequenceDescription holding the labels must be put together.
Some "trivial" solutions I tried, e.g., using templates, failed so far. My intuition tells me that the "cleanest", most elegant solution would be to employ some kind of double dispatch here, but I have to admit that I have not thought about it very deeply, yet.
Still, the whole reason for this problem is that the labels have to be stored at all (very temporally) just to be passed to the parent shortly after.
My current workaround is to have ImageSequenceDescription own one member for each of the three label types. I later use a number of ugly switch/if-statements to select which of these members will be written to / read from. This is very error-prone because one has to rely on the correct member to be selected by hand instead of some proper dynamic dispatch mechanism.
Another thing to consider is that, once reading from different streams will be implemented, there will be no more need to read regression labels with the ImageReader at all. Therefore, I am not entirely sure whether it is even worth the effort to build some nice architecture around it.
Do you have an idea about how to best deal with this (from a conceptual point of view)?
I tried to stick to the coding guidelines as well as possible, but I am new to the project and might have failed in a few places. A pull request would probably still be premature as of now given the (in my opinion) ugly solution.
My current version is accessible here: https://github.com/DanielMerget/CNTK/tree/image_regression
Two other, only indirectly related, small bugs I was able to fix (pull-requests already sent) which are required for the above solution to work properly: https://github.com/DanielMerget/CNTK/tree/bugfix_grayscale https://github.com/DanielMerget/CNTK/tree/bugfix_multiview
Best, Daniel
Hi Daniel,
Regarding the tests: we always recommend include tests with pull requests. You can create unit tests (i.e. for readers, samples are at Tests/UnitTests/ReaderTests/Tests.cpp) or end to end tests (i.e. Tests/EndToEndTests/AlexNet/). End to end tests can be later integrated into our build procedure, but at start I would stick with self contained unit tests, especially if you change a single part of the system (i.e. image reader).
Regarding the hacky solution: We already have a lot of code debt in CNTK, so hacks should be avoided. (You can have hacks in your forks/branches to unblock you, but we should keep the master codebase clean).
As for your scenario - please have a look at the eldak/addingLogicalKeyToImageDeserializer branch. It is work in progress, but you can give early feedback whether this will address your scenario. Please have a look at the ImageAndTextReaderSimple unit test in ImageReaderTests.cpp (it is still red for now), the config is in ImageAndTextReaderSimple_Config.cntk. It shows how you will be able to combine several deserializers with each other:
reader = [ verbosity=0 randomize=true
deserializers=[
[
type="CNTKTextFormatDeserializer"
module="CNTKTextFormatReader"
file = "$RootDir$/ImageAndTextReaderSimple_labels.txt"
input=[
labels=[
dim=4
format="sparse"
]
]
]:[
type="ImageDataDeserializer"
module="ImageReader"
file = "$RootDir$/ImageAndTextReaderSimple_map.txt"
input=[
features=[
transforms=[
[
type="Crop"
cropType=Center
cropRatio=1.0
jitterType=UniRatio
]:[
type="Scale"
width=4
height=8
channels=3
interpolations=Linear
]:[
type="Mean"
]:[
type="Transpose"
]
]
]
# Currently the image deserializer always has labels, we read but ignore them.
# Code should be adapted if the labels are not specified.
ignored=[
labelDim=4
]
]
]
]
Please keep in mind, this is work in progress, the code has not been tested yet, maybe you can help me to add test this as well :)
Thank you very much for the contributions!
Hi Daniel,
Please have a look at the ImageAndTextReaderSimple unit test on master. It takes images from ImageDeserializer and labels from CNTKTextFormat. Thanks!
Hi again,
thanks for the update. I will definitely check it out soon.
I recently refactored my implementation of image regression and also wrote two unit tests for it. I pushed the updates into https://github.com/DanielMerget/CNTK/tree/image_regression
Basically, I made ImageDataDeserializer a template which depends on both the LabelType (Classification/Regression) and Precision (float/double). The downside is that most of the code is now a template and as such resides in the header file. However, on the positive side, (> 90%) the code is now statically dispatched to the right place without error-prone run-time checks. At the cost of ~20-30 more lines of code I could make it 100% static, but personally I don't have the feeling that this is necessary, given that the few remaining dynamic parts are easy-to-understand one-liners.
I still have to merge my version with the current master in order to submit a pull request. Before I do that, however, it would be helpful to know whether it generally complies with your quality demands and guidelines.
Could you maybe give it a quick inspection and share your thoughts? Or should I simply merge it and create a pull request right away?
Best, Daniel
Any update on this?
Could you please have a look here, whether this solves your problem (combining image reader and text format for labels)
https://github.com/Microsoft/CNTK/wiki/Deserializers-and-Transforms
Thanks for the reply!
Maybe I was not clear enough earlier: I was already able to solve my problem by means of enabling regression for ImageReader myself, see https://github.com/DanielMerget/CNTK/tree/image_regression
Considering the example you gave me earlier in this thread, I am convinced that it would also work in the master branch by combining two different deserializers. I have not tried it, though, given that I could solve the problem already. For my scenario, your solution is a not-so-complicated and robust "workaround", but I would still consider a single deserializer superior because it is more clear what belongs to where when trying to inspect the files by hand.
I would happily provide a merge of my version with master with a subsequent pull request in order to have both options available. However, the merge is very involved (basically two unrelated rewrites of the whole ImageDataDeserializer have to be merged correctly), so I want to make sure I don't do the work for nothing.
Of course, it may be difficult for you to forecast whether a pull request will be acceptable. But if you consider the "regression for ImageReader" as something that you would like to have in your master branch, I can do the job. Just wanted to know whether you consider it more as "please go ahead, we appreciate it and are looking forward to it" or rather along the lines of "actually we don't really need it. There is an alternative solution already supported and supporting both solutions makes it unnecessarily complex (for us in the future to maintain)".
A final remark: I like the approach of combining different deserializers for different streams or different data sets a lot, as it is far more flexible for the community. In my opinion, what is still missing is the combination of different deserializers for the same stream. What I mean by that is, for example, for a 40-dimensional label vector (regression), I could read labels 1 to 20 from one file and labels 21 to 40 from another file. In exaggerated form, this would allow to read every entry of the label vector from a different file, or even from the same file but in different order, maybe skipping some entries, etc. (e.g., using something similar to the start parameter in UCIFastReader [I don't know if it exists for TextFormatReader]). From what I understood, this is not yet possible. Is it planned, though? It would definitely be superior even in my scenario.
Hi Daniel, Most probably, we will go with composition for now. But let me bring this to the team and come back to you later next week. Thank you very much for your patience and all effort you put into cntk to make it better!
Hi Daniel, We settled on composition for now. If you need any help with converting your data to the required format please ping me, I will be happy to help. Thank you!
Good to know, thank you. Conversion will not be a problem, but thanks anyway! I guess the issue can be closed then :-) Also, thanks again for the support!
For an example on how to train a regression model on images using the image reader see here: https://github.com/Microsoft/CNTK/wiki/Train-a-regression-model-on-images.