{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":77476,"databundleVersionId":8462666,"sourceType":"competition"}],"dockerImageVersionId":30698,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"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)\nimport seaborn as sns\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\n%matplotlib inline\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\n\ntrain_filepath = '/kaggle/input/2024-smarcle-ks-3-fashion-mnist2/train.csv'\ntrain_df = pd.read_csv(train_filepath)\n\ntest_filepath = '/kaggle/input/2024-smarcle-ks-3-fashion-mnist2/test.csv'\ntest_df = pd.read_csv(test_filepath)\n\nprint(train_df)","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-05-16T02:36:57.641031Z","iopub.execute_input":"2024-05-16T02:36:57.641433Z","iopub.status.idle":"2024-05-16T02:37:06.551249Z","shell.execute_reply.started":"2024-05-16T02:36:57.641402Z","shell.execute_reply":"2024-05-16T02:37:06.549895Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Separate features and labels in the training data\nX_train = train_df.drop(columns=['label']).values\ny_train = train_df['label'].values\n\n# Extract features from the test data\nX_test = test_df.values\n\n# Normalize the pixel values (0-255) to the range [0, 1]\nX_train = X_train / 255.0\nX_test = X_test / 255.0\n\n# Reshape the data to fit the model's input requirements\nX_train = X_train.reshape(-1, 28, 28, 1)\nX_test = X_test.reshape(-1, 28, 28, 1)\n\n# Convert labels to one-hot encoding\nfrom tensorflow.keras.utils import to_categorical\ny_train = to_categorical(y_train, num_classes=10)","metadata":{"execution":{"iopub.status.busy":"2024-05-16T02:38:36.705075Z","iopub.execute_input":"2024-05-16T02:38:36.705770Z","iopub.status.idle":"2024-05-16T02:38:37.007661Z","shell.execute_reply.started":"2024-05-16T02:38:36.705730Z","shell.execute_reply":"2024-05-16T02:38:37.006210Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Step 2: Build the Model\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout\n\nmodel = Sequential([\n    Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),\n    MaxPooling2D((2, 2)),\n    Conv2D(64, (3, 3), activation='relu'),\n    MaxPooling2D((2, 2)),\n    Conv2D(128, (3, 3), activation='relu'),\n    Flatten(),\n    Dense(128, activation='relu'),\n    Dropout(0.5),\n    Dense(10, activation='softmax')\n])","metadata":{"execution":{"iopub.status.busy":"2024-05-16T02:38:47.003545Z","iopub.execute_input":"2024-05-16T02:38:47.004000Z","iopub.status.idle":"2024-05-16T02:38:47.074340Z","shell.execute_reply.started":"2024-05-16T02:38:47.003967Z","shell.execute_reply":"2024-05-16T02:38:47.073184Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Compile the model\nmodel.compile(optimizer='adam',\n              loss='categorical_crossentropy',\n              metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2024-05-16T02:38:55.181901Z","iopub.execute_input":"2024-05-16T02:38:55.182278Z","iopub.status.idle":"2024-05-16T02:38:55.201113Z","shell.execute_reply.started":"2024-05-16T02:38:55.182250Z","shell.execute_reply":"2024-05-16T02:38:55.199875Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Step 3: Train the Model\nhistory = model.fit(X_train, y_train, epochs=10, batch_size=64, validation_split=0.1)","metadata":{"execution":{"iopub.status.busy":"2024-05-16T02:39:03.575225Z","iopub.execute_input":"2024-05-16T02:39:03.576960Z","iopub.status.idle":"2024-05-16T02:44:34.709448Z","shell.execute_reply.started":"2024-05-16T02:39:03.576912Z","shell.execute_reply":"2024-05-16T02:44:34.708240Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"predictions = model.predict(X_test)\npred_labels = np.argmax(predictions, axis=1)\n\nimage_ids = np.arange(1, len(pred_labels) + 1)\nsubmission_df = pd.DataFrame({'ImageId': image_ids, 'label': pred_labels})\n\n# Save the submission DataFrame to a CSV file\nsubmission_df.to_csv(\"/kaggle/working/submission_cnn.csv\", index=False)","metadata":{"execution":{"iopub.status.busy":"2024-05-16T02:48:52.629561Z","iopub.execute_input":"2024-05-16T02:48:52.630506Z","iopub.status.idle":"2024-05-16T02:48:55.206341Z","shell.execute_reply.started":"2024-05-16T02:48:52.630467Z","shell.execute_reply":"2024-05-16T02:48:55.205160Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Step 5: Save the Model\nmodel.save('/kaggle/working/fashion_mnist_model.h5')","metadata":{"execution":{"iopub.status.busy":"2024-05-16T02:48:41.715714Z","iopub.execute_input":"2024-05-16T02:48:41.716140Z","iopub.status.idle":"2024-05-16T02:48:41.756866Z","shell.execute_reply.started":"2024-05-16T02:48:41.716108Z","shell.execute_reply":"2024-05-16T02:48:41.755584Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Step 6: Visualize Training History\n# Plot training & validation accuracy values\nplt.figure(figsize=(12, 4))\nplt.subplot(1, 2, 1)\nplt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])\nplt.title('Model accuracy')\nplt.ylabel('Accuracy')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Validation'], loc='upper left')\n\n# Plot training & validation loss values\nplt.subplot(1, 2, 2)\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('Model loss')\nplt.ylabel('Loss')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Validation'], loc='upper left')\n\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-05-16T02:44:54.448187Z","iopub.execute_input":"2024-05-16T02:44:54.448639Z","iopub.status.idle":"2024-05-16T02:44:55.002064Z","shell.execute_reply.started":"2024-05-16T02:44:54.448588Z","shell.execute_reply":"2024-05-16T02:44:55.000837Z"},"trusted":true},"execution_count":null,"outputs":[]}]}