-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathletter_recognition.py
191 lines (141 loc) · 5.4 KB
/
letter_recognition.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
# -*- coding: utf-8 -*-
"""Letter Recognition.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1Q5wslzpK6YVoUwgkRtORaxXFScUUOJNw
#### Importing libraries
"""
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn import svm
from sklearn.neighbors import KNeighborsClassifier
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
"""#### Load the dataset and Split features and target variable"""
!wget https://archive.ics.uci.edu/static/public/59/letter+recognition.zip
!unzip letter+recognition.zip
!ls
# Load the dataset
data = pd.read_csv('letter-recognition.data', header=None)
# Split features and target variable
X = data.iloc[:, 1:]
y = data.iloc[:, 0]
data.head()
data.describe()
data.info()
data.boxplot()
"""#### Splitting the data into training and testing sets"""
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
"""#### Create an SVM classifier"""
svm_model = svm.SVC()
svm_model.fit(X_train, y_train)
svm_predictions = svm_model.predict(X_test)
svm_accuracy = accuracy_score(y_test, svm_predictions)
"""#### Create a KNN classifier"""
knn_model = KNeighborsClassifier()
knn_model.fit(X_train, y_train)
knn_predictions = knn_model.predict(X_test)
knn_accuracy = accuracy_score(y_test, knn_predictions)
"""#### Create a Decision Tree classifier"""
dt_model = DecisionTreeClassifier()
dt_model.fit(X_train, y_train)
dt_predictions = dt_model.predict(X_test)
dt_accuracy = accuracy_score(y_test, dt_predictions)
"""#### Compare the accuracies of the models"""
print("SVM Accuracy:", svm_accuracy)
print("KNN Accuracy:", knn_accuracy)
print("Decision Tree Accuracy:", dt_accuracy)
svm_accuracy = accuracy_score(y_test, svm_predictions)
knn_accuracy = accuracy_score(y_test, knn_predictions)
dt_accuracy = accuracy_score(y_test, dt_predictions)
svm_precision = precision_score(y_test, svm_predictions, average='weighted')
knn_precision = precision_score(y_test, knn_predictions, average='weighted')
dt_precision = precision_score(y_test, dt_predictions, average='weighted')
svm_recall = recall_score(y_test, svm_predictions, average='weighted')
knn_recall = recall_score(y_test, knn_predictions, average='weighted')
dt_recall = recall_score(y_test, dt_predictions, average='weighted')
svm_f1 = f1_score(y_test, svm_predictions, average='weighted')
knn_f1 = f1_score(y_test, knn_predictions, average='weighted')
dt_f1 = f1_score(y_test, dt_predictions, average='weighted')
performance_metrics = pd.DataFrame({
'Algorithm': ['SVM', 'KNN', 'Decision Tree'],
'Accuracy': [svm_accuracy, knn_accuracy, dt_accuracy],
'Precision': [svm_precision, knn_precision, dt_precision],
'Recall': [svm_recall, knn_recall, dt_recall],
'F1-Score': [svm_f1, knn_f1, dt_f1]
})
print(performance_metrics)
"""## Data visualization
#### Class distribution
"""
plt.figure(figsize=(8, 6))
sns.countplot(x=y)
plt.xlabel('Letter')
plt.ylabel('Count')
plt.title('Class Distribution')
plt.show()
"""#### Plotting histograms for each feature"""
plt.figure(figsize=(12, 8))
for i, column in enumerate(X.columns):
plt.subplot(3, 7, i + 1)
plt.hist(X[column], bins=20, edgecolor='black')
plt.xlabel(column)
plt.ylabel('Count')
plt.tight_layout()
plt.show()
"""#### Plotting each letter"""
unique_letters = sorted(data[0].unique())
plt.figure(figsize=(16, 10))
for i, letter in enumerate(unique_letters):
plt.subplot(4, 7, i + 1)
letter_data = data[data[0] == letter].drop(columns=0)
letter_data = letter_data.reset_index(drop=True)
for j in range(len(letter_data)):
plt.plot(range(1, len(letter_data.columns) + 1), letter_data.iloc[j, :], marker='o', linewidth=0.5)
plt.xlabel('Feature')
plt.ylabel('Value')
plt.title(f'Letter: {letter}')
plt.tight_layout()
plt.show()
"""#### Confusion matrix for SVM"""
plt.figure(figsize=(8, 6))
svm_cm = pd.crosstab(y_test, svm_predictions, rownames=['Actual'], colnames=['Predicted'])
sns.heatmap(svm_cm, annot=True, cmap='Blues')
plt.title('Confusion Matrix - SVM')
plt.show()
"""#### Confusion matrix for KNN"""
plt.figure(figsize=(8, 6))
knn_cm = pd.crosstab(y_test, knn_predictions, rownames=['Actual'], colnames=['Predicted'])
sns.heatmap(knn_cm, annot=True, cmap='Blues')
plt.title('Confusion Matrix - KNN')
plt.show()
"""#### Confusion matrix for Decision Tree"""
plt.figure(figsize=(8, 6))
dt_cm = pd.crosstab(y_test, dt_predictions, rownames=['Actual'], colnames=['Predicted'])
sns.heatmap(dt_cm, annot=True, cmap='Blues')
plt.title('Confusion Matrix - Decision Tree')
plt.show()
"""#### Plotting a few input images"""
n_examples = 8
example_indices = np.random.choice(range(len(X_train)), size=n_examples, replace=False)
for i, idx in enumerate(example_indices):
plt.subplot(2, 4, i+1)
example_image = X_train.iloc[idx, :].values.reshape(4, 4)
plt.imshow(example_image, cmap='binary')
plt.title(f"Letter: {y_train.iloc[idx]}")
plt.axis('off')
plt.tight_layout()
plt.show()
"""#### Comparison of accuracies"""
models = ['SVM', 'KNN', 'Decision Tree']
accuracies = [svm_accuracy, knn_accuracy, dt_accuracy]
plt.figure(figsize=(8, 6))
sns.barplot(x=models, y=accuracies)
plt.xlabel('Model')
plt.ylabel('Accuracy')
plt.title('Comparison of Accuracies')
plt.ylim(0, 1)
plt.show()