{"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":30587,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"<div style=\"background-color: #FFF3E0; padding: 20px; border-radius: 10px; box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.1);\">\n    <h1 style=\"font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif; text-align: center; color: #3A405A;\">DSI206 Project</h1>\n</div>","metadata":{}},{"cell_type":"markdown","source":"\n<div style=\"background-color: #FFE5E5; padding: 15px; border-radius: 10px; box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.1);\">\n    <h1 style=\"font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif; text-align: center; color: #3A405A;\">Yelp Restaurant Photo Classification</h1>\n</div>","metadata":{}},{"cell_type":"markdown","source":"\n<div class=\"alert alert-block alert-info\">\n    <h2 align=\"left\"> <font>Introduction</font></h2>\n\n</div>","metadata":{}},{"cell_type":"markdown","source":"จุดมุ่งหมาย : เพื่อศึกษาวิธีการทำโมเดล Photo Clssification โดยการแยกประเภทของรูปภาพอาหาร ในร้านอาหารต่างๆ 9 ประเภท จากรูปภาพทั้งหมด 234842 ภาพ ในชุดข้อมูล Yelp Restaurant Photo Classification ด้วยภาษา Python\n","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":"**File descriptions**\n* sample_submission.csv\n* test_photo_to_biz.csv\n* test_photos\n* train.csv\n* train_photo_to_biz_ids.csv\n* train_photos\n","metadata":{}},{"cell_type":"markdown","source":"### Members\n1. 6524651095 ปาณิสรา กุยยะรัตน์\n2. 6524651129 พิมพกานต์ คงทอง\n3. 6524651236 ณัชชา คงแก้ว\n4. 6524651301 พิชามญชุ์ พรอรุณสถาพร\n5. 6524651343 รอยมีย์ เนสะและ\n6. 6524651392 วรานิษฐ์ เตชะระพีพัฒน์","metadata":{}},{"cell_type":"markdown","source":"\n<div class=\"alert alert-block alert-info\">\n    <font>โดย notebook นี้เป็นการทดลอง Photo classification รูป ด้วยโมเดล ResNet50 เพื่อใช้เปรียบเทียบกับโมเดล CNN</font></h2>\n\n</div>\n","metadata":{}},{"cell_type":"markdown","source":"### ขั้นตอนการดำเนินงาน\n1. Data Exploration\n2. Data Preparation\n3. Modeling\n4. Project Summary","metadata":{}},{"cell_type":"markdown","source":"# 1.Data Exploration\n*  Imports Libraries ที่ต้องการใช้\n* นำเข้าข้อมูลจากชุดข้อมูล\n* ดูข้อมูลที่นำเข้ามาว่ามีข้อมูลอะไรบ้าง","metadata":{}},{"cell_type":"code","source":"# import Library ทั้งหมดที่ต้องใช้\nimport 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.neighbors import KNeighborsClassifier\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","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-11-28T07:14:24.588515Z","iopub.execute_input":"2023-11-28T07:14:24.588938Z","iopub.status.idle":"2023-11-28T07:14:26.243323Z","shell.execute_reply.started":"2023-11-28T07:14:24.588895Z","shell.execute_reply":"2023-11-28T07:14:26.242204Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"นำเข้าชุดข้อมูล Yelp Restaurant Photo Classification","metadata":{}},{"cell_type":"code","source":"%%bash\ntar -xzf /kaggle/input/yelp-restaurant-photo-classification/sample_submission.csv.tgz\ntar -xzf /kaggle/input/yelp-restaurant-photo-classification/test_photo_to_biz.csv.tgz\ntar -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-28T07:14:26.245226Z","iopub.execute_input":"2023-11-28T07:14:26.245773Z","iopub.status.idle":"2023-11-28T07:19:04.726416Z","shell.execute_reply.started":"2023-11-28T07:14:26.245735Z","shell.execute_reply":"2023-11-28T07:19:04.725599Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"อ่านไฟล์ csv แล้วนำข้อมูลไปเก็บในตัวแปรต่างๆ","metadata":{}},{"cell_type":"code","source":"\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')\ntest_photo_to_biz = pd.read_csv('test_photo_to_biz.csv')\nsample_sub = pd.read_csv('sample_submission.csv')\n\n# แสดง information และตัวอย่างข้อมูล ของข้อมูล Train data\nprint(train_data.info())\nprint(train_data.head())","metadata":{"execution":{"iopub.status.busy":"2023-11-28T07:19:04.727527Z","iopub.execute_input":"2023-11-28T07:19:04.728104Z","iopub.status.idle":"2023-11-28T07:19:05.242002Z","shell.execute_reply.started":"2023-11-28T07:19:04.728077Z","shell.execute_reply":"2023-11-28T07:19:05.241039Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Dataframe แสดงตัวอย่างข้อมูลที่นำเข้ามา","metadata":{}},{"cell_type":"markdown","source":"แสดงตัวอย่างข้อมูล และจำนวนข้อมูลใน train_photo_to_biz_ids","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-28T07:19:05.244668Z","iopub.execute_input":"2023-11-28T07:19:05.245312Z","iopub.status.idle":"2023-11-28T07:19:05.257821Z","shell.execute_reply.started":"2023-11-28T07:19:05.245277Z","shell.execute_reply":"2023-11-28T07:19:05.256888Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"แสดงตัวอย่างข้อมูล และจำนวนข้อมูลใน train_data\n","metadata":{}},{"cell_type":"code","source":"# Load training data that maps business ID to labels\ndisplay_module.display(train_data.head())\nprint('Shape of train data:', train_data.shape)\nprint('Number of unique businesses:', train_data.shape[0])\n","metadata":{"execution":{"iopub.status.busy":"2023-11-28T07:19:05.259060Z","iopub.execute_input":"2023-11-28T07:19:05.259409Z","iopub.status.idle":"2023-11-28T07:19:05.449628Z","shell.execute_reply.started":"2023-11-28T07:19:05.259377Z","shell.execute_reply":"2023-11-28T07:19:05.448679Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Missing Values**\nตรวจสอบข้อมูลที่หายไปในชุดข้อมูล และแสดงรายละเอียดข้อมูลนั้น เนื่องจาก Missing Values สามารถมีผลกระทบต่อการ Train Model เราจึงทำการลบ 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-28T07:19:05.450704Z","iopub.execute_input":"2023-11-28T07:19:05.451459Z","iopub.status.idle":"2023-11-28T07:19:05.464137Z","shell.execute_reply.started":"2023-11-28T07:19:05.451432Z","shell.execute_reply":"2023-11-28T07:19:05.463176Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# ลบค่าที่หายไปจากคอลัมน์ 'labels'\ntrain_data = train_data.dropna(subset=['labels'])\n\n# ตรวจสอบข้อมูลหลังจากลบค่าที่หายไป\nprint('Total number of missing labels after removal:', train_data['labels'].isnull().sum())","metadata":{"execution":{"iopub.status.busy":"2023-11-28T07:19:05.465325Z","iopub.execute_input":"2023-11-28T07:19:05.465697Z","iopub.status.idle":"2023-11-28T07:19:05.476526Z","shell.execute_reply.started":"2023-11-28T07:19:05.465665Z","shell.execute_reply":"2023-11-28T07:19:05.475648Z"},"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(('._'))]","metadata":{"execution":{"iopub.status.busy":"2023-11-28T07:19:05.477734Z","iopub.execute_input":"2023-11-28T07:19:05.478030Z","iopub.status.idle":"2023-11-28T07:19:05.908536Z","shell.execute_reply.started":"2023-11-28T07:19:05.477997Z","shell.execute_reply":"2023-11-28T07:19:05.907637Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Merg Dataframe \nนำข้อมูลที่มีความเกี่ยวข้องกัน ของแต่ละ dataframe มาเชื่อมโยงกัน เพื่อสามารถเรียกใช้ข้อมูลได้อย่างมีประสิทธิภาพ","metadata":{}},{"cell_type":"code","source":"data=pd.merge(train_photo_to_biz_ids, train_data, on='business_id',how='left')\ndata=data.head(20000)\ndata","metadata":{"execution":{"iopub.status.busy":"2023-11-28T07:19:05.909545Z","iopub.execute_input":"2023-11-28T07:19:05.909853Z","iopub.status.idle":"2023-11-28T07:19:05.952741Z","shell.execute_reply.started":"2023-11-28T07:19:05.909829Z","shell.execute_reply":"2023-11-28T07:19:05.951791Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data=data.dropna(subset=['labels'])\ndata = data.head(10000)\ndata","metadata":{"execution":{"iopub.status.busy":"2023-11-28T07:19:05.956123Z","iopub.execute_input":"2023-11-28T07:19:05.956399Z","iopub.status.idle":"2023-11-28T07:19:05.972411Z","shell.execute_reply.started":"2023-11-28T07:19:05.956375Z","shell.execute_reply":"2023-11-28T07:19:05.971562Z"},"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') \ndata_test.head()","metadata":{"execution":{"iopub.status.busy":"2023-11-28T07:19:05.973481Z","iopub.execute_input":"2023-11-28T07:19:05.973757Z","iopub.status.idle":"2023-11-28T07:19:06.270050Z","shell.execute_reply.started":"2023-11-28T07:19:05.973733Z","shell.execute_reply":"2023-11-28T07:19:06.269002Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data['labs']=data['labels'].apply(lambda x:str(x).split(' '))\ndata","metadata":{"execution":{"iopub.status.busy":"2023-11-28T07:19:06.271561Z","iopub.execute_input":"2023-11-28T07:19:06.271985Z","iopub.status.idle":"2023-11-28T07:19:06.299375Z","shell.execute_reply.started":"2023-11-28T07:19:06.271952Z","shell.execute_reply":"2023-11-28T07:19:06.298464Z"},"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        i[j]=int(i[j])","metadata":{"execution":{"iopub.status.busy":"2023-11-28T07:19:06.300582Z","iopub.execute_input":"2023-11-28T07:19:06.300868Z","iopub.status.idle":"2023-11-28T07:19:06.339574Z","shell.execute_reply.started":"2023-11-28T07:19:06.300845Z","shell.execute_reply":"2023-11-28T07:19:06.338741Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data['labsint']=labelsint\ndata\n\ndata_train=data[[\"photo_id\",\"labsint\"]]\ndata_train","metadata":{"execution":{"iopub.status.busy":"2023-11-28T07:19:06.340740Z","iopub.execute_input":"2023-11-28T07:19:06.341018Z","iopub.status.idle":"2023-11-28T07:19:06.359466Z","shell.execute_reply.started":"2023-11-28T07:19:06.340993Z","shell.execute_reply":"2023-11-28T07:19:06.358405Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 2.Data Preparation","metadata":{}},{"cell_type":"markdown","source":"จัดเตรียมข้อมูลเพื่อนำมา train โดยโหลดรูปภาพจากไฟล์ในโฟลเดอร์ 'train_photos' และนำมาเก็บไว้ในตัวแปร X  และทำการแปลงรูปภาพให้อยู่ในรูปแบบของ NumPy array เพื่อให้สามารถนำมาใช้ในการฝึกโมเดลได้","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\n\nimg_width = 150\nimg_height = 150\nnum_images = 10000\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-28T07:19:06.360699Z","iopub.execute_input":"2023-11-28T07:19:06.361070Z","iopub.status.idle":"2023-11-28T07:19:38.750156Z","shell.execute_reply.started":"2023-11-28T07:19:06.361035Z","shell.execute_reply":"2023-11-28T07:19:38.749017Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### One-Hot Encoding \nใช้  One-Hot Encoding เพื่อแปลงข้อมูลประเภทของรูปภาพอาหาร ที่มีอยู่ในประเภทอาหารนั้นๆ ให้กลายเป็น vector มีค่า 1,0 เพื่อให้โมเดล Machine Learning ทำงานง่ายขึ้น","metadata":{}},{"cell_type":"code","source":"from sklearn.preprocessing import MultiLabelBinarizer\nimport pandas as pd\ny = data.drop(['photo_id', 'labels', 'business_id', 'labs'], axis=1)\n# ข้อมูล\n# Define label names\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\n\n# ใช้ MultiLabelBinarizer\nmlb = MultiLabelBinarizer()\none_hot_labels = mlb.fit_transform(y['labsint'])\n\ny = pd.DataFrame(one_hot_labels, columns=label_names)\n# สร้าง DataFrame ใหม่\ny\n","metadata":{"execution":{"iopub.status.busy":"2023-11-28T07:19:38.751585Z","iopub.execute_input":"2023-11-28T07:19:38.752255Z","iopub.status.idle":"2023-11-28T07:19:38.798982Z","shell.execute_reply.started":"2023-11-28T07:19:38.752216Z","shell.execute_reply":"2023-11-28T07:19:38.797992Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 3.Modeling ResNet50 Model","metadata":{}},{"cell_type":"code","source":"# Make sure X_resnet and y_encoded have the same number of samples\nmin_samples = min(X.shape[0], y.shape[0])\nX = X[:min_samples]\ny = y.iloc[:min_samples, :]\n\n# Split the data\nX_train, X_test, y_train, y_test = train_test_split(X, y, random_state=0, test_size=0.2)","metadata":{"execution":{"iopub.status.busy":"2023-11-28T07:19:38.800159Z","iopub.execute_input":"2023-11-28T07:19:38.800449Z","iopub.status.idle":"2023-11-28T07:19:40.023455Z","shell.execute_reply.started":"2023-11-28T07:19:38.800424Z","shell.execute_reply":"2023-11-28T07:19:40.022672Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Load the ResNet50 model pretrained on ImageNet data\nresnet_model = ResNet50(weights='imagenet', include_top=False, input_shape=(img_width, img_height, 3))","metadata":{"execution":{"iopub.status.busy":"2023-11-28T07:19:40.024708Z","iopub.execute_input":"2023-11-28T07:19:40.024971Z","iopub.status.idle":"2023-11-28T07:19:45.238891Z","shell.execute_reply.started":"2023-11-28T07:19:40.024948Z","shell.execute_reply":"2023-11-28T07:19:45.237894Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 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-28T07:19:45.240601Z","iopub.execute_input":"2023-11-28T07:19:45.240985Z","iopub.status.idle":"2023-11-28T07:19:45.821516Z","shell.execute_reply.started":"2023-11-28T07:19:45.240951Z","shell.execute_reply":"2023-11-28T07:19:45.820625Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Train Model","metadata":{}},{"cell_type":"code","source":"# Compile the model\nopt = Adam(learning_rate=0.001)\nmodel.compile(optimizer=opt, loss='binary_crossentropy', metrics=['accuracy'])\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-28T07:19:45.822695Z","iopub.execute_input":"2023-11-28T07:19:45.822951Z","iopub.status.idle":"2023-11-28T07:21:19.524480Z","shell.execute_reply.started":"2023-11-28T07:19:45.822929Z","shell.execute_reply":"2023-11-28T07:21:19.523150Z"},"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-28T07:21:19.526505Z","iopub.execute_input":"2023-11-28T07:21:19.526896Z","iopub.status.idle":"2023-11-28T07:21:40.649978Z","shell.execute_reply.started":"2023-11-28T07:21:19.526870Z","shell.execute_reply":"2023-11-28T07:21:40.648980Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"กราฟแสดงค่า accuracy และ loss ของโมเดลในระหว่างการฝึก (training) และการทดสอบ (validation) ในแต่ละ epoch หลังจากการฝึกโมเดล","metadata":{}},{"cell_type":"code","source":"def plot_learningCurve(history_resnet):\n    # Plot training & validation accuracy values\n    plt.plot(history_resnet['accuracy'])\n    plt.plot(history_resnet['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_resnet['loss'])\n    plt.plot(history_resnet['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_resnet.history)\n","metadata":{"execution":{"iopub.status.busy":"2023-11-28T07:38:13.865212Z","iopub.execute_input":"2023-11-28T07:38:13.866125Z","iopub.status.idle":"2023-11-28T07:38:14.474722Z","shell.execute_reply.started":"2023-11-28T07:38:13.866087Z","shell.execute_reply":"2023-11-28T07:38:14.473803Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_pred = model.predict(X_test)\n\ny_pred = np.argmax(y_pred, axis=1)\ny_true = np.argmax(y_test, axis=1)\n\ncm = confusion_matrix(y_true, y_pred)\nplt.figure(figsize=(7, 7))\nax = sns.heatmap(cm, cmap=plt.cm.Reds, annot=True, square=True, xticklabels=label_names, yticklabels=label_names)\nax.set_ylabel('Actual', fontsize=15)\nax.set_xlabel('Predicted', fontsize=15)","metadata":{"execution":{"iopub.status.busy":"2023-11-28T07:38:18.110480Z","iopub.execute_input":"2023-11-28T07:38:18.110831Z","iopub.status.idle":"2023-11-28T07:38:23.211710Z","shell.execute_reply.started":"2023-11-28T07:38:18.110804Z","shell.execute_reply":"2023-11-28T07:38:23.210775Z"},"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)","metadata":{"execution":{"iopub.status.busy":"2023-11-28T07:38:26.496417Z","iopub.execute_input":"2023-11-28T07:38:26.497533Z","iopub.status.idle":"2023-11-28T07:38:30.278407Z","shell.execute_reply.started":"2023-11-28T07:38:26.497485Z","shell.execute_reply":"2023-11-28T07:38:30.277524Z"},"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-28T07:38:32.448939Z","iopub.execute_input":"2023-11-28T07:38:32.449294Z","iopub.status.idle":"2023-11-28T07:38:32.467173Z","shell.execute_reply.started":"2023-11-28T07:38:32.449265Z","shell.execute_reply":"2023-11-28T07:38:32.466272Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 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=(200, 200))\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)","metadata":{"execution":{"iopub.status.busy":"2023-11-28T07:38:47.119696Z","iopub.execute_input":"2023-11-28T07:38:47.120714Z","iopub.status.idle":"2023-11-28T07:38:53.271167Z","shell.execute_reply.started":"2023-11-28T07:38:47.120677Z","shell.execute_reply":"2023-11-28T07:38:53.270265Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# 4.Project Summary","metadata":{}},{"cell_type":"markdown","source":"จากการที่พวกเราทำโมเดลออกมา เราได้ค่า accuracy ประมาณ 0.04 ซึ่งเป็นค่าที่น้อยมาก และค่า loss ที่สูง แสดงให้เห็นว่า โมเดลของเรายังทำนายได้ไม่แม่นยำพอ ","metadata":{}}]}