{"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":3362,"databundleVersionId":31148,"sourceType":"competition"}],"dockerImageVersionId":30746,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Import lib","metadata":{}},{"cell_type":"code","source":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport seaborn as sns\nimport os\nimport random\nimport zipfile\nimport cv2\n\nfrom tensorflow.keras.utils import to_categorical\nfrom keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-08-08T22:41:17.159840Z","iopub.execute_input":"2024-08-08T22:41:17.161155Z","iopub.status.idle":"2024-08-08T22:41:17.167927Z","shell.execute_reply.started":"2024-08-08T22:41:17.161108Z","shell.execute_reply":"2024-08-08T22:41:17.166775Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))","metadata":{"execution":{"iopub.status.busy":"2024-08-08T22:41:17.173197Z","iopub.execute_input":"2024-08-08T22:41:17.174095Z","iopub.status.idle":"2024-08-08T22:41:17.183856Z","shell.execute_reply.started":"2024-08-08T22:41:17.174059Z","shell.execute_reply":"2024-08-08T22:41:17.182462Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Unzip file","metadata":{}},{"cell_type":"code","source":"zip_files = ['train', 'test1']\nfor zip_file in zip_files:\n    with zipfile.ZipFile(\"/kaggle/input/dogs-vs-cats/{}.zip\".format(zip_file),'r') as z:\n        z.extractall(\".\")\n        print(\"{} unzipped\".format(zip_file))","metadata":{"execution":{"iopub.status.busy":"2024-08-08T22:41:17.188831Z","iopub.execute_input":"2024-08-08T22:41:17.189196Z","iopub.status.idle":"2024-08-08T22:41:29.005647Z","shell.execute_reply.started":"2024-08-08T22:41:17.189169Z","shell.execute_reply":"2024-08-08T22:41:29.004567Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Load Data","metadata":{}},{"cell_type":"code","source":"train_path = \"./train\"\ntest_path = \"./test1\"\nfile_names = os.listdir(train_path)\nfile_names_test = os.listdir(test_path)\nprint (\"There are {} number of image in directory \".format(len(file_names)))","metadata":{"execution":{"iopub.status.busy":"2024-08-08T22:41:29.007622Z","iopub.execute_input":"2024-08-08T22:41:29.007966Z","iopub.status.idle":"2024-08-08T22:41:29.033732Z","shell.execute_reply.started":"2024-08-08T22:41:29.007937Z","shell.execute_reply":"2024-08-08T22:41:29.032298Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def to_dataframe(file_names):\n    files, labels = list(), list()\n    for file_name in file_names:\n        files.append(file_name)\n        labels.append(file_name[:3])\n    df = pd.DataFrame({'file_name':files, 'label':labels})\n    return df\ndf = to_dataframe(file_names)\n        ","metadata":{"execution":{"iopub.status.busy":"2024-08-08T22:41:29.035048Z","iopub.execute_input":"2024-08-08T22:41:29.035382Z","iopub.status.idle":"2024-08-08T22:41:29.052318Z","shell.execute_reply.started":"2024-08-08T22:41:29.035355Z","shell.execute_reply":"2024-08-08T22:41:29.051209Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.head()","metadata":{"execution":{"iopub.status.busy":"2024-08-08T22:41:29.055420Z","iopub.execute_input":"2024-08-08T22:41:29.055952Z","iopub.status.idle":"2024-08-08T22:41:29.075819Z","shell.execute_reply.started":"2024-08-08T22:41:29.055908Z","shell.execute_reply":"2024-08-08T22:41:29.074168Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Data Processing","metadata":{}},{"cell_type":"code","source":"# Label disibution\nprint(\"Dataset label distribution :\\n\", df['label'].value_counts())","metadata":{"execution":{"iopub.status.busy":"2024-08-08T22:41:29.077643Z","iopub.execute_input":"2024-08-08T22:41:29.078109Z","iopub.status.idle":"2024-08-08T22:41:29.090031Z","shell.execute_reply.started":"2024-08-08T22:41:29.078059Z","shell.execute_reply":"2024-08-08T22:41:29.088685Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.figure(figsize = (7,7))\nsns.countplot(x = df['label'], palette='viridis')\nplt.title(\"Label Distribution\")\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-08-08T22:41:29.091502Z","iopub.execute_input":"2024-08-08T22:41:29.091890Z","iopub.status.idle":"2024-08-08T22:41:29.330444Z","shell.execute_reply.started":"2024-08-08T22:41:29.091860Z","shell.execute_reply":"2024-08-08T22:41:29.329119Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cat = [file for file in file_names if file[:3] == 'cat']\ndog = [file for file in file_names if file[:3] == 'dog']\n#Tên ảnh","metadata":{"execution":{"iopub.status.busy":"2024-08-08T22:41:29.331961Z","iopub.execute_input":"2024-08-08T22:41:29.332414Z","iopub.status.idle":"2024-08-08T22:41:29.348825Z","shell.execute_reply.started":"2024-08-08T22:41:29.332374Z","shell.execute_reply":"2024-08-08T22:41:29.347577Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Chọn ngẫu nhiên 4 ảnh từ danh sách cat\nrandom_cats = random.sample(cat, 4)\n\n# Hiển thị các ảnh mèo ngẫu nhiên\nfig, axes = plt.subplots(1, 4, figsize=(15, 5))\nfor i, img_name in enumerate(random_cats):\n    img = mpimg.imread(os.path.join(train_path, img_name))\n    axes[i].imshow(img)\n    axes[i].axis('off')\n\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-08-08T22:41:29.350527Z","iopub.execute_input":"2024-08-08T22:41:29.350985Z","iopub.status.idle":"2024-08-08T22:41:29.761801Z","shell.execute_reply.started":"2024-08-08T22:41:29.350945Z","shell.execute_reply":"2024-08-08T22:41:29.760538Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Chọn ngẫu nhiên 4 ảnh từ danh sách dogs\nrandom_dogs = random.sample(dog, 4)\n\n# Hiển thị các ảnh chó ngẫu nhiên\nfig, axes = plt.subplots(1, 4, figsize=(15, 5))\nfor i, img_name in enumerate(random_dogs):\n    img = mpimg.imread(os.path.join(train_path, img_name))\n    axes[i].imshow(img)\n    axes[i].axis('off')\n\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-08-08T22:41:29.763608Z","iopub.execute_input":"2024-08-08T22:41:29.764033Z","iopub.status.idle":"2024-08-08T22:41:30.239783Z","shell.execute_reply.started":"2024-08-08T22:41:29.763999Z","shell.execute_reply":"2024-08-08T22:41:30.238489Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Nhận xét các file ảnh k cùng kích thước --> cần resize lại ảnh","metadata":{}},{"cell_type":"markdown","source":"# Split Train, Val","metadata":{}},{"cell_type":"code","source":"random.shuffle(file_names)","metadata":{"execution":{"iopub.status.busy":"2024-08-08T22:41:30.244191Z","iopub.execute_input":"2024-08-08T22:41:30.245046Z","iopub.status.idle":"2024-08-08T22:41:30.271962Z","shell.execute_reply.started":"2024-08-08T22:41:30.245004Z","shell.execute_reply":"2024-08-08T22:41:30.270827Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_size = 0.8\ntotal_files = len(file_names)\nnum_train = int(total_files*train_size)","metadata":{"execution":{"iopub.status.busy":"2024-08-08T22:41:30.273894Z","iopub.execute_input":"2024-08-08T22:41:30.274262Z","iopub.status.idle":"2024-08-08T22:41:30.283570Z","shell.execute_reply.started":"2024-08-08T22:41:30.274232Z","shell.execute_reply":"2024-08-08T22:41:30.282288Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_dir = './train/'\ntest_dir  = './test1/'","metadata":{"execution":{"iopub.status.busy":"2024-08-08T22:41:30.284958Z","iopub.execute_input":"2024-08-08T22:41:30.285347Z","iopub.status.idle":"2024-08-08T22:41:30.295315Z","shell.execute_reply.started":"2024-08-08T22:41:30.285308Z","shell.execute_reply":"2024-08-08T22:41:30.294069Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_images =[train_dir +i for i in file_names[:num_train]]\nval_images = [train_dir +i for i in file_names[num_train:]]\ntest_images = [test_dir +i for i in file_names_test]","metadata":{"execution":{"iopub.status.busy":"2024-08-08T22:41:30.296669Z","iopub.execute_input":"2024-08-08T22:41:30.297025Z","iopub.status.idle":"2024-08-08T22:41:30.315963Z","shell.execute_reply.started":"2024-08-08T22:41:30.296989Z","shell.execute_reply":"2024-08-08T22:41:30.314755Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Resize image","metadata":{}},{"cell_type":"code","source":"ROWS = 64\nCOLS = 64\nCHANNELS = 3","metadata":{"execution":{"iopub.status.busy":"2024-08-08T22:41:30.317416Z","iopub.execute_input":"2024-08-08T22:41:30.317756Z","iopub.status.idle":"2024-08-08T22:41:30.328066Z","shell.execute_reply.started":"2024-08-08T22:41:30.317714Z","shell.execute_reply":"2024-08-08T22:41:30.326714Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def read_image(file_path):\n    img = cv2.imread(file_path, cv2.IMREAD_COLOR)\n    if img is None:\n        raise FileNotFoundError(f\"Cannot open or read the image file: {file_path}\")\n    return cv2.resize(img, (COLS, ROWS), interpolation=cv2.INTER_CUBIC)\n\ndef prep_data(images):\n    m = len(images)\n    X = np.ndarray((m, ROWS, COLS, CHANNELS), dtype=np.uint8)\n    y = np.zeros((m, 1))\n    print(\"X.shape is {}\".format(X.shape))\n\n    for i, image_file in enumerate(images):\n        image = read_image(image_file)\n        X[i, :] = np.squeeze(image.reshape((ROWS, COLS, CHANNELS)))\n        \n        if 'dog' in image_file.lower():\n            y[i, 0] = 1\n        elif 'cat' in image_file.lower():\n            y[i, 0] = 0\n        else:  # for test data\n            y[i, 0] = image_file.split('/')[-1].split('.')[0]\n\n        if i % 5000 == 0:\n            print(\"Proceed {} of {}\".format(i, m))\n\n    return X, y\n","metadata":{"execution":{"iopub.status.busy":"2024-08-08T22:41:30.329636Z","iopub.execute_input":"2024-08-08T22:41:30.330083Z","iopub.status.idle":"2024-08-08T22:41:30.342784Z","shell.execute_reply.started":"2024-08-08T22:41:30.330042Z","shell.execute_reply":"2024-08-08T22:41:30.341514Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_train, y_train = prep_data(train_images)\n","metadata":{"execution":{"iopub.status.busy":"2024-08-08T22:41:30.344374Z","iopub.execute_input":"2024-08-08T22:41:30.344855Z","iopub.status.idle":"2024-08-08T22:41:57.076263Z","shell.execute_reply.started":"2024-08-08T22:41:30.344813Z","shell.execute_reply":"2024-08-08T22:41:57.075294Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_test, y_test =prep_data(test_images)","metadata":{"execution":{"iopub.status.busy":"2024-08-08T22:41:57.077595Z","iopub.execute_input":"2024-08-08T22:41:57.078024Z","iopub.status.idle":"2024-08-08T22:42:13.716251Z","shell.execute_reply.started":"2024-08-08T22:41:57.077988Z","shell.execute_reply":"2024-08-08T22:42:13.715040Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_val, y_val = prep_data(val_images)\n","metadata":{"execution":{"iopub.status.busy":"2024-08-08T22:42:13.717651Z","iopub.execute_input":"2024-08-08T22:42:13.718080Z","iopub.status.idle":"2024-08-08T22:42:20.313602Z","shell.execute_reply.started":"2024-08-08T22:42:13.718044Z","shell.execute_reply":"2024-08-08T22:42:20.312381Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_train_one_hot = to_categorical(y_train)\ny_val_one_hot = to_categorical(y_val)\n","metadata":{"execution":{"iopub.status.busy":"2024-08-08T22:42:20.315073Z","iopub.execute_input":"2024-08-08T22:42:20.315524Z","iopub.status.idle":"2024-08-08T22:42:20.322698Z","shell.execute_reply.started":"2024-08-08T22:42:20.315485Z","shell.execute_reply":"2024-08-08T22:42:20.321546Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"num_classes = y_train_one_hot.shape[1]","metadata":{"execution":{"iopub.status.busy":"2024-08-08T22:42:20.324043Z","iopub.execute_input":"2024-08-08T22:42:20.324486Z","iopub.status.idle":"2024-08-08T22:42:20.332092Z","shell.execute_reply.started":"2024-08-08T22:42:20.324454Z","shell.execute_reply":"2024-08-08T22:42:20.330948Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Chuan hoa du lieu\nX_train_norm = X_train / 255\nX_val_norm = X_val / 255\n","metadata":{"execution":{"iopub.status.busy":"2024-08-08T22:42:20.333613Z","iopub.execute_input":"2024-08-08T22:42:20.334062Z","iopub.status.idle":"2024-08-08T22:42:21.420819Z","shell.execute_reply.started":"2024-08-08T22:42:20.334022Z","shell.execute_reply":"2024-08-08T22:42:21.419630Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Build Network","metadata":{}},{"cell_type":"code","source":"model = Sequential()\n\nmodel.add(Conv2D(32, (3,3), input_shape=(ROWS, COLS, CHANNELS), activation='relu'))\nmodel.add(MaxPooling2D(pool_size = (2,2)))\n\nmodel.add(Conv2D(64, (3,3), activation='relu'))\nmodel.add(MaxPooling2D(pool_size = (2,2)))\nmodel.add(Dropout(0.4))\n\nmodel.add(Conv2D(128, (3,3), activation='relu'))\nmodel.add(MaxPooling2D(pool_size = (2,2)))\nmodel.add(Dropout(0.4))\n\nmodel.add(Conv2D(256, (3,3), activation='relu'))\nmodel.add(MaxPooling2D(pool_size = (2,2)))\nmodel.add(Dropout(0.4))\n\nmodel.add(Conv2D(512, (1,1), activation='relu'))\n#model.add(MaxPooling2D(pool_size = (2,2)))\n\nmodel.add(Flatten())\nmodel.add(Dropout(0.4))\n\nmodel.add(Dense(units=120, activation='relu'))\nmodel.add(Dense(units=2, activation='sigmoid'))\n\nmodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2024-08-08T22:42:21.422064Z","iopub.execute_input":"2024-08-08T22:42:21.422394Z","iopub.status.idle":"2024-08-08T22:42:21.656493Z","shell.execute_reply.started":"2024-08-08T22:42:21.422365Z","shell.execute_reply":"2024-08-08T22:42:21.655224Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.fit(X_train_norm, y_train_one_hot, validation_data=(X_val_norm, y_val_one_hot), epochs=50, batch_size = 64)\n","metadata":{"execution":{"iopub.status.busy":"2024-08-08T22:42:21.657706Z","iopub.execute_input":"2024-08-08T22:42:21.658048Z","iopub.status.idle":"2024-08-08T23:46:07.823253Z","shell.execute_reply.started":"2024-08-08T22:42:21.658020Z","shell.execute_reply":"2024-08-08T23:46:07.821948Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n# Dự đoán xác suất\nimage = X_test[20]\npredictions = model.predict(image.reshape(1, 64, 64, 3))\n\n# Chuyển đổi xác suất thành lớp\npredicted_class = np.argmax(predictions, axis=1)\n\n# Hiển thị hình ảnh và dự đoán\nplt.figure(figsize=(4, 2))\nplt.imshow(image)\nplt.title(f\"Predicted class: {predicted_class[0]}\")\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2024-08-09T00:08:32.677769Z","iopub.execute_input":"2024-08-09T00:08:32.678854Z","iopub.status.idle":"2024-08-09T00:08:32.972135Z","shell.execute_reply.started":"2024-08-09T00:08:32.678814Z","shell.execute_reply":"2024-08-09T00:08:32.970998Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}