{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-04-06T13:20:33.675242Z","iopub.execute_input":"2023-04-06T13:20:33.675712Z","iopub.status.idle":"2023-04-06T13:20:33.694478Z","shell.execute_reply.started":"2023-04-06T13:20:33.675675Z","shell.execute_reply":"2023-04-06T13:20:33.692598Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport cv2\nfrom PIL import Image\n\nimport tensorflow as tf\nfrom tensorflow.keras.optimizers import *\nfrom tensorflow.keras.losses import *\nfrom tensorflow.keras.layers import *\nfrom tensorflow.keras.models import *\nfrom tensorflow.keras.callbacks import *\nfrom tensorflow.keras.preprocessing.image import *\nfrom tensorflow.keras.utils import *\nfrom sklearn.metrics import *\nfrom sklearn.model_selection import *\nimport tensorflow.keras.backend as K\n\nfrom tqdm import tqdm\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom skimage.io import *\n%config Completer.use_jedi = False\nimport time\nfrom sklearn.metrics import confusion_matrix\n\nprint(\"All modules have been imported\")\n","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"info=pd.read_csv(\"../input/prepossessed-arrays-of-binary-data/1000_Binary Dataframe\")\ninfo=info.drop('Unnamed: 0',axis=1)\ninfo.head()","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"info.level.value_counts()","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sns.set_style('darkgrid')\nfig, ax = plt.subplots(figsize=(10,5))\nsns.barplot(x=info.level.unique(),y=info.level.value_counts(),palette='Blues_r',ax=ax)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sizes = info['level'].values\nsns.distplot(sizes, kde=False)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"Binary_90 = np.load('../input/prepossessed-arrays-of-binary-data/1000_Binary_images_data_90.npz')\nX_90=Binary_90['a']\nBinary_128 = np.load('../input/prepossessed-arrays-of-binary-data/1000_Binary_images_data_128.npz')\nX_128=Binary_128['a']\nBinary_264 = np.load('../input/prepossessed-arrays-of-binary-data/1000_Binary_images_data_264.npz')\nX_264=Binary_264['a']\ny=info['level'].values\n\n\nprint(X_90.shape)\nprint(X_128.shape)\nprint(X_264.shape)\nprint(y.shape)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"Shape before reshaping X_90\" +str(X_90.shape))\nX_90=X_90.reshape(1000,90,90,3)\nprint(\"Shape after reshaping X_90\" +str(X_90.shape))\nprint(\"\\n\\n\")\n\nprint(\"Shape before reshaping X_128\" +str(X_128.shape))\nX_128=X_128.reshape(1000,128,128,3)\nprint(\"Shape after reshaping X_128\" +str(X_128.shape))\nprint(\"\\n\\n\")\n\nprint(\"Shape before reshaping X_264\" +str(X_264.shape))\nX_264=X_264.reshape(1000,264,264,3)\nprint(\"Shape after reshaping X_264\" +str(X_264.shape))","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.title(\"90*90*3 Image\")\nplt.imshow(X_90[1])\nplt.show()\n\nplt.title(\"128*128*3 Image\")\nplt.imshow(X_128[1])\nplt.show()\n\nplt.title(\"264*264*3 Image\")\nplt.imshow(X_264[1])\nplt.show()","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X=np.array(X_264)\nY=np.array(y)\n# Y=to_categorical(Y,5)\nx_train, x_test1, y_train, y_test1 = train_test_split(X, Y, test_size=0.4, random_state=42)\nx_val, x_test, y_val, y_test = train_test_split(x_test1, y_test1, test_size=0.5, random_state=42)\nprint(len(x_train),len(x_val),len(x_test))","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"Y1=pd.DataFrame(Y)\nY1.value_counts()","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create the CNN model\nmodel = Sequential([\n    Conv2D(32, (3, 3), activation='relu', input_shape=(264, 264, 3)),\n    MaxPooling2D((2, 2)),\n    Conv2D(64, (3, 3), activation='relu'),\n    MaxPooling2D((2, 2)),\n    Conv2D(64, (3, 3), activation='relu'),\n    Flatten(),\n    Dense(64, activation='relu'),\n    Dense(5, activation='softmax')\n])\n\n# Compile the model\nmodel.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])\n\n# Train the model\nhistory = model.fit(x_train, y_train, epochs=10, batch_size=32, validation_data=(x_val, y_val))\n\n# Evaluate the model on the test set\ntest_loss, test_acc = model.evaluate(x_test, y_test)\nprint('Test accuracy:', test_acc)\n","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.metrics import confusion_matrix\n\n# Get the predicted class labels for the test set\ny_pred = np.argmax(model.predict(x_test), axis=-1)\n\n# Calculate the confusion matrix\ncm = confusion_matrix(y_test, y_pred)\n\n# Print the confusion matrix\nprint(\"Confusion Matrix:\")\nprint(cm)\n","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import seaborn as sns\n\n# Visualize the confusion matrix as a heatmap\nsns.heatmap(cm, annot=True, fmt='d', cmap='Blues', cbar=False)\nplt.xlabel(\"Predicted\")\nplt.ylabel(\"True\")\nplt.show()\n","metadata":{},"execution_count":null,"outputs":[]}]}