Skip to content

Commit 7228a4d

Browse files
authored
Create traffic_sign.py
1 parent fc0bdc6 commit 7228a4d

File tree

1 file changed

+110
-0
lines changed
  • MachineLearning Projects/traffic sign recognition using CNN and Keras

1 file changed

+110
-0
lines changed
Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
import numpy as np
2+
import pandas as pd
3+
import matplotlib.pyplot as plt
4+
import cv2
5+
import tensorflow as tf
6+
from PIL import Image
7+
import os
8+
from sklearn.model_selection import train_test_split
9+
from keras.utils import to_categorical
10+
from keras.models import Sequential, load_model
11+
from keras.layers import Conv2D, MaxPool2D, Dense, Flatten, Dropout
12+
13+
data = []
14+
labels = []
15+
classes = 43
16+
cur_path = os.getcwd()
17+
18+
#Retrieving the images and their labels
19+
for i in range(classes):
20+
path = os.path.join(cur_path,'train',str(i))
21+
images = os.listdir(path)
22+
23+
for a in images:
24+
try:
25+
image = Image.open(path + '\\'+ a)
26+
image = image.resize((30,30))
27+
image = np.array(image)
28+
#sim = Image.fromarray(image)
29+
data.append(image)
30+
labels.append(i)
31+
except:
32+
print("Error loading image")
33+
34+
#Converting lists into numpy arrays
35+
data = np.array(data)
36+
labels = np.array(labels)
37+
38+
print(data.shape, labels.shape)
39+
#Splitting training and testing dataset
40+
X_train, X_test, y_train, y_test = train_test_split(data, labels, test_size=0.2, random_state=42)
41+
42+
print(X_train.shape, X_test.shape, y_train.shape, y_test.shape)
43+
44+
#Converting the labels into one hot encoding
45+
y_train = to_categorical(y_train, 43)
46+
y_test = to_categorical(y_test, 43)
47+
48+
#Building the model
49+
model = Sequential()
50+
model.add(Conv2D(filters=32, kernel_size=(5,5), activation='relu', input_shape=X_train.shape[1:]))
51+
model.add(Conv2D(filters=32, kernel_size=(5,5), activation='relu'))
52+
model.add(MaxPool2D(pool_size=(2, 2)))
53+
model.add(Dropout(rate=0.25))
54+
model.add(Conv2D(filters=64, kernel_size=(3, 3), activation='relu'))
55+
model.add(Conv2D(filters=64, kernel_size=(3, 3), activation='relu'))
56+
model.add(MaxPool2D(pool_size=(2, 2)))
57+
model.add(Dropout(rate=0.25))
58+
model.add(Flatten())
59+
model.add(Dense(256, activation='relu'))
60+
model.add(Dropout(rate=0.5))
61+
model.add(Dense(43, activation='softmax'))
62+
63+
#Compilation of the model
64+
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
65+
66+
epochs = 15
67+
history = model.fit(X_train, y_train, batch_size=32, epochs=epochs, validation_data=(X_test, y_test))
68+
model.save("my_model.h5")
69+
70+
#plotting graphs for accuracy
71+
plt.figure(0)
72+
plt.plot(history.history['accuracy'], label='training accuracy')
73+
plt.plot(history.history['val_accuracy'], label='val accuracy')
74+
plt.title('Accuracy')
75+
plt.xlabel('epochs')
76+
plt.ylabel('accuracy')
77+
plt.legend()
78+
plt.show()
79+
80+
plt.figure(1)
81+
plt.plot(history.history['loss'], label='training loss')
82+
plt.plot(history.history['val_loss'], label='val loss')
83+
plt.title('Loss')
84+
plt.xlabel('epochs')
85+
plt.ylabel('loss')
86+
plt.legend()
87+
plt.show()
88+
89+
#testing accuracy on test dataset
90+
from sklearn.metrics import accuracy_score
91+
92+
y_test = pd.read_csv('Test.csv')
93+
94+
labels = y_test["ClassId"].values
95+
imgs = y_test["Path"].values
96+
97+
data=[]
98+
99+
for img in imgs:
100+
image = Image.open(img)
101+
image = image.resize((30,30))
102+
data.append(np.array(image))
103+
104+
X_test=np.array(data)
105+
106+
pred = model.predict_classes(X_test)
107+
108+
#Accuracy with the test data
109+
from sklearn.metrics import accuracy_score
110+
print(accuracy_score(labels, pred))

0 commit comments

Comments
 (0)