{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.7.9","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":5048,"databundleVersionId":868335,"sourceType":"competition"}],"dockerImageVersionId":30066,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Importing Libraries","metadata":{}},{"cell_type":"code","source":"import os\nimport pandas as pd\nimport pickle\nimport shutil\nimport numpy as np\nimport seaborn as sns\nfrom sklearn.datasets import load_files\nfrom keras.utils import np_utils\nimport matplotlib.pyplot as plt\nfrom keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D\nfrom keras.layers import Dropout, Flatten, Dense\nfrom keras.models import Sequential\nfrom keras.utils.vis_utils import plot_model\nfrom keras.callbacks import ModelCheckpoint\nfrom keras.utils import to_categorical\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import accuracy_score,precision_score,recall_score,f1_score\n\n\nfrom PIL import ImageFile   \nfrom sklearn.model_selection import train_test_split\nfrom keras.preprocessing import image                  \nfrom tqdm import tqdm\n\nfrom keras.applications.vgg16 import VGG16","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-19T12:00:11.943544Z","iopub.execute_input":"2025-12-19T12:00:11.943937Z","iopub.status.idle":"2025-12-19T12:00:17.970440Z","shell.execute_reply.started":"2025-12-19T12:00:11.943842Z","shell.execute_reply":"2025-12-19T12:00:17.969809Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Defining the train,test and model directories\n\n* We will create the directories for train,test and model training paths if not present","metadata":{}},{"cell_type":"code","source":"DATA_DIR = \"../input/state-farm-distracted-driver-detection/imgs\"\nTEST_DIR = os.path.join(DATA_DIR,\"test\")\nTRAIN_DIR = os.path.join(DATA_DIR,\"train\")\n\nCSV_DIR = os.path.join(os.getcwd(),\"csv_files\")\n\nMODEL_PATH = os.path.join(os.getcwd(),\"model\",\"vgg16\")\nPICKLE_PATH = os.path.join(os.getcwd(),\"pickle\")\nTEST_CSV = os.path.join(os.getcwd(),\"csv_files\",\"test.csv\")\nTRAIN_CSV = os.path.join(os.getcwd(),\"csv_files\",\"train.csv\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-19T12:00:44.684664Z","iopub.execute_input":"2025-12-19T12:00:44.685002Z","iopub.status.idle":"2025-12-19T12:00:44.690403Z","shell.execute_reply.started":"2025-12-19T12:00:44.684974Z","shell.execute_reply":"2025-12-19T12:00:44.689630Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"if not os.path.exists(TEST_DIR):\n    print(\"Testing data does not exists\")\nif not os.path.exists(TRAIN_DIR):\n    print(\"Training data does not exists\")\nif not os.path.exists(MODEL_PATH):\n    print(\"Model path does not exists\")\n    os.makedirs(MODEL_PATH)\n    print(\"Model path created\")\nelse:\n    shutil.rmtree(MODEL_PATH)\n    os.makedirs(MODEL_PATH)\nif not os.path.exists(PICKLE_PATH):\n    os.makedirs(PICKLE_PATH)\nif not os.path.exists(CSV_DIR):\n    os.makedirs(CSV_DIR)\n    ","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-19T12:00:47.536688Z","iopub.execute_input":"2025-12-19T12:00:47.537027Z","iopub.status.idle":"2025-12-19T12:00:47.554312Z","shell.execute_reply.started":"2025-12-19T12:00:47.536998Z","shell.execute_reply":"2025-12-19T12:00:47.553484Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"os.listdir(os.getcwd())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-19T12:00:52.366565Z","iopub.execute_input":"2025-12-19T12:00:52.366903Z","iopub.status.idle":"2025-12-19T12:00:52.374606Z","shell.execute_reply.started":"2025-12-19T12:00:52.366873Z","shell.execute_reply":"2025-12-19T12:00:52.373753Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def create_csv(DATA_DIR,filename):\n    class_names = os.listdir(DATA_DIR)\n    data = list()\n    if(os.path.isdir(os.path.join(DATA_DIR,class_names[0]))):\n        for class_name in class_names:\n            file_names = os.listdir(os.path.join(DATA_DIR,class_name))\n            for file in file_names:\n                data.append({\n                    \"Filename\":os.path.join(DATA_DIR,class_name,file),\n                    \"ClassName\":class_name\n                })\n    else:\n        class_name = \"test\"\n        file_names = os.listdir(DATA_DIR)\n        for file in file_names:\n            data.append(({\n                \"FileName\":os.path.join(DATA_DIR,file),\n                \"ClassName\":class_name\n            }))\n    data = pd.DataFrame(data)\n    data.to_csv(os.path.join(os.getcwd(),\"csv_files\",filename),index=False)\n\ncreate_csv(TRAIN_DIR,\"train.csv\")\ncreate_csv(TEST_DIR,\"test.csv\")\ndata_train = pd.read_csv(os.path.join(os.getcwd(),\"csv_files\",\"train.csv\"))\ndata_test = pd.read_csv(os.path.join(os.getcwd(),\"csv_files\",\"test.csv\"))\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-19T12:00:55.915943Z","iopub.execute_input":"2025-12-19T12:00:55.916283Z","iopub.status.idle":"2025-12-19T12:00:57.802775Z","shell.execute_reply.started":"2025-12-19T12:00:55.916256Z","shell.execute_reply":"2025-12-19T12:00:57.802148Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"data_train = pd.read_csv(TRAIN_CSV)\ndata_test = pd.read_csv(TEST_CSV)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-19T12:01:11.158930Z","iopub.execute_input":"2025-12-19T12:01:11.159218Z","iopub.status.idle":"2025-12-19T12:01:11.280104Z","shell.execute_reply.started":"2025-12-19T12:01:11.159194Z","shell.execute_reply":"2025-12-19T12:01:11.279489Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"labels_list = list(set(data_train['ClassName'].values.tolist()))\nlabels_id = {label_name:id for id,label_name in enumerate(labels_list)}\nprint(labels_id)\ndata_train['ClassName'].replace(labels_id,inplace=True)\n\nlabels = to_categorical(data_train['ClassName'])\nprint(labels.shape)\n\nwith open(os.path.join(PICKLE_PATH,\"labels_list_vgg16.pkl\"),\"wb\") as handle:\n    pickle.dump(labels_id,handle)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-19T12:01:14.470072Z","iopub.execute_input":"2025-12-19T12:01:14.470369Z","iopub.status.idle":"2025-12-19T12:01:14.500817Z","shell.execute_reply.started":"2025-12-19T12:01:14.470345Z","shell.execute_reply":"2025-12-19T12:01:14.500040Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Data Preparation\n\n1. Converting the all the train and test images into image size of 64,64,3 \n2. Standardizing the flattened image vector ","metadata":{}},{"cell_type":"code","source":"xtrain,xtest,ytrain,ytest = train_test_split(data_train.iloc[:,0],labels,test_size = 0.2,random_state=42)\ndef path_to_tensor(img_path):\n    # loads RGB image as PIL.Image.Image type\n    img = image.load_img(img_path, target_size=(64, 64))\n    # convert PIL.Image.Image type to 3D tensor with shape (64, 64, 3)\n    x = image.img_to_array(img)\n    # convert 3D tensor to 4D tensor with shape (1, 64, 64, 3) and return 4D tensor\n    return np.expand_dims(x, axis=0)\n\ndef paths_to_tensor(img_paths):\n    list_of_tensors = [path_to_tensor(img_path) for img_path in tqdm(img_paths)]\n    return np.vstack(list_of_tensors)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-19T12:01:25.651041Z","iopub.execute_input":"2025-12-19T12:01:25.651322Z","iopub.status.idle":"2025-12-19T12:01:25.663392Z","shell.execute_reply.started":"2025-12-19T12:01:25.651299Z","shell.execute_reply":"2025-12-19T12:01:25.662771Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ImageFile.LOAD_TRUNCATED_IMAGES = True                 \n# pre-process the data for Keras\ntrain_tensors = paths_to_tensor(xtrain).astype('float32')/255 - 0.5\nvalid_tensors = paths_to_tensor(xtest).astype('float32')/255 - 0.5","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-19T12:01:28.368570Z","iopub.execute_input":"2025-12-19T12:01:28.368898Z","iopub.status.idle":"2025-12-19T12:06:13.157638Z","shell.execute_reply.started":"2025-12-19T12:01:28.368867Z","shell.execute_reply":"2025-12-19T12:06:13.157023Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# MODEL ARCHITECTURE\n\n## Approach Used\n1. Removing the top layer of VGG16 model\n2. Using the n-1 layers of VGG16 to predict the last layer of it using the flattened image vector \n3. The last layer thus achieved is a dense feature representation for a particular image\n4. Passing this layer feature through a GlobalAveragePooling Layer and a further dense softmax layer for each of 10 classes\n\n## Benefits\n\n1. Making CNN architecture from scratch involves in training of all the deep layers which results in slow training\n2. Instead of a large sparse image vector a dense feature representation used here requires less memory while training","metadata":{}},{"cell_type":"code","source":"model = VGG16(include_top=False)\nmodel.summary()","metadata":{"scrolled":true,"trusted":true,"execution":{"iopub.status.busy":"2025-12-19T12:19:24.796200Z","iopub.execute_input":"2025-12-19T12:19:24.796501Z","iopub.status.idle":"2025-12-19T12:19:30.291367Z","shell.execute_reply.started":"2025-12-19T12:19:24.796476Z","shell.execute_reply":"2025-12-19T12:19:30.290500Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_vgg16 = model.predict(train_tensors,verbose=1)\nvalid_vgg16 = model.predict(valid_tensors,verbose=1)","metadata":{"scrolled":true,"trusted":true,"execution":{"iopub.status.busy":"2025-12-19T12:19:31.751563Z","iopub.execute_input":"2025-12-19T12:19:31.751881Z","iopub.status.idle":"2025-12-19T12:19:41.993755Z","shell.execute_reply.started":"2025-12-19T12:19:31.751852Z","shell.execute_reply":"2025-12-19T12:19:41.993118Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(\"Train shape\",train_vgg16.shape)\nprint(\"Validation shape\",valid_vgg16.shape)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-19T12:19:45.498173Z","iopub.execute_input":"2025-12-19T12:19:45.498459Z","iopub.status.idle":"2025-12-19T12:19:45.502529Z","shell.execute_reply.started":"2025-12-19T12:19:45.498435Z","shell.execute_reply":"2025-12-19T12:19:45.501762Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_features = train_vgg16[0]\nvalid_features = valid_vgg16[0]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-19T12:19:51.247763Z","iopub.execute_input":"2025-12-19T12:19:51.248048Z","iopub.status.idle":"2025-12-19T12:19:51.251606Z","shell.execute_reply.started":"2025-12-19T12:19:51.248023Z","shell.execute_reply":"2025-12-19T12:19:51.250877Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"print(\"Train features shape\",train_features.shape)\nprint(\"Validation features shape\",valid_features.shape)","metadata":{"scrolled":true,"trusted":true,"execution":{"iopub.status.busy":"2025-12-19T12:19:54.049562Z","iopub.execute_input":"2025-12-19T12:19:54.049889Z","iopub.status.idle":"2025-12-19T12:19:54.054244Z","shell.execute_reply.started":"2025-12-19T12:19:54.049856Z","shell.execute_reply":"2025-12-19T12:19:54.053532Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"VGG16_model = Sequential()\nVGG16_model.add(GlobalAveragePooling2D(input_shape=train_features.shape))\nVGG16_model.add(Dense(10, activation='softmax', kernel_initializer='glorot_normal'))\n\nVGG16_model.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-19T12:19:57.649597Z","iopub.execute_input":"2025-12-19T12:19:57.649912Z","iopub.status.idle":"2025-12-19T12:19:57.672337Z","shell.execute_reply.started":"2025-12-19T12:19:57.649885Z","shell.execute_reply":"2025-12-19T12:19:57.671603Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"VGG16_model.compile(loss='categorical_crossentropy', optimizer='rmsprop', metrics=['accuracy'])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-19T12:20:02.278941Z","iopub.execute_input":"2025-12-19T12:20:02.279226Z","iopub.status.idle":"2025-12-19T12:20:02.291226Z","shell.execute_reply.started":"2025-12-19T12:20:02.279200Z","shell.execute_reply":"2025-12-19T12:20:02.290623Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plot_model(VGG16_model,to_file=os.path.join(os.getcwd(),\"model\",\"vgg16\",\"model_distracted_driver_vgg16.png\"),show_shapes=True,show_layer_names=True)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-19T12:20:05.900156Z","iopub.execute_input":"2025-12-19T12:20:05.900436Z","iopub.status.idle":"2025-12-19T12:20:06.481788Z","shell.execute_reply.started":"2025-12-19T12:20:05.900412Z","shell.execute_reply":"2025-12-19T12:20:06.480851Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"filepath = os.path.join(MODEL_PATH,\"distracted-{epoch:02d}-{val_accuracy:.2f}.hdf5\")\ncheckpoint = ModelCheckpoint(filepath, monitor='val_accuracy', verbose=1, save_best_only=True, mode='max',period=1)\ncallbacks_list = [checkpoint]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-19T12:20:12.562735Z","iopub.execute_input":"2025-12-19T12:20:12.563052Z","iopub.status.idle":"2025-12-19T12:20:12.567007Z","shell.execute_reply.started":"2025-12-19T12:20:12.563023Z","shell.execute_reply":"2025-12-19T12:20:12.566149Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model_history = VGG16_model.fit(train_vgg16,ytrain,validation_data = (valid_vgg16, ytest),epochs=400, batch_size=16, shuffle=True,callbacks=callbacks_list)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-19T12:20:15.211661Z","iopub.execute_input":"2025-12-19T12:20:15.212016Z","iopub.status.idle":"2025-12-19T12:35:11.836633Z","shell.execute_reply.started":"2025-12-19T12:20:15.211984Z","shell.execute_reply":"2025-12-19T12:35:11.835838Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(12, 12))\nax1.plot(model_history.history['loss'], color='b', label=\"Training loss\")\nax1.plot(model_history.history['val_loss'], color='r', label=\"validation loss\")\nax1.set_xticks(np.arange(1, 400, 1))\nax1.set_yticks(np.arange(0, 1, 0.1))\n\nax2.plot(model_history.history['accuracy'], color='b', label=\"Training accuracy\")\nax2.plot(model_history.history['val_accuracy'], color='r',label=\"Validation accuracy\")\nax2.set_xticks(np.arange(1, 400, 1))\n\nlegend = plt.legend(loc='best', shadow=True)\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-19T12:43:02.594514Z","iopub.execute_input":"2025-12-19T12:43:02.594920Z","iopub.status.idle":"2025-12-19T12:43:11.891904Z","shell.execute_reply.started":"2025-12-19T12:43:02.594877Z","shell.execute_reply":"2025-12-19T12:43:11.890937Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Model Analysis\nFinding the Confusion matrix,Precision,Recall and F1 score to analyse the model thus created","metadata":{}},{"cell_type":"code","source":"def print_confusion_matrix(confusion_matrix, class_names, figsize = (10,7), fontsize=14):\n    df_cm = pd.DataFrame(\n        confusion_matrix, index=class_names, columns=class_names, \n    )\n    fig = plt.figure(figsize=figsize)\n    try:\n        heatmap = sns.heatmap(df_cm, annot=True, fmt=\"d\")\n    except ValueError:\n        raise ValueError(\"Confusion matrix values must be integers.\")\n    heatmap.yaxis.set_ticklabels(heatmap.yaxis.get_ticklabels(), rotation=0, ha='right', fontsize=fontsize)\n    heatmap.xaxis.set_ticklabels(heatmap.xaxis.get_ticklabels(), rotation=45, ha='right', fontsize=fontsize)\n    plt.ylabel('True label')\n    plt.xlabel('Predicted label')\n    fig.savefig(os.path.join(MODEL_PATH,\"confusion_matrix.png\"))\n    return fig","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-19T12:43:28.749134Z","iopub.execute_input":"2025-12-19T12:43:28.749449Z","iopub.status.idle":"2025-12-19T12:43:28.755322Z","shell.execute_reply.started":"2025-12-19T12:43:28.749413Z","shell.execute_reply":"2025-12-19T12:43:28.754379Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"def print_heatmap(n_labels, n_predictions, class_names):\n    labels = n_labels #sess.run(tf.argmax(n_labels, 1))\n    predictions = n_predictions #sess.run(tf.argmax(n_predictions, 1))\n\n#     confusion_matrix = sess.run(tf.contrib.metrics.confusion_matrix(labels, predictions))\n    matrix = confusion_matrix(labels.argmax(axis=1),predictions.argmax(axis=1))\n    row_sum = np.sum(matrix, axis = 1)\n    w, h = matrix.shape\n\n    c_m = np.zeros((w, h))\n\n    for i in range(h):\n        c_m[i] = matrix[i] * 100 / row_sum[i]\n\n    c = c_m.astype(dtype = np.uint8)\n\n    \n    heatmap = print_confusion_matrix(c, class_names, figsize=(18,10), fontsize=20)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-19T12:43:31.161583Z","iopub.execute_input":"2025-12-19T12:43:31.161906Z","iopub.status.idle":"2025-12-19T12:43:31.167451Z","shell.execute_reply.started":"2025-12-19T12:43:31.161878Z","shell.execute_reply":"2025-12-19T12:43:31.166513Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"class_names = list()\nfor name,idx in labels_id.items():\n    class_names.append(name)\n# print(class_names)\nypred = VGG16_model.predict(valid_vgg16,verbose=1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-19T12:43:44.815163Z","iopub.execute_input":"2025-12-19T12:43:44.815472Z","iopub.status.idle":"2025-12-19T12:43:44.992474Z","shell.execute_reply.started":"2025-12-19T12:43:44.815445Z","shell.execute_reply":"2025-12-19T12:43:44.991875Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Confusion Matrix","metadata":{}},{"cell_type":"code","source":"print_heatmap(ytest,ypred,class_names)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-19T12:43:47.165066Z","iopub.execute_input":"2025-12-19T12:43:47.165408Z","iopub.status.idle":"2025-12-19T12:43:48.024563Z","shell.execute_reply.started":"2025-12-19T12:43:47.165377Z","shell.execute_reply":"2025-12-19T12:43:48.023631Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Precision Recall F1 Score","metadata":{}},{"cell_type":"code","source":"ypred_class = np.argmax(ypred,axis=1)\n# print(ypred_class[:10])\nytest = np.argmax(ytest,axis=1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-19T12:43:51.498319Z","iopub.execute_input":"2025-12-19T12:43:51.498619Z","iopub.status.idle":"2025-12-19T12:43:51.502667Z","shell.execute_reply.started":"2025-12-19T12:43:51.498591Z","shell.execute_reply":"2025-12-19T12:43:51.501940Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"accuracy = accuracy_score(ytest,ypred_class)\nprint('Accuracy: %f' % accuracy)\n# precision tp / (tp + fp)\nprecision = precision_score(ytest, ypred_class,average='weighted')\nprint('Precision: %f' % precision)\n# recall: tp / (tp + fn)\nrecall = recall_score(ytest,ypred_class,average='weighted')\nprint('Recall: %f' % recall)\n# f1: 2 tp / (2 tp + fp + fn)\nf1 = f1_score(ytest,ypred_class,average='weighted')\nprint('F1 score: %f' % f1)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-19T12:49:48.097373Z","iopub.execute_input":"2025-12-19T12:49:48.097673Z","iopub.status.idle":"2025-12-19T12:49:48.113142Z","shell.execute_reply.started":"2025-12-19T12:49:48.097644Z","shell.execute_reply":"2025-12-19T12:49:48.112253Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"from sklearn.metrics import classification_report\n\n# ytest ve ypred_class zaten int\n# ytest = np.argmax(ytest, axis=1)\n# ypred_class = np.argmax(ypred, axis=1)\n\n# labels_id: {\"c0\":id, \"c1\":id, ...}\nid_to_label = {v:k for k,v in labels_id.items()}\ntarget_names = [id_to_label[i] for i in range(len(id_to_label))]\n\nprint(\"Classification Report:\\n\")\nprint(classification_report(\n    ytest,\n    ypred_class,\n    target_names=target_names,\n    digits=4\n))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-19T12:49:52.444231Z","iopub.execute_input":"2025-12-19T12:49:52.444547Z","iopub.status.idle":"2025-12-19T12:49:52.463469Z","shell.execute_reply.started":"2025-12-19T12:49:52.444514Z","shell.execute_reply":"2025-12-19T12:49:52.462666Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import random\nfrom keras.preprocessing import image\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\n\n# id -> label (c0..c9)\nid_to_label = {v:k for k,v in labels_id.items()}\n\n# 1) random test image\ntest_files = [f for f in os.listdir(TEST_DIR) if f.lower().endswith(('.jpg','.jpeg','.png'))]\nimg_name = random.choice(test_files)\nimg_path = os.path.join(TEST_DIR, img_name)\nprint(\"Seçilen test görseli:\", img_path)\n\n# 2) preprocess (seninle aynı)\nimg = image.load_img(img_path, target_size=(64,64))\nx = image.img_to_array(img).astype('float32')/255 - 0.5\nx = np.expand_dims(x, axis=0)\n\n# 3) VGG16 feature çıkar\nfeat = model.predict(x, verbose=0)     # model = VGG16(include_top=False)\n\n# 4) sınıf tahmini (head)\nprobs = VGG16_model.predict(feat, verbose=0)[0]\npred_id = int(np.argmax(probs))\nconf = float(np.max(probs))\npred_label = id_to_label[pred_id]\n\nprint(f\"Tahmin: {pred_label}  |  Confidence: %{conf*100:.2f}\")\n\n# 5) görüntüyü göster\nplt.figure(figsize=(4,4))\nplt.imshow(image.load_img(img_path))\nplt.axis('off')\nplt.title(f\"{pred_label} (%{conf*100:.2f})\")\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-12-19T12:55:12.259526Z","iopub.execute_input":"2025-12-19T12:55:12.259864Z","iopub.status.idle":"2025-12-19T12:55:12.495446Z","shell.execute_reply.started":"2025-12-19T12:55:12.259833Z","shell.execute_reply":"2025-12-19T12:55:12.494781Z"}},"outputs":[],"execution_count":null}]}