{"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":"from os.path import join\nfrom tensorflow.keras.applications.resnet50 import preprocess_input\nfrom tensorflow.keras.preprocessing.image import load_img, img_to_array\nfrom tensorflow.keras.applications import ResNet50\nfrom learntools.deep_learning.decode_predictions import decode_predictions\nfrom IPython.display import Image, display\nimport numpy as np\n \nimg_path = '/kaggle/input/appenzeller-photo/appenzeller.jpg'\n\nmy_model = ResNet50(weights='/kaggle/input/resnet50/resnet50_weights_tf_dim_ordering_tf_kernels.h5')\n\nimg = load_img(img_path, target_size=(224, 224))\nimg_array = img_to_array(img)\ntest_data = preprocess_input(img_array)\npreds = my_model.predict(np.array([test_data]))\n\nmost_likely_labels = decode_predictions(preds, top=1000, class_list_path='../input/resnet50/imagenet_class_index.json')\nfor i in range(999):\n    if \"Appenzeller\" in most_likely_labels[0][i][1]:\n        print(most_likely_labels[0][i][2], most_likely_labels[0][i][1])\ndisplay(Image(img_path))","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2023-06-13T09:36:21.743877Z","iopub.execute_input":"2023-06-13T09:36:21.744265Z","iopub.status.idle":"2023-06-13T09:36:26.095466Z","shell.execute_reply.started":"2023-06-13T09:36:21.744225Z","shell.execute_reply":"2023-06-13T09:36:26.094330Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Task 2. Day/Night","metadata":{}},{"cell_type":"code","source":"import torch\nfrom torchvision.datasets import ImageFolder\nfrom torch.utils.data import DataLoader, Subset\n\nfrom torchvision import transforms\nfrom torchvision.models import resnet18 as resnet\nfrom torchvision.models import ResNet18_Weights as resnet_weights\n\nfrom tqdm import tqdm\n\nfrom torch.optim import AdamW\nfrom torch.nn import MSELoss\n\nimport numpy as np\n# from torchvision import datasets\n\nfrom matplotlib import pyplot as plt\n","metadata":{"execution":{"iopub.status.busy":"2023-06-13T09:34:17.853810Z","iopub.execute_input":"2023-06-13T09:34:17.854182Z","iopub.status.idle":"2023-06-13T09:34:17.862737Z","shell.execute_reply.started":"2023-06-13T09:34:17.854150Z","shell.execute_reply":"2023-06-13T09:34:17.860142Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"weights = resnet_weights.IMAGENET1K_V1\n\npreprocess = weights.transforms()\ndataset = ImageFolder(root=\"/kaggle/input/from-git/Day-Night-Classifier-master/day_night_dataset/train\")\ntrain_dataset, test_dataset = torch.utils.data.random_split(dataset, (0.7, 0.3))","metadata":{"execution":{"iopub.status.busy":"2023-06-13T09:34:17.867264Z","iopub.execute_input":"2023-06-13T09:34:17.867594Z","iopub.status.idle":"2023-06-13T09:34:17.886161Z","shell.execute_reply.started":"2023-06-13T09:34:17.867570Z","shell.execute_reply":"2023-06-13T09:34:17.885356Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = resnet(weights=weights).train()\nmodel.fc = torch.nn.Linear(512, 1)\n\noptim = AdamW(model.fc.parameters(), lr=0.001)\nmodel = model.to('cuda')\n\nloss = MSELoss()","metadata":{"execution":{"iopub.status.busy":"2023-06-13T09:34:17.889221Z","iopub.execute_input":"2023-06-13T09:34:17.889843Z","iopub.status.idle":"2023-06-13T09:34:18.111089Z","shell.execute_reply.started":"2023-06-13T09:34:17.889813Z","shell.execute_reply":"2023-06-13T09:34:18.110163Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"iterations = 120\nbatch_size = 8\n\nfor _ in tqdm(range(iterations)):\n  idx = np.random.randint(0, len(train_dataset), batch_size)\n  imgs = []\n  labels = []\n  \n  for id in idx:\n    imgs.append(preprocess(train_dataset[id][0]))\n    labels.append(train_dataset[id][1])\n  \n  imgs = torch.stack(imgs).to('cuda')\n  labels = torch.tensor(labels, dtype=torch.float).to('cuda')\n  optim.zero_grad()\n  preds = model(imgs)\n  pred_loss = loss(preds, labels.unsqueeze(1))\n  pred_loss.backward()\n  \n  optim.step()","metadata":{"execution":{"iopub.status.busy":"2023-06-13T09:34:18.112459Z","iopub.execute_input":"2023-06-13T09:34:18.112898Z","iopub.status.idle":"2023-06-13T09:34:33.503299Z","shell.execute_reply.started":"2023-06-13T09:34:18.112866Z","shell.execute_reply":"2023-06-13T09:34:33.502353Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.eval()\ntrain_preprocess = transforms.Compose([\n    transforms.Resize(224),\n    transforms.ToTensor()\n])\nim_num = 10\ncurr_count = 0\nwith torch.no_grad():\n  for test_img, _ in test_dataset:\n    pred = model(train_preprocess(test_img).to('cuda').unsqueeze(0))\n    print(pred.item())\n    if pred > 0:\n      print('Night')\n    else:\n      print('Day')\n    plt.imshow(test_img)\n    plt.show()\n    curr_count += 1\n    if curr_count == im_num:\n      break","metadata":{"execution":{"iopub.status.busy":"2023-06-13T09:34:33.505520Z","iopub.execute_input":"2023-06-13T09:34:33.506172Z","iopub.status.idle":"2023-06-13T09:34:36.520559Z","shell.execute_reply.started":"2023-06-13T09:34:33.506134Z","shell.execute_reply":"2023-06-13T09:34:36.519641Z"},"trusted":true},"execution_count":null,"outputs":[]}]}