{"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":"gpu","dataSources":[{"sourceId":3362,"databundleVersionId":31148,"sourceType":"competition"}],"dockerImageVersionId":30747,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"<h3 style=\"text-align: center;\">IMPORT LIBRARIES</h3>","metadata":{}},{"cell_type":"code","source":"%%time\n\nimport numpy as np\nimport pandas as pd\nimport os\nimport zipfile\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n        \nimport torch\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nprint('-'*100)\nprint('Using device:', device)\n\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D\nfrom tensorflow.keras.layers import Activation, Dropout, Flatten, Dense\nfrom tensorflow.keras import backend as K\nimport cv2\n\nimport matplotlib.pyplot as pltt\n%matplotlib inline\n\nfrom tqdm import tqdm\nfrom random import shuffle\n\ntf.__version__\n        ","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-07-27T12:59:35.337248Z","iopub.execute_input":"2024-07-27T12:59:35.338095Z","iopub.status.idle":"2024-07-27T12:59:35.353783Z","shell.execute_reply.started":"2024-07-27T12:59:35.338064Z","shell.execute_reply":"2024-07-27T12:59:35.352857Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<h3 style=\"text-align: center;\">Extract Zip File</h3>","metadata":{}},{"cell_type":"markdown","source":"* **test1.zip**\n* **train.zip**","metadata":{}},{"cell_type":"code","source":"%%time\n\n# กำหนดเส้นทางไปยังไฟล์ ZIP ที่คุณต้องการเปิด\nzip_test_path = '/kaggle/input/dogs-vs-cats/test1.zip'\nzip_train_path = '/kaggle/input/dogs-vs-cats/train.zip'\n\n# สร้างตัวจัดการไฟล์ ZIP\nwith zipfile.ZipFile(zip_test_path, 'r') as zip_ref:\n    # แสดงรายชื่อไฟล์ใน ZIP\n    #zip_ref.printdir()\n    \n    # แยกไฟล์ทั้งหมดไปยังไดเรกทอรีที่กำหนด\n    extract_path = '/kaggle/working/'\n    zip_ref.extractall(extract_path)\n    \nwith zipfile.ZipFile(zip_train_path, 'r') as zip_ref:\n    # แสดงรายชื่อไฟล์ใน ZIP\n    #zip_ref.printdir()\n    \n    # แยกไฟล์ทั้งหมดไปยังไดเรกทอรีที่กำหนด\n    extract_path = '/kaggle/working/'\n    zip_ref.extractall(extract_path)","metadata":{"execution":{"iopub.status.busy":"2024-07-27T12:59:37.377029Z","iopub.execute_input":"2024-07-27T12:59:37.377398Z","iopub.status.idle":"2024-07-27T12:59:48.247857Z","shell.execute_reply.started":"2024-07-27T12:59:37.377367Z","shell.execute_reply":"2024-07-27T12:59:48.246974Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\n\nTRAIN_DIR = '/kaggle/working/train'\nTEST_DIR = '/kaggle/working/test1'\nIMG_SIZE = 128\n","metadata":{"execution":{"iopub.status.busy":"2024-07-27T12:59:54.854076Z","iopub.execute_input":"2024-07-27T12:59:54.854428Z","iopub.status.idle":"2024-07-27T12:59:54.859727Z","shell.execute_reply.started":"2024-07-27T12:59:54.854399Z","shell.execute_reply":"2024-07-27T12:59:54.858762Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\n\ndef create_label(image_name):\n    word_label = image_name.split('.')[-3]\n    if word_label == 'cat':\n        return np.array([1,0])\n    elif word_label == 'dog':\n        return np.array([0,1])\n\ndef create_train_data():\n    training_data = []\n    for img in tqdm(os.listdir(TRAIN_DIR)):\n        path = os.path.join(TRAIN_DIR, img)\n        img_data = cv2.imread(path)\n        img_data = cv2.resize(img_data, (IMG_SIZE, IMG_SIZE))\n        training_data.append([np.array(img_data), create_label(img)])\n    shuffle(training_data)\n    return training_data","metadata":{"execution":{"iopub.status.busy":"2024-07-27T12:59:56.312382Z","iopub.execute_input":"2024-07-27T12:59:56.312724Z","iopub.status.idle":"2024-07-27T12:59:56.320397Z","shell.execute_reply.started":"2024-07-27T12:59:56.312697Z","shell.execute_reply":"2024-07-27T12:59:56.319448Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\n\ntrain_data = create_train_data()","metadata":{"execution":{"iopub.status.busy":"2024-07-27T12:59:57.682496Z","iopub.execute_input":"2024-07-27T12:59:57.683427Z","iopub.status.idle":"2024-07-27T13:00:20.435101Z","shell.execute_reply.started":"2024-07-27T12:59:57.683385Z","shell.execute_reply":"2024-07-27T13:00:20.434202Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train = train_data[0:-15000] #ตัวที่ 0 ถึง 500 ตัวสุดท้าย\ntest = train_data[-500:] #500 ตัวสุดท้าย\n\nX_train = np.array([i[0] for i in train]).reshape(-1, IMG_SIZE, IMG_SIZE, 3)/255\ny_train = np.array([i[1] for i in train])\nX_test = np.array([i[0] for i in test]).reshape(-1, IMG_SIZE, IMG_SIZE, 3)/255\ny_test = np.array([i[1] for i in test])","metadata":{"execution":{"iopub.status.busy":"2024-07-27T13:00:20.436624Z","iopub.execute_input":"2024-07-27T13:00:20.436925Z","iopub.status.idle":"2024-07-27T13:00:21.865784Z","shell.execute_reply.started":"2024-07-27T13:00:20.436900Z","shell.execute_reply":"2024-07-27T13:00:21.865038Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"base_model = tf.keras.applications.MobileNetV2(input_shape=(128, 128, 3), include_top=False, weights='imagenet')\nbase_model.summary()\nbase_model.trainable = False","metadata":{"execution":{"iopub.status.busy":"2024-07-27T13:00:21.866825Z","iopub.execute_input":"2024-07-27T13:00:21.867088Z","iopub.status.idle":"2024-07-27T13:00:23.977842Z","shell.execute_reply.started":"2024-07-27T13:00:21.867066Z","shell.execute_reply":"2024-07-27T13:00:23.976949Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<h3 style=\"text-align: center;\">Add Custom Head</h3>","metadata":{}},{"cell_type":"code","source":"average_pooling_layer = tf.keras.layers.GlobalAveragePooling2D()(base_model.output)\nprediction_layer = tf.keras.layers.Dense(units=2, activation='sigmoid')(average_pooling_layer)","metadata":{"execution":{"iopub.status.busy":"2024-07-27T13:00:23.980358Z","iopub.execute_input":"2024-07-27T13:00:23.980988Z","iopub.status.idle":"2024-07-27T13:00:23.997836Z","shell.execute_reply.started":"2024-07-27T13:00:23.980960Z","shell.execute_reply":"2024-07-27T13:00:23.996955Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = tf.keras.models.Model(inputs=base_model.input, outputs=prediction_layer)\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2024-07-27T13:00:23.998957Z","iopub.execute_input":"2024-07-27T13:00:23.999295Z","iopub.status.idle":"2024-07-27T13:00:24.210457Z","shell.execute_reply.started":"2024-07-27T13:00:23.999262Z","shell.execute_reply":"2024-07-27T13:00:24.209485Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<h3 style=\"text-align: center;\">Train Model</h3>","metadata":{}},{"cell_type":"code","source":"%%time\n\nmodel.compile(optimizer=tf.keras.optimizers.RMSprop(learning_rate=0.0001), loss='binary_crossentropy', metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2024-07-27T13:00:24.211507Z","iopub.execute_input":"2024-07-27T13:00:24.211768Z","iopub.status.idle":"2024-07-27T13:00:24.228725Z","shell.execute_reply.started":"2024-07-27T13:00:24.211745Z","shell.execute_reply":"2024-07-27T13:00:24.227593Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\n\nhistory = model.fit(X_train, y_train, batch_size=32, epochs=25, validation_data=(X_test, y_test))","metadata":{"execution":{"iopub.status.busy":"2024-07-27T13:00:24.229814Z","iopub.execute_input":"2024-07-27T13:00:24.230093Z","iopub.status.idle":"2024-07-27T13:02:18.020036Z","shell.execute_reply.started":"2024-07-27T13:00:24.230070Z","shell.execute_reply":"2024-07-27T13:02:18.019057Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\n\nimport matplotlib.pyplot as plt\nplt.figure(figsize=(10,4))\nplt.subplot(121),\nplt.title('model accuracy');plt.ylabel('accuracy');plt.xlabel('epoch')\nplt.legend(['train', 'validation'], loc='upper left')\nplt.plot(history.history['accuracy']);plt.plot(history.history['val_accuracy'])\n\nplt.subplot(122)\nplt.title('model loss')\nplt.ylabel('loss')\nplt.xlabel('epoch')\nplt.legend(['train', 'validation'], loc='upper left')\nplt.plot(history.history['loss']);plt.plot(history.history['val_loss'])","metadata":{"execution":{"iopub.status.busy":"2024-07-27T13:02:18.021219Z","iopub.execute_input":"2024-07-27T13:02:18.021519Z","iopub.status.idle":"2024-07-27T13:02:18.514123Z","shell.execute_reply.started":"2024-07-27T13:02:18.021493Z","shell.execute_reply":"2024-07-27T13:02:18.513146Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<h3 style=\"text-align: center;\">Prediction</h3>","metadata":{}},{"cell_type":"code","source":"%%time\n\nimport numpy as np\nfrom PIL import Image\nimport cv2\n\nwidth, height = 128, 128\n\ndef imageToArray(imageName):\n  # Load the image and resize it to the desired dimensions\n  image_path = f'/kaggle/working/test1/{imageName}.jpg'\n  image = Image.open(image_path)\n  image = image.resize((width, height))\n\n  # Convert the image to a NumPy array and normalize the pixel values (if necessary)\n  image_array = np.asarray(image)\n  image_array = image_array / 255.0  # Normalize the pixel values between 0 and 1\n\n  # Reshape the image array to match the input shape of your model\n  image_array = image_array.reshape(1, width, height, 3)  # Assumes the input shape is (width, height, 3)\n\n  return image_array\n\nlabel = ['Cat','Dog']\nIMAGES_TO_TEST = ['1','2','3', '4', '5', '6', '7', '8', '9', '10']\n\nfor image in IMAGES_TO_TEST:\n  imageName = image\n  image_array = imageToArray(imageName)\n  preds = model.predict(image_array)\n  preds = label[np.argmax(preds)] \n  actual_single = imageName\n  print(f'file name: {actual_single}.jpg')\n  print(f'predict: {preds}')\n  image_path = f'/kaggle/working/test1/{imageName}.jpg'\n  img = cv2.imread(image_path)\n  img = cv2.resize(img, (width, height))\n  plt.imshow(img)\n  plt.show()\n  print('-'*100)","metadata":{"execution":{"iopub.status.busy":"2024-07-27T13:05:31.483320Z","iopub.execute_input":"2024-07-27T13:05:31.484011Z","iopub.status.idle":"2024-07-27T13:05:35.266533Z","shell.execute_reply.started":"2024-07-27T13:05:31.483978Z","shell.execute_reply":"2024-07-27T13:05:35.265645Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"'''%%time\n\n# กำหนด path ไปยัง directory ที่เก็บรูปภาพ\nimg_dir = '/kaggle/working/test1/'\n\n# สร้าง lists เก็บชื่อไฟล์และ labels\nfile_names = []\nlabels = []\n\n# วนลูปอ่านไฟล์จาก directory\nfor file_name in os.listdir(img_dir):\n    if file_name.endswith('.jpg'):\n        file_names.append(file_name)\n        if file_name.startswith('cat'):\n            labels.append(0)\n        elif file_name.startswith('dog'):\n            labels.append(1)\n\n# สร้าง DataFrame จาก lists\ntrain = pd.DataFrame({\n    'file_name': file_names,\n    'label': labels\n})\n\n# แสดง DataFrame\nprint(train)\ntrain.to_csv('/kaggle/working/Submission.csv')'''","metadata":{},"execution_count":null,"outputs":[]}]}