-
Notifications
You must be signed in to change notification settings - Fork 4
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Adding a CNN-based classifier for the task of entries/other classification #5
Open
iamgroot42
wants to merge
2
commits into
FreeUKGen:master
Choose a base branch
from
iamgroot42:image_classification
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 1 commit
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
*.pyc |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
## Classification of images into entry/other | ||
|
||
### Proposed Technique | ||
* Convert all images into Black&White. | ||
* Downsize all images into (150, 250) | ||
* Define a simple CNN-classifier and train it on the given data | ||
* Batch-normalization is used to handle the variance in given data, while automatic class-weights are used to balance the error function (as the class distribution is biased) | ||
* To account for the low amount of data given, a small learning rate is used (to avoid overfitting) | ||
|
||
### Running it | ||
* Run `python trainClassifier.py <images_folder> <label_file>` from the current directory to train an end-to-end model. | ||
* For example, run `python trainClassifier.py images/freecen/ data/gold/combined_classifications_20180227.csv` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,29 @@ | ||
import keras | ||
from keras.models import Sequential | ||
from keras.layers import Dense, Dropout, Flatten, Activation | ||
from keras.layers import Conv2D, MaxPooling2D, BatchNormalization | ||
|
||
# Define a simple CNN model | ||
def getSimpleCNN(input_shape, num_classes): | ||
model = Sequential() | ||
model.add(Conv2D(16, kernel_size=(3, 3), input_shape=input_shape)) | ||
model.add(BatchNormalization()) | ||
model.add(Activation('relu')) | ||
model.add(Conv2D(32, (3, 3))) | ||
model.add(BatchNormalization()) | ||
model.add(Activation('relu')) | ||
model.add(MaxPooling2D(pool_size=(2, 2))) | ||
model.add(Dropout(0.25)) | ||
model.add(Flatten()) | ||
model.add(Dense(64)) | ||
model.add(BatchNormalization()) | ||
model.add(Activation('relu')) | ||
model.add(Dropout(0.5)) | ||
model.add(Dense(num_classes, activation='softmax')) | ||
|
||
model.compile(loss=keras.losses.categorical_crossentropy, | ||
optimizer=keras.optimizers.Adadelta(lr=0.1), | ||
metrics=['accuracy']) | ||
|
||
return model | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
import numpy as np | ||
from PIL import Image | ||
import os | ||
from tqdm import tqdm | ||
from scipy.misc import imresize | ||
import csv | ||
|
||
# Read label classification file, construct data | ||
def getData(imageDirPrefix, filePath): | ||
X = [] | ||
Y = [] | ||
with open(filePath, 'r') as f: | ||
reader = csv.reader(f) | ||
for line in tqdm(reader): | ||
filePath = line[0] | ||
imgClass = line[1] | ||
# Read image as a black&white image | ||
image = np.asarray(Image.open(os.path.join(imageDirPrefix, filePath)).convert('L')) | ||
# Resize into a smaller image | ||
image = imresize(image, (150, 250)) | ||
X.append(image) | ||
Y.append(imgClass) | ||
X = np.array(X) | ||
X = X.reshape(X.shape + (1,)) | ||
# Also store the mapping between class-names and indices | ||
mappingDict = dict([(y,x) for x,y in enumerate(sorted(set(Y)))]) | ||
Y = np.array([ mappingDict[x] for x in Y]) | ||
return X, Y, mappingDict | ||
|
||
|
||
if __name__ == "__main__": | ||
import sys | ||
X, Y, mapping = getData(sys.argv[1], sys.argv[2]) | ||
print X.shape, Y.shape | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
import readData | ||
import model | ||
import keras | ||
|
||
|
||
if __name__ == "__main__": | ||
import sys | ||
# Load data | ||
X, Y, mapping = readData.getData(sys.argv[1], sys.argv[2]) | ||
num_classes = len(mapping.keys()) | ||
input_shape = X.shape[1:] | ||
# Loada simple CNN for tha classification task | ||
model = model.getSimpleCNN(input_shape, num_classes) | ||
Y = keras.utils.to_categorical(Y, num_classes) | ||
batch_size = 8 | ||
epochs = 20 | ||
# Train our model on the available data | ||
model.fit(X, Y, batch_size=batch_size, epochs=epochs, validation_split=0.2, class_weight='auto') | ||
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Why is indentation change not causing Python to vomit?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Oh well. Not sure how I missed it :(
Fixed it now