{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras import models, layers\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport zipfile\nfrom tqdm import tqdm","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-06-23T18:56:07.251123Z","iopub.execute_input":"2023-06-23T18:56:07.251914Z","iopub.status.idle":"2023-06-23T18:56:07.258917Z","shell.execute_reply.started":"2023-06-23T18:56:07.251876Z","shell.execute_reply":"2023-06-23T18:56:07.257162Z"},"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":"2023-06-23T18:56:07.261153Z","iopub.execute_input":"2023-06-23T18:56:07.261650Z","iopub.status.idle":"2023-06-23T18:56:07.275463Z","shell.execute_reply.started":"2023-06-23T18:56:07.261615Z","shell.execute_reply":"2023-06-23T18:56:07.274325Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with zipfile.ZipFile(\"../input/dogs-vs-cats/train.zip\",\"r\") as z:\n    z.extractall(\".\")\n    \nwith zipfile.ZipFile(\"../input/dogs-vs-cats/test1.zip\",\"r\") as z:\n    z.extractall(\".\")\n    \nos.listdir(\".\")","metadata":{"execution":{"iopub.status.busy":"2023-06-23T18:56:07.277038Z","iopub.execute_input":"2023-06-23T18:56:07.277782Z","iopub.status.idle":"2023-06-23T18:56:19.893523Z","shell.execute_reply.started":"2023-06-23T18:56:07.277682Z","shell.execute_reply":"2023-06-23T18:56:19.892171Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"os.mkdir('cats')\nos.mkdir('dogs')","metadata":{"execution":{"iopub.status.busy":"2023-06-23T18:56:19.896748Z","iopub.execute_input":"2023-06-23T18:56:19.897131Z","iopub.status.idle":"2023-06-23T18:56:19.901895Z","shell.execute_reply.started":"2023-06-23T18:56:19.897079Z","shell.execute_reply":"2023-06-23T18:56:19.900817Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import shutil\npath = \"train\"\n\ndirs = [each for each in os.listdir(path)]\n\nfor _ in tqdm(dirs):\n    folder = _.split(\".\")[0]\n    if folder=='cat':\n        shutil.move(path+\"/\"+_, \"cats\")\n    else:\n        shutil.move(path+\"/\"+_, \"dogs\")","metadata":{"execution":{"iopub.status.busy":"2023-06-23T18:56:19.903633Z","iopub.execute_input":"2023-06-23T18:56:19.904010Z","iopub.status.idle":"2023-06-23T18:56:21.286751Z","shell.execute_reply.started":"2023-06-23T18:56:19.903976Z","shell.execute_reply":"2023-06-23T18:56:21.285583Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"shutil.move('cats', 'train')\nshutil.move('dogs','train')","metadata":{"execution":{"iopub.status.busy":"2023-06-23T18:56:21.288484Z","iopub.execute_input":"2023-06-23T18:56:21.289146Z","iopub.status.idle":"2023-06-23T18:56:21.297282Z","shell.execute_reply.started":"2023-06-23T18:56:21.289106Z","shell.execute_reply":"2023-06-23T18:56:21.296178Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"IMAGE_SIZE=256\nBATCH_SIZE=32 #every batch 32 images\nCHANNELS=3#rgb\nEPOCHS=25","metadata":{"execution":{"iopub.status.busy":"2023-06-23T18:56:21.299372Z","iopub.execute_input":"2023-06-23T18:56:21.299728Z","iopub.status.idle":"2023-06-23T18:56:21.306799Z","shell.execute_reply.started":"2023-06-23T18:56:21.299696Z","shell.execute_reply":"2023-06-23T18:56:21.305622Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dataset=tf.keras.preprocessing.image_dataset_from_directory(\n    \"train\",\n    shuffle=True,\n    image_size=(IMAGE_SIZE,IMAGE_SIZE),\n    batch_size=BATCH_SIZE\n)","metadata":{"execution":{"iopub.status.busy":"2023-06-23T18:56:21.313447Z","iopub.execute_input":"2023-06-23T18:56:21.318077Z","iopub.status.idle":"2023-06-23T18:56:25.064349Z","shell.execute_reply.started":"2023-06-23T18:56:21.318047Z","shell.execute_reply":"2023-06-23T18:56:25.063305Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class_names=dataset.class_names\ndataset=dataset.take(int(0.1*len(dataset)))\nclass_names","metadata":{"execution":{"iopub.status.busy":"2023-06-23T18:56:25.065815Z","iopub.execute_input":"2023-06-23T18:56:25.066341Z","iopub.status.idle":"2023-06-23T18:56:25.077327Z","shell.execute_reply.started":"2023-06-23T18:56:25.066304Z","shell.execute_reply":"2023-06-23T18:56:25.076339Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_dataset_partitions(ds,shuffle=True,shuffle_size=10000):\n    size=len(ds)\n\n    if shuffle:\n        ds=ds.shuffle(shuffle_size,seed=12)\n    \n    train_ds=ds.take(int(size*0.8)) # 0 -> 0.8\n    # skip means 0.8 -> 1\n    t=(ds.skip(int(size*0.8)))\n    test_ds=t.take(int(0.5*len(t)))\n\n    \n    val_ds=t.skip(int(0.5*len(t)))\n\n    return train_ds,test_ds,val_ds","metadata":{"execution":{"iopub.status.busy":"2023-06-23T18:56:25.081618Z","iopub.execute_input":"2023-06-23T18:56:25.082235Z","iopub.status.idle":"2023-06-23T18:56:25.092141Z","shell.execute_reply.started":"2023-06-23T18:56:25.082198Z","shell.execute_reply":"2023-06-23T18:56:25.091036Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_ds,test_ds,val_ds=get_dataset_partitions(dataset)\n\n","metadata":{"execution":{"iopub.status.busy":"2023-06-23T18:56:25.093514Z","iopub.execute_input":"2023-06-23T18:56:25.094161Z","iopub.status.idle":"2023-06-23T18:56:25.240239Z","shell.execute_reply.started":"2023-06-23T18:56:25.094125Z","shell.execute_reply":"2023-06-23T18:56:25.239144Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_ds=train_ds.cache().shuffle(1000).prefetch(buffer_size=tf.data.AUTOTUNE)\nval_ds=val_ds.cache().shuffle(1000).prefetch(buffer_size=tf.data.AUTOTUNE)\ntest_ds=test_ds.cache().shuffle(1000).prefetch(buffer_size=tf.data.AUTOTUNE)","metadata":{"execution":{"iopub.status.busy":"2023-06-23T18:56:25.241730Z","iopub.execute_input":"2023-06-23T18:56:25.242427Z","iopub.status.idle":"2023-06-23T18:56:25.254338Z","shell.execute_reply.started":"2023-06-23T18:56:25.242391Z","shell.execute_reply":"2023-06-23T18:56:25.253218Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"resize_and_rescale=tf.keras.Sequential([\n    layers.experimental.preprocessing.Resizing(IMAGE_SIZE,IMAGE_SIZE),\n    layers.experimental.preprocessing.Rescaling(1.0/255)\n    \n])\n","metadata":{"execution":{"iopub.status.busy":"2023-06-23T18:56:25.256328Z","iopub.execute_input":"2023-06-23T18:56:25.256731Z","iopub.status.idle":"2023-06-23T18:56:25.268706Z","shell.execute_reply.started":"2023-06-23T18:56:25.256696Z","shell.execute_reply":"2023-06-23T18:56:25.267686Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data_augmentation = tf.keras.Sequential([\n    layers.experimental.preprocessing.RandomFlip(\"horizontal_and_vertical\"),\n    layers.experimental.preprocessing.RandomRotation(0.2)\n])","metadata":{"execution":{"iopub.status.busy":"2023-06-23T18:56:25.270401Z","iopub.execute_input":"2023-06-23T18:56:25.270758Z","iopub.status.idle":"2023-06-23T18:56:25.282807Z","shell.execute_reply.started":"2023-06-23T18:56:25.270725Z","shell.execute_reply":"2023-06-23T18:56:25.281801Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"input_shape=(BATCH_SIZE,IMAGE_SIZE,IMAGE_SIZE,CHANNELS)\nn_classes=3;\nmodel=models.Sequential([\n    resize_and_rescale,\n    data_augmentation,\n    layers.Conv2D(32, (3,3), activation = 'relu', input_shape = input_shape),\n    layers.MaxPooling2D((2,2)),\n    layers.Conv2D(64, kernel_size = (3,3), activation='relu'),\n    layers.MaxPooling2D((2,2)),\n    layers.Conv2D(64, kernel_size = (3,3), activation='relu'),\n    layers.MaxPooling2D((2,2)),\n    layers.MaxPooling2D((2,2)),\n    layers.Flatten(),\n    layers.Dense(128, activation='relu'),\n    layers.Dense(n_classes, activation='softmax')\n\n])\nmodel.build(input_shape=input_shape);","metadata":{"execution":{"iopub.status.busy":"2023-06-23T18:56:25.284380Z","iopub.execute_input":"2023-06-23T18:56:25.285044Z","iopub.status.idle":"2023-06-23T18:56:25.629894Z","shell.execute_reply.started":"2023-06-23T18:56:25.285010Z","shell.execute_reply":"2023-06-23T18:56:25.628803Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(\n    optimizer='adam',\n    loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False),\n    metrics=['accuracy']\n)","metadata":{"execution":{"iopub.status.busy":"2023-06-23T18:56:25.631355Z","iopub.execute_input":"2023-06-23T18:56:25.631810Z","iopub.status.idle":"2023-06-23T18:56:25.647687Z","shell.execute_reply.started":"2023-06-23T18:56:25.631775Z","shell.execute_reply":"2023-06-23T18:56:25.646061Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":" history = model.fit(\n        train_ds,\n        epochs=EPOCHS,\n        batch_size=BATCH_SIZE,\n        verbose=1,\n        validation_data=val_ds\n    )","metadata":{"execution":{"iopub.status.busy":"2023-06-23T18:56:25.651108Z","iopub.execute_input":"2023-06-23T18:56:25.651989Z","iopub.status.idle":"2023-06-23T18:59:04.868544Z","shell.execute_reply.started":"2023-06-23T18:56:25.651956Z","shell.execute_reply":"2023-06-23T18:59:04.867459Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"row=list()\nclass_names = {0: \"Cat\", 1: \"Dog\"}","metadata":{"execution":{"iopub.status.busy":"2023-06-23T18:59:04.872892Z","iopub.execute_input":"2023-06-23T18:59:04.873220Z","iopub.status.idle":"2023-06-23T18:59:04.879807Z","shell.execute_reply.started":"2023-06-23T18:59:04.873193Z","shell.execute_reply":"2023-06-23T18:59:04.878519Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"directory = \"test1\"\n\n#fig, axs = plt.subplots(20, 10, figsize=(16, 32))\n\n#i = 1\nfor i in tqdm(range(1000)):\n    filename=str(i+1)+\".jpg\"\n    image_path = os.path.join(directory, filename)\n    img = plt.imread(image_path)\n\n    #row = i // 10\n    #col = i % 10\n\n    #ax = axs[row, col]\n\n    img1 = tf.image.resize(img, (256, 256))\n    img_array = tf.keras.preprocessing.image.img_to_array(img1)\n    img_array = tf.expand_dims(img_array, 0)\n\n    predictions = model.predict(img_array,verbose=0)\n\n    animal_class= np.argmax(predictions[0])\n    predicted_class = class_names[animal_class]\n\n    row.append([int(filename.split(\".\")[0]), animal_class])\n\n    #confidence = round(100 * np.max(predictions[0]), 2)\n    #ax.set_title(f\"Predicted: {predicted_class}\\nConfidence: {confidence}%\", fontsize=8)\n    #ax.imshow(img)\n    #ax.axis(\"off\")\n    #i += 1\n\nrow.sort()\n\n#plt.tight_layout()\n#plt.show()\n","metadata":{"execution":{"iopub.status.busy":"2023-06-23T18:59:04.881546Z","iopub.execute_input":"2023-06-23T18:59:04.882192Z","iopub.status.idle":"2023-06-23T19:00:13.568770Z","shell.execute_reply.started":"2023-06-23T18:59:04.882156Z","shell.execute_reply":"2023-06-23T19:00:13.567742Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import csv\n\ncsv_file = 'submission.csv'\n\nwith open(csv_file, 'w', newline='') as file:\n    # Create a CSV writer object\n    writer = csv.writer(file)\n\n    # Write the column names to the CSV file\n    writer.writerow(['id', 'label'])\n\n    # Write the data to the CSV file\n    writer.writerows(row)","metadata":{"execution":{"iopub.status.busy":"2023-06-23T19:00:13.570414Z","iopub.execute_input":"2023-06-23T19:00:13.570791Z","iopub.status.idle":"2023-06-23T19:00:13.581691Z","shell.execute_reply.started":"2023-06-23T19:00:13.570756Z","shell.execute_reply":"2023-06-23T19:00:13.580754Z"},"trusted":true},"execution_count":null,"outputs":[]}]}