{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":4829,"databundleVersionId":44847,"sourceType":"competition"}],"dockerImageVersionId":30580,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Yelp Restaurant Photo Classification\nautomatically tags restaurants with multiple labels using a dataset of user-submitted photos","metadata":{}},{"cell_type":"markdown","source":"Yelp Restaurant Photo Classification : มีเป้าหมายในการระบุลักษณะของรูปภาพในร้านอาหารต่างๆ ซึ่ง .............................................................","metadata":{}},{"cell_type":"markdown","source":"มีลักษณะ 9 อย่าง ดังนี้\n\n1.good_for_lunch\n2.good_for_dinner\n3.takes_reservations\n4.outdoor_seating\n5.restaurant_is_expensive\n6.has_alcohol\n7.has_table_service\n8.ambience_is_classy\n9.good_for_kids","metadata":{}},{"cell_type":"markdown","source":"## Library Imports","metadata":{}},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.metrics import accuracy_score, classification_report\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.multiclass import OneVsRestClassifier\nfrom sklearn.svm import SVC\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.preprocessing import MultiLabelBinarizer\nfrom sklearn.decomposition import PCA\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.metrics import accuracy_score, classification_report\nfrom sklearn.model_selection import cross_val_predict\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn import metrics\nfrom skimage import io\nimport os\nfrom tqdm import tqdm\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.linear_model import LogisticRegression\nfrom PIL import Image\nimport os\nimport random\nimport IPython.display as display_module\nfrom collections import Counter","metadata":{"execution":{"iopub.status.busy":"2023-11-27T17:18:38.202402Z","iopub.execute_input":"2023-11-27T17:18:38.202795Z","iopub.status.idle":"2023-11-27T17:18:39.360538Z","shell.execute_reply.started":"2023-11-27T17:18:38.202764Z","shell.execute_reply":"2023-11-27T17:18:39.359737Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%bash\n# tar -xzf /kaggle/input/yelp-restaurant-photo-classification/sample_submission.csv.tgz\n# tar -xzf /kaggle/input/yelp-restaurant-photo-classification/test_photo_to_biz.csv.tgz\n# tar -xzf /kaggle/input/yelp-restaurant-photo-classification/test_photos.tgz\ntar -xzf /kaggle/input/yelp-restaurant-photo-classification/train.csv.tgz\ntar -xzf /kaggle/input/yelp-restaurant-photo-classification/train_photo_to_biz_ids.csv.tgz\ntar -xzf /kaggle/input/yelp-restaurant-photo-classification/train_photos.tgz","metadata":{"execution":{"iopub.status.busy":"2023-11-27T17:18:40.789451Z","iopub.execute_input":"2023-11-27T17:18:40.790110Z","iopub.status.idle":"2023-11-27T17:20:51.438493Z","shell.execute_reply.started":"2023-11-27T17:18:40.790079Z","shell.execute_reply":"2023-11-27T17:20:51.437658Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport pandas as pd\n\n# Load the training data\ntrain_data = pd.read_csv('train.csv')\ntrain_photo_to_biz_ids = pd.read_csv('train_photo_to_biz_ids.csv')\n# test_photo_to_biz = pd.read_csv('test_photo_to_biz.csv')\n# sample_sub = pd.read_csv('sample_submission.csv')\n\n# Display basic information about the training data\nprint(train_data.info())\nprint(train_data.head())","metadata":{"execution":{"iopub.status.busy":"2023-11-27T17:30:27.225766Z","iopub.execute_input":"2023-11-27T17:30:27.226161Z","iopub.status.idle":"2023-11-27T17:30:27.323382Z","shell.execute_reply.started":"2023-11-27T17:30:27.226129Z","shell.execute_reply":"2023-11-27T17:30:27.322463Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Dataframe","metadata":{}},{"cell_type":"code","source":"# Load training data that maps photos to business ID\ndisplay_module.display(train_photo_to_biz_ids.head())\nprint('Shape of train_photo_to_id:', train_photo_to_biz_ids.shape)\nprint('Number of images in training set:', train_photo_to_biz_ids.shape[0])","metadata":{"execution":{"iopub.status.busy":"2023-11-27T17:30:32.995098Z","iopub.execute_input":"2023-11-27T17:30:32.996066Z","iopub.status.idle":"2023-11-27T17:30:33.005258Z","shell.execute_reply.started":"2023-11-27T17:30:32.996034Z","shell.execute_reply":"2023-11-27T17:30:33.004267Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Load training data that maps business ID to labels\ndisplay_module.display(train_data.head())\n# print('Shape of train data:', train_data.shape)\n# print('Number of unique businesses:', train_data.shape[0])\n","metadata":{"execution":{"iopub.status.busy":"2023-11-27T17:30:38.976463Z","iopub.execute_input":"2023-11-27T17:30:38.977288Z","iopub.status.idle":"2023-11-27T17:30:38.985706Z","shell.execute_reply.started":"2023-11-27T17:30:38.977257Z","shell.execute_reply":"2023-11-27T17:30:38.984697Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Missing Values","metadata":{}},{"cell_type":"code","source":"# Business id to labels dataframe\nprint('Total number of missing labels:', train_data['labels'].isnull().sum())\ndisplay_module.display(train_data[train_data['labels'].isnull()])","metadata":{"execution":{"iopub.status.busy":"2023-11-27T17:30:41.677767Z","iopub.execute_input":"2023-11-27T17:30:41.678657Z","iopub.status.idle":"2023-11-27T17:30:41.689573Z","shell.execute_reply.started":"2023-11-27T17:30:41.678620Z","shell.execute_reply":"2023-11-27T17:30:41.688737Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Merg Dataframe","metadata":{}},{"cell_type":"code","source":"# sub_data = test_photo_to_biz.groupby('business_id').first()\n# test_photo_to_biz","metadata":{"execution":{"iopub.status.busy":"2023-11-27T16:36:14.232483Z","iopub.execute_input":"2023-11-27T16:36:14.233289Z","iopub.status.idle":"2023-11-27T16:36:14.237101Z","shell.execute_reply.started":"2023-11-27T16:36:14.233257Z","shell.execute_reply":"2023-11-27T16:36:14.236068Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"image_files = [f for f in os.listdir('/kaggle/working/train_photos') if f.endswith(('.jpg', '.jpeg', '.png')) and not f.startswith(('._'))]\n","metadata":{"execution":{"iopub.status.busy":"2023-11-27T17:30:47.463161Z","iopub.execute_input":"2023-11-27T17:30:47.464036Z","iopub.status.idle":"2023-11-27T17:30:47.886649Z","shell.execute_reply.started":"2023-11-27T17:30:47.464001Z","shell.execute_reply":"2023-11-27T17:30:47.885652Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data=pd.merge(train_photo_to_biz_ids, train_data, on='business_id',how='left')\n# data=data.head(10000)\ndata","metadata":{"execution":{"iopub.status.busy":"2023-11-27T17:30:50.767208Z","iopub.execute_input":"2023-11-27T17:30:50.768103Z","iopub.status.idle":"2023-11-27T17:30:50.801201Z","shell.execute_reply.started":"2023-11-27T17:30:50.768068Z","shell.execute_reply":"2023-11-27T17:30:50.800297Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# data_test=pd.merge(test_photo_to_biz,sample_sub, on='business_id',how='left') \n# data_test.head()","metadata":{"execution":{"iopub.status.busy":"2023-11-27T16:36:36.496668Z","iopub.execute_input":"2023-11-27T16:36:36.497402Z","iopub.status.idle":"2023-11-27T16:36:36.501106Z","shell.execute_reply.started":"2023-11-27T16:36:36.497368Z","shell.execute_reply":"2023-11-27T16:36:36.500189Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data['labs']=data['labels'].apply(lambda x:str(x).split(' '))\ndata\n","metadata":{"execution":{"iopub.status.busy":"2023-11-27T17:31:34.132864Z","iopub.execute_input":"2023-11-27T17:31:34.133518Z","iopub.status.idle":"2023-11-27T17:31:34.830309Z","shell.execute_reply.started":"2023-11-27T17:31:34.133475Z","shell.execute_reply":"2023-11-27T17:31:34.829261Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data = data.dropna(subset=['labels'])","metadata":{"execution":{"iopub.status.busy":"2023-11-27T17:34:45.396698Z","iopub.execute_input":"2023-11-27T17:34:45.397223Z","iopub.status.idle":"2023-11-27T17:34:45.440657Z","shell.execute_reply.started":"2023-11-27T17:34:45.397191Z","shell.execute_reply":"2023-11-27T17:34:45.439805Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"labelsint=data.labs.tolist()\nfor i in tqdm(labelsint):\n    for j in range(len(i)):\n#         print(j)\n#         break\n        i[j]=int(i[j])","metadata":{"execution":{"iopub.status.busy":"2023-11-27T17:34:46.798502Z","iopub.execute_input":"2023-11-27T17:34:46.799083Z","iopub.status.idle":"2023-11-27T17:34:47.419989Z","shell.execute_reply.started":"2023-11-27T17:34:46.799053Z","shell.execute_reply":"2023-11-27T17:34:47.419029Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data['labsint']=labelsint\ndata\n\ndata_train=data[[\"photo_id\",\"labsint\"]]\ndata_train\n","metadata":{"execution":{"iopub.status.busy":"2023-11-27T17:35:18.716248Z","iopub.execute_input":"2023-11-27T17:35:18.717118Z","iopub.status.idle":"2023-11-27T17:35:18.792981Z","shell.execute_reply.started":"2023-11-27T17:35:18.717083Z","shell.execute_reply":"2023-11-27T17:35:18.792036Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Take some random images and visualize them with their lables","metadata":{}},{"cell_type":"code","source":"# import matplotlib.pyplot as plt\n# import cv2\n# import random\n# import os\n\n# # หาไฟล์ภาพที่ใช้ได้\n\n\n\n\n# # Randomly sample 8 images\n# imgs_samples = random.sample(image_files, min(10, len(image_files)))\n\n# # Plot random sample of 8 images\n# plt.figure(figsize=(15, 10))\n\n# for i, img_file in enumerate(imgs_samples):\n#     # Get the image path\n#     img_path = os.path.join('/kaggle/working/train_photos', img_file)\n\n#     # Try to read the image\n#     img = cv2.imread(img_path)\n\n#     # Check if the image is successfully loaded\n#     if img is not None:\n#         # Convert color channels to RGB\n#         img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n\n#         # Grab image's business ID and labels (assuming you have these variables defined)\n#         business = train_photo_to_biz_ids.loc[train_photo_to_biz_ids['photo_id'] == int(img_file[:-4]), 'business_id']\n#         labels = train_data.loc[train_data['business_id'] == business.values[0], 'labels']\n\n#         # Annotate each image with image ID, business ID, and labels\n# #         title = \"Image ID: \" + img_file + ' Business: ' + str(business.values[0]) + '\\nLabels: ' + ''.join(labels.values)\n\n\n#     else:\n#         print(f\"Error: Unable to read image: {img_path}\")\n\n# plt.show()\n","metadata":{"execution":{"iopub.status.busy":"2023-11-27T16:37:12.704323Z","iopub.execute_input":"2023-11-27T16:37:12.704995Z","iopub.status.idle":"2023-11-27T16:37:12.975877Z","shell.execute_reply.started":"2023-11-27T16:37:12.704965Z","shell.execute_reply":"2023-11-27T16:37:12.974884Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Model CNN","metadata":{}},{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras import Sequential\nfrom tensorflow.keras.layers import Flatten, Dense, Dropout, BatchNormalization, Conv2D, MaxPool2D\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.preprocessing import image\n\nimg_width = 150\nimg_height = 150\nnum_images = 20000\n\nX = []\n\nfor i in tqdm(range(num_images)):\n    photo_id = data['photo_id'].iloc[i]\n    path = 'train_photos/' + str(photo_id) + '.jpg'\n    \n    img = image.load_img(path, target_size = (img_width, img_height))\n    img = image.img_to_array(img)\n    img = img/255.0\n    X.append(img)\n\nX = np.array(X)","metadata":{"execution":{"iopub.status.busy":"2023-11-27T17:23:16.163644Z","iopub.execute_input":"2023-11-27T17:23:16.164475Z","iopub.status.idle":"2023-11-27T17:23:55.077807Z","shell.execute_reply.started":"2023-11-27T17:23:16.164442Z","shell.execute_reply":"2023-11-27T17:23:55.076852Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_dir= 'train_photos/'\n\nimg_height=100\nimh_width=100\nbatch_size=32\nepochs=20\ntrain_gen=ImageDataGenerator(rescale=1/255, validation_split=.2)\n                                     .flow_from_directory( train_dir,\n                                      target_size=(img_height, img_width),                                                                              \n                                      batch_size=batch_size, seed=123,                                                                               \n                                      class_mode='categorical',subset='training' \n                                      shuffle=True)\nvalid_gen= ImageDataGenerator(rescale=1/255, validation_split=.2)\n                                     .flow_from_directory( train_dir,\n                                      target_size=(img_height, img_width),                                                                              \n                                      batch_size=batch_size, seed=123,                                                                               \n                                      class_mode='categorical',subset='validation' \n                                      shuffle=False)\n    \n    \ntrain_generator = train_datagen.flow_from_directory(\n    directory=r\"./train/\",\n    target_size=(224, 224),\n    color_mode=\"rgb\",\n    batch_size=32,\n    class_mode=\"categorical\",\n    shuffle=True,\n    seed=42\n)\n    \ntrain_datagen = ImageDataGenerator(\n        rescale=1./255,\n        shear_range=0.2,\n        zoom_range=0.2,\n        horizontal_flip=True)\n\n\nvalidation_generator = test_datagen.flow_from_directory(\n        'data/validation',\n        target_size=(150, 150),\n        batch_size=32,\n        class_mode='binary')\nmodel.fit(\n        train_generator,\n        steps_per_epoch=2000,\n        epochs=50,\n        validation_data=validation_generator,\n        validation_steps=800) ","metadata":{"execution":{"iopub.status.busy":"2023-11-27T18:02:34.313914Z","iopub.execute_input":"2023-11-27T18:02:34.314450Z","iopub.status.idle":"2023-11-27T18:02:34.323152Z","shell.execute_reply.started":"2023-11-27T18:02:34.314411Z","shell.execute_reply":"2023-11-27T18:02:34.322006Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data","metadata":{"execution":{"iopub.status.busy":"2023-11-27T17:38:12.760986Z","iopub.execute_input":"2023-11-27T17:38:12.761356Z","iopub.status.idle":"2023-11-27T17:38:12.781336Z","shell.execute_reply.started":"2023-11-27T17:38:12.761326Z","shell.execute_reply":"2023-11-27T17:38:12.780331Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# selected_img 20000\n\ny=data[['labsint']]\ny=y[0:20000]","metadata":{"execution":{"iopub.status.busy":"2023-11-27T17:47:22.115117Z","iopub.execute_input":"2023-11-27T17:47:22.115807Z","iopub.status.idle":"2023-11-27T17:47:22.126791Z","shell.execute_reply.started":"2023-11-27T17:47:22.115775Z","shell.execute_reply":"2023-11-27T17:47:22.125950Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Assuming y is a DataFrame with multiple label columns\n\n\nmlb = MultiLabelBinarizer()\none_hot_labels = mlb.fit_transform(y['labsint'])\nlabel_names = ['good_for_lunch', 'good_for_dinner', 'takes_reservations',\n               'outdoor_seating', 'restaurant_is_expensive', 'has_alcohol',\n               'has_table_service', 'ambience_is_classy', 'good_for_kids']\n\ny = pd.DataFrame(one_hot_labels, columns=label_names)\n\n# Display the resulting DataFrame\ny","metadata":{"execution":{"iopub.status.busy":"2023-11-27T17:47:30.062410Z","iopub.execute_input":"2023-11-27T17:47:30.062783Z","iopub.status.idle":"2023-11-27T17:47:30.126135Z","shell.execute_reply.started":"2023-11-27T17:47:30.062752Z","shell.execute_reply":"2023-11-27T17:47:30.125081Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Reduce size\n\n\n# Train data\nX_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0, test_size=0.3)\nX_train.shape, X_test.shape, y_train.shape, y_test.shape","metadata":{"execution":{"iopub.status.busy":"2023-11-27T17:47:34.300636Z","iopub.execute_input":"2023-11-27T17:47:34.301570Z","iopub.status.idle":"2023-11-27T17:47:37.299499Z","shell.execute_reply.started":"2023-11-27T17:47:34.301527Z","shell.execute_reply":"2023-11-27T17:47:37.297250Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras import Sequential\nfrom tensorflow.keras.layers import Flatten, Dense, Dropout, BatchNormalization, Conv2D, MaxPool2D\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.preprocessing import image\nfrom tensorflow.keras import layers, callbacks","metadata":{"execution":{"iopub.status.busy":"2023-11-27T17:47:42.170635Z","iopub.execute_input":"2023-11-27T17:47:42.171494Z","iopub.status.idle":"2023-11-27T17:47:42.176340Z","shell.execute_reply.started":"2023-11-27T17:47:42.171461Z","shell.execute_reply":"2023-11-27T17:47:42.175436Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nmodel = Sequential()\nmodel.add(Conv2D(32, (7,7), activation='relu', input_shape = X_train[0].shape))\nmodel.add(BatchNormalization())\nmodel.add(MaxPool2D(4,4))\n\n\nmodel.add(Conv2D(64, (7,7), activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPool2D(4,4))\n\n\n\nmodel.add(Flatten())\n\nmodel.add(Dense(64, activation='relu'))\nmodel.add(BatchNormalization())\n\n\n\nmodel.add(Dense(9, activation='relu'))\n\nmodel.summary()\n\n\nearly_stopping = callbacks.EarlyStopping(\n    min_delta=0.1, # minimium amount of change to count as an improvement\n    patience=5, # how many epochs to wait before stopping\n    restore_best_weights=True,)","metadata":{"execution":{"iopub.status.busy":"2023-11-27T17:47:51.385496Z","iopub.execute_input":"2023-11-27T17:47:51.386354Z","iopub.status.idle":"2023-11-27T17:47:53.960212Z","shell.execute_reply.started":"2023-11-27T17:47:51.386320Z","shell.execute_reply":"2023-11-27T17:47:53.959193Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from keras.optimizers import Adam\n\n# 1. สร้าง Adam optimizer โดยกำหนด learning_rate=0.01\nopt = Adam(learning_rate=0.01)\n\n# 2. Compile โมเดลโดยใช้ Adam optimizer ที่สร้างขึ้น\nmodel.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n\n# 3. Fit โมเดลด้วยข้อมูลการฝึกและการทดสอบ\nhistory = model.fit(X_train, y_train, epochs=20, validation_data=(X_test, y_test))\n","metadata":{"execution":{"iopub.status.busy":"2023-11-27T17:48:00.737784Z","iopub.execute_input":"2023-11-27T17:48:00.738158Z","iopub.status.idle":"2023-11-27T17:54:20.843237Z","shell.execute_reply.started":"2023-11-27T17:48:00.738128Z","shell.execute_reply":"2023-11-27T17:54:20.841676Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"val_score, val_acc = model.evaluate(X_test, y_test, verbose=0)\ntrain_score,train_acc = model.evaluate(X_train, y_train, verbose=0)\nprint('Validation score:', val_score,'Validation accuracy:', val_acc)\nprint('Train score:', train_score,'   Train accuracy:', train_acc)","metadata":{"execution":{"iopub.status.busy":"2023-11-27T16:49:27.458931Z","iopub.execute_input":"2023-11-27T16:49:27.459338Z","iopub.status.idle":"2023-11-27T16:49:32.428496Z","shell.execute_reply.started":"2023-11-27T16:49:27.459308Z","shell.execute_reply":"2023-11-27T16:49:32.427580Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"code","source":"def plot_learningCurve(history):\n    # Plot training & validation accuracy values\n    plt.plot(history['accuracy'])\n    plt.plot(history['val_accuracy'])\n    plt.title('Model accuracy')\n    plt.ylabel('Accuracy')\n    plt.xlabel('Epoch')\n    plt.legend(['Train', 'Val'], loc='upper left')\n    plt.show()\n\n    # Plot training & validation loss values\n    plt.plot(history['loss'])\n    plt.plot(history['val_loss'])\n    plt.title('Model loss')\n    plt.ylabel('Loss')\n    plt.xlabel('Epoch')\n    plt.legend(['Train', 'Val'], loc='upper left')\n    plt.show()\n\n# ใช้งานฟังก์ชัน\nplot_learningCurve(history.history)\n","metadata":{"execution":{"iopub.status.busy":"2023-11-27T15:10:08.733497Z","iopub.execute_input":"2023-11-27T15:10:08.734289Z","iopub.status.idle":"2023-11-27T15:10:09.419903Z","shell.execute_reply.started":"2023-11-27T15:10:08.734253Z","shell.execute_reply":"2023-11-27T15:10:09.418962Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"classification_report","metadata":{}},{"cell_type":"code","source":"X_test.shape,y_test.shape","metadata":{"execution":{"iopub.status.busy":"2023-11-27T15:10:09.421025Z","iopub.execute_input":"2023-11-27T15:10:09.421303Z","iopub.status.idle":"2023-11-27T15:10:09.427603Z","shell.execute_reply.started":"2023-11-27T15:10:09.421278Z","shell.execute_reply":"2023-11-27T15:10:09.426683Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_pred = model.predict(X_test)\ny_pred = np.argmax(y_pred, axis=1)\n\ny_true = np.argmax(y_test, axis=1)\n","metadata":{"execution":{"iopub.status.busy":"2023-11-27T15:10:09.428668Z","iopub.execute_input":"2023-11-27T15:10:09.428933Z","iopub.status.idle":"2023-11-27T15:10:11.010217Z","shell.execute_reply.started":"2023-11-27T15:10:09.428909Z","shell.execute_reply":"2023-11-27T15:10:11.009170Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"c = Counter(y_true)\nc","metadata":{"execution":{"iopub.status.busy":"2023-11-27T15:10:11.011442Z","iopub.execute_input":"2023-11-27T15:10:11.011740Z","iopub.status.idle":"2023-11-27T15:10:11.018755Z","shell.execute_reply.started":"2023-11-27T15:10:11.011713Z","shell.execute_reply":"2023-11-27T15:10:11.017702Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.metrics import classification_report\n\nprint(classification_report(y_true, y_pred))","metadata":{"execution":{"iopub.status.busy":"2023-11-27T18:15:58.653852Z","iopub.execute_input":"2023-11-27T18:15:58.654644Z","iopub.status.idle":"2023-11-27T18:15:58.694456Z","shell.execute_reply.started":"2023-11-27T18:15:58.654608Z","shell.execute_reply":"2023-11-27T18:15:58.693121Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"สุ่มรูป 20 รูป จาก train_photos มา predict","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras.preprocessing import image\nimport numpy as np\nimport os\n\nimage_directory = '/kaggle/working/test_photos'\n\n# Assuming you have already defined img_width and img_height\nimage_files = [file for file in os.listdir(image_directory) if file[:-4].isdigit() and file.lower().endswith('.jpg')]\n\n# Shuffle the list of image files\nnp.random.shuffle(image_files)\n\n# Limit the number of images to predict\nnum_images_to_predict = 10\n\nfor i in range(num_images_to_predict):\n    file = image_files[i]\n    img_path = os.path.join(image_directory, file)\n    \n    # Update the target size to match the input shape of your model\n    img = image.load_img(img_path, target_size=(300, 300))\n\n    img_array = image.img_to_array(img)\n    img_array = np.expand_dims(img_array, axis=0)\n    img_array /= 255.0  # Normalize pixel values to be between 0 and 1\n\n    # ทำนาย labels\n    predictions = model.predict(img_array)\n\n    # นำ labels ที่ทำนายได้มาเรียกตามลำดับ\n    label_names = ['good_for_lunch', 'good_for_dinner', 'takes_reservations',\n                   'outdoor_seating', 'restaurant_is_expensive', 'has_alcohol',\n                   'has_table_service', 'ambience_is_classy', 'good_for_kids']\n\n    predicted_labels = [label_names[i] for i, pred in enumerate(predictions[0]) if pred > 0.5]\n\n    # แสดงรูปภาพ\n    plt.imshow(img)\n    plt.show()\n\n    # แสดง labels ที่ทำนายได้\n    print(\"Predicted labels:\", predicted_labels)\n","metadata":{"execution":{"iopub.status.busy":"2023-11-27T15:10:11.045268Z","iopub.execute_input":"2023-11-27T15:10:11.045917Z","iopub.status.idle":"2023-11-27T15:10:15.491874Z","shell.execute_reply.started":"2023-11-27T15:10:11.045877Z","shell.execute_reply":"2023-11-27T15:10:15.490953Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Model Resnet50","metadata":{}},{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras import Sequential\nfrom tensorflow.keras.layers import Flatten, Dense, Dropout, BatchNormalization, Conv2D, MaxPool2D, GlobalAveragePooling2D\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.preprocessing import image\nfrom tensorflow.keras.applications import ResNet50\nfrom tensorflow.keras.applications.resnet50 import preprocess_input\n","metadata":{"execution":{"iopub.status.busy":"2023-11-27T15:10:15.493138Z","iopub.execute_input":"2023-11-27T15:10:15.493490Z","iopub.status.idle":"2023-11-27T15:10:15.505194Z","shell.execute_reply.started":"2023-11-27T15:10:15.493460Z","shell.execute_reply":"2023-11-27T15:10:15.504058Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n# Load the ResNet50 model pretrained on ImageNet data\nresnet_model = ResNet50(weights='imagenet', include_top=False, input_shape=(img_width, img_height, 3))\n\n# Freeze the layers\nfor layer in resnet_model.layers:\n    layer.trainable = False\n\n# Create a new model by adding ResNet50 and additional layers\nmodel = Sequential()\nmodel.add(resnet_model)\nmodel.add(GlobalAveragePooling2D())\nmodel.add(Dense(128, activation='relu'))\nmodel.add(Dense(9, activation='sigmoid'))\n\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2023-11-27T15:10:15.506459Z","iopub.execute_input":"2023-11-27T15:10:15.507064Z","iopub.status.idle":"2023-11-27T15:10:21.405960Z","shell.execute_reply.started":"2023-11-27T15:10:15.507036Z","shell.execute_reply":"2023-11-27T15:10:21.405014Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Compile the model\nopt = Adam(learning_rate=0.01)\nmodel.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\n\n# Train the model\nhistory_resnet = model.fit(X_train, y_train, epochs=5, validation_data=(X_test, y_test))","metadata":{"execution":{"iopub.status.busy":"2023-11-27T15:10:21.407309Z","iopub.execute_input":"2023-11-27T15:10:21.407604Z","iopub.status.idle":"2023-11-27T15:11:03.820883Z","shell.execute_reply.started":"2023-11-27T15:10:21.407579Z","shell.execute_reply":"2023-11-27T15:11:03.819796Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Evaluate the model\nval_score_resnet, val_acc_resnet = model.evaluate(X_test, y_test, verbose=0)\ntrain_score_resnet, train_acc_resnet = model.evaluate(X_train, y_train, verbose=0)\nprint('Validation score:', val_score_resnet, 'Validation accuracy:', val_acc_resnet)\nprint('Train score:', train_score_resnet, 'Train accuracy:', train_acc_resnet)","metadata":{"execution":{"iopub.status.busy":"2023-11-27T15:11:03.822481Z","iopub.execute_input":"2023-11-27T15:11:03.822780Z","iopub.status.idle":"2023-11-27T15:11:18.777115Z","shell.execute_reply.started":"2023-11-27T15:11:03.822755Z","shell.execute_reply":"2023-11-27T15:11:18.776038Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def plot_learningCurve(history):\n    # Plot training & validation accuracy values\n    plt.plot(history['accuracy'])\n    plt.plot(history['val_accuracy'])\n    plt.title('Model accuracy')\n    plt.ylabel('Accuracy')\n    plt.xlabel('Epoch')\n    plt.legend(['Train', 'Val'], loc='upper left')\n    plt.show()\n\n    # Plot training & validation loss values\n    plt.plot(history['loss'])\n    plt.plot(history['val_loss'])\n    plt.title('Model loss')\n    plt.ylabel('Loss')\n    plt.xlabel('Epoch')\n    plt.legend(['Train', 'Val'], loc='upper left')\n    plt.show()\n\n# ใช้งานฟังก์ชัน\nplot_learningCurve(history.history)\n","metadata":{"execution":{"iopub.status.busy":"2023-11-27T15:11:18.778531Z","iopub.execute_input":"2023-11-27T15:11:18.778866Z","iopub.status.idle":"2023-11-27T15:11:19.392784Z","shell.execute_reply.started":"2023-11-27T15:11:18.778837Z","shell.execute_reply":"2023-11-27T15:11:19.391800Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.preprocessing import image\nimport numpy as np\nimport os\n\nimage_directory = '/kaggle/working/test_photos'\n\n# Assuming you have already defined img_width and img_height\nimage_files = [file for file in os.listdir(image_directory) if file[:-4].isdigit() and file.lower().endswith('.jpg')]\n\n# Shuffle the list of image files\nnp.random.shuffle(image_files)\n\n #Limit the number of images to predict\nnum_images_to_predict = 10\n\nfor i in range(num_images_to_predict):\n    file = image_files[i]\n    img_path = os.path.join(image_directory, file)\n    \n    # Update the target size to match the input shape of your model\n    img = image.load_img(img_path, target_size=(300, 300))\n\n    img_array = image.img_to_array(img)\n    img_array = np.expand_dims(img_array, axis=0)\n    img_array /= 255.0  # Normalize pixel values to be between 0 and 1\n\n    # ทำนาย labels\n    predictions = model.predict(img_array)\n\n    # นำ labels ที่ทำนายได้มาเรียกตามลำดับ\n    label_names = ['good_for_lunch', 'good_for_dinner', 'takes_reservations',\n                   'outdoor_seating', 'restaurant_is_expensive', 'has_alcohol',\n                   'has_table_service', 'ambience_is_classy', 'good_for_kids']\n\n    predicted_labels = [label_names[i] for i, pred in enumerate(predictions[0]) if pred > 0.5]\n\n    # แสดงรูปภาพ\n    plt.imshow(img)\n    plt.show()\n\n    # แสดง labels ที่ทำนายได้\n    print(\"Predicted labels:\", predicted_labels)\n","metadata":{"execution":{"iopub.status.busy":"2023-11-27T15:11:19.393886Z","iopub.execute_input":"2023-11-27T15:11:19.394165Z","iopub.status.idle":"2023-11-27T15:11:25.059279Z","shell.execute_reply.started":"2023-11-27T15:11:19.394140Z","shell.execute_reply":"2023-11-27T15:11:25.058424Z"},"trusted":true},"execution_count":null,"outputs":[]}]}