-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
91 lines (76 loc) · 2.6 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# python 3.7
# Scikit-learn ver. 0.23.2
from imblearn import pipeline
from scipy.sparse import data
from sklearn import preprocessing
from sklearn.linear_model import LogisticRegression
from sklearn.linear_model import SGDClassifier
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
from sklearn.model_selection import RepeatedStratifiedKFold
from sklearn.metrics import plot_confusion_matrix
from sklearn.tree import DecisionTreeClassifier
# Imblearn
from imblearn.over_sampling import RandomOverSampler
from imblearn.under_sampling import RandomUnderSampler
from imblearn.pipeline import Pipeline
from imblearn.over_sampling import SMOTE
# OpenCv
import cv2
# matplotlib 3.3.1
from matplotlib import pyplot
# Numpy
import numpy as np
# DataLoader
from DataLoader import Dataset
# from DataLoader import MiniBatch
# Pickle
import pickle
# Hyperparameters
epochs = 20
batch_size = 64
max_each_class = 1000
def main():
train()
def train():
data_loader = Dataset('Recaptcha_Data_2\\', batch_size=batch_size, max_each_class=1000)
# Verify Sizes
print(f'Data Loader Length: {len(data_loader)}')
# Declare Model
model = SGDClassifier(random_state=0, loss='hinge', penalty='l2') # verbose=1
# Train Loop
# Set Rounds Per Epoch
rounds_per_epoch = int(len(data_loader)/batch_size)
# Test Data
test_x, test_y = data_loader.get_test_data()
for epoch in range(epochs):
for round in range(rounds_per_epoch):
data, label = data_loader.get_next_batch()
model.partial_fit(data, label, classes=data_loader.num_classes_list)
if round % 15 == 0:
print(f'Batches Checked: {round}/{rounds_per_epoch}')
print(f'Epoch: {epoch}/{epochs}')
test(model, test_x, test_y)
data_loader.reset_index()
plot_confusion_matrix(model, test_x, test_y)
for i in range(len(test_y)):
check_image(test_x[i], test_y[i], model)
def test(model, test_x_final, test_y_final):
preds = model.predict(test_x_final)
correct = 0
incorrect = 0
for pred, gt in zip(preds, test_y_final):
if pred == gt: correct += 1
else: incorrect += 1
print(f"Correct: {correct}, Incorrect: {incorrect}, % Correct: {correct/(correct + incorrect): 5.2}")
pyplot.show()
def check_image(image, label, model):
print(f'Label: {label}')
prediction = model.predict(image.reshape(1, -1))
print(f'Prediction {prediction}')
image = image.reshape(200, 100, 3)
cv2.imshow('Image', image)
cv2.waitKey(0)
cv2.destroyAllWindows()
if __name__ == "__main__":
main()