<jupyter_start><jupyter_text>Importing the Required Libraries<jupyter_code>import cv2 # for using computer vision related functions
import numpy as np # for numerical computations on 2D image array
import pandas as pd # for dataset preparation for deep learning libraries
import matplotlib.pyplot as plt # for displaying image and plotting graph<jupyter_output><empty_output><jupyter_text>Reading our Processed Dataset<jupyter_code># the different classes of our shapes
categories = ["circle", "square", "star", "triangle"]
dataset = pd.read_csv("/content/drive/MyDrive/sem 8/CV/processed_shapes/shapes.csv")
dataset.drop("Unnamed: 0", axis = 1, inplace = True)
features = dataset.columns[:-1]
target = "target"
dataset
print(dataset[target].value_counts())
dataset[target].value_counts().plot(kind = 'bar', title = "bar graph of counts of instances of different classes");<jupyter_output>star        3765
square      3765
triangle    3720
circle      3720
Name: target, dtype: int64<jupyter_text>Transforming classes to integer values<jupyter_code>mapping_dict = dict(zip(categories, range(len(categories))))
mapping_dict
dataset[target] = dataset[target].map(mapping_dict)
dataset[target].plot(legend = "class values", title = "line graph of class values");
# defining width and height of image
img_width, img_height = 25, 25
# visualizing the first entry of the dataset
img = dataset.iloc[0, :-1].to_numpy().reshape(img_width, img_height)
plt.imshow(img, cmap = 'binary_r'), plt.show();

# visualizing the last entry of the dataset
img = dataset.iloc[-1, :-1].to_numpy().reshape(img_width, img_height)
plt.imshow(img, cmap = 'binary_r'), plt.show();<jupyter_output><empty_output><jupyter_text>Applying Gaussian Naive Bayes  Importing required libraries<jupyter_code>import random # for generating random numbers
import seaborn as sns # for plotting confusion_matrix
from sklearn.metrics import confusion_matrix # for obtaining confusion_matrix
from sklearn.naive_bayes import GaussianNB # using probabilistic machine learning model
from sklearn.metrics import accuracy_score # for computing accuracy
from sklearn.model_selection import train_test_split # for splitting training and testing dataset

# for projecting data into a lower dimensional space to improve accuracy
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis as LDA<jupyter_output><empty_output><jupyter_text>Splitting the dataset into training and testing sets<jupyter_code>X_train, X_test, y_train, y_test = train_test_split(dataset[features], dataset[target], test_size = 0.25, random_state = 42)
clf = GaussianNB()
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
accuracy_score(y_test, y_pred)
cf_mat = confusion_matrix(y_test, y_pred)

df_cm = pd.DataFrame(cf_mat, index =  range(4), columns = range(4))
plt.figure(figsize = (10,7))
sns.heatmap(df_cm, annot=True);<jupyter_output><empty_output><jupyter_text>Using LDA to project data into a 3D Space to improve accuracy<jupyter_code>lda = LDA(n_components = 3)
lda.fit(X_train, y_train)
X_train = lda.transform(X_train)
X_test = lda.transform(X_test)
clf = GaussianNB()
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
accuracy_score(y_test, y_pred)
cf_mat = confusion_matrix(y_test, y_pred)

df_cm = pd.DataFrame(cf_mat, index =  range(4), columns = range(4))
plt.figure(figsize = (10,7))
sns.heatmap(df_cm, annot=True);
rows = 4
cols = 4

plt.figure(figsize = (cols * 4, rows * 4))
rdm_indices = np.random.randint(low = 0, high = dataset.shape[0], size = rows * cols)
y_pred = clf.predict(lda.transform(dataset.iloc[rdm_indices, :-1]))

for i in range(rows * cols):
  img = dataset.iloc[rdm_indices[i], :-1].to_numpy().reshape(img_width, img_height)
  plt.subplot(rows, cols, i + 1), plt.axis("off")
  plt.title(f"true: {dataset.iloc[rdm_indices[i], -1]}, pred: {y_pred[i]}")
  plt.imshow(img, cmap = "binary_r")
  
plt.show();
# !pip install cPickle
import _pickle as cPickle
# save the classifier
with open('/content/drive/MyDrive/sem 8/CV/processed_shapes/gauss-without-lda.pkl', 'wb') as fid:
    cPickle.dump(clf, fid)
# load it again
with open('/content/drive/MyDrive/sem 8/CV/processed_shapes/gauss-without-lda.pkl', 'rb') as fid:
    clf_loaded = cPickle.load(fid)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.11674888419074465, 'fraction_numerical': 0.01432933991073526, 'mean_word_length': 6.341379310344828, 'pattern_counts': {'":': 0, '<': 24, '<?xml version=': 0, '>': 24, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '6', 'dir': 'jupyter-structured-clean-dedup', 'id': '603401', 'license': 'Xnet', 'n_tokens_mistral': 1525, 'n_tokens_neox': 1451, 'n_words': 370, 'path': 'CV_Project_Approach_2_ML_Training.ipynb', 'repo_name': 'Amagnum/2D-shapes-Recognition-using-Guassian-based-probabilistic-Learning', 'size': '4257'}