{"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":"raw","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\n'''\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n'''\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19"}},{"cell_type":"code","source":"!pip install torch torchvision timm","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np \nimport pandas as pd \nfrom matplotlib import pyplot as plt\nimport cv2\nfrom torch.utils.data import Dataset, DataLoader\nimport io\nimport os\nfrom PIL import Image\nimport os\nimport torch\nimport torchvision\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torchvision import transforms\nimport timm","metadata":{"execution":{"iopub.status.busy":"2023-04-16T14:39:45.293703Z","iopub.execute_input":"2023-04-16T14:39:45.294738Z","iopub.status.idle":"2023-04-16T14:39:45.301984Z","shell.execute_reply.started":"2023-04-16T14:39:45.294683Z","shell.execute_reply":"2023-04-16T14:39:45.300749Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def testnumber_to_filename(number):\n    filename = f\"{number:06d}.png\"\n    path = '/kaggle/input/spr-x-ray-gender/kaggle/kaggle/test/'\n    filename = path+filename\n    return filename","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df = pd.read_csv('/kaggle/input/spr-x-ray-gender/sample_submission_gender.csv')","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df['filepath'] = test_df['imageId'].apply(testnumber_to_filename)","metadata":{"execution":{"iopub.status.busy":"2023-04-16T14:39:46.758654Z","iopub.execute_input":"2023-04-16T14:39:46.759744Z","iopub.status.idle":"2023-04-16T14:39:46.777521Z","shell.execute_reply.started":"2023-04-16T14:39:46.759701Z","shell.execute_reply":"2023-04-16T14:39:46.776472Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_x= test_df['filepath'].tolist()\ntest_y = test_df['gender'].tolist()","metadata":{"execution":{"iopub.status.busy":"2023-04-16T14:39:46.778972Z","iopub.execute_input":"2023-04-16T14:39:46.779485Z","iopub.status.idle":"2023-04-16T14:39:46.785596Z","shell.execute_reply.started":"2023-04-16T14:39:46.779442Z","shell.execute_reply":"2023-04-16T14:39:46.784537Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"label2id = {}\nid2label = {}\nlabel2id['0'] = str(0)\nid2label[str(0)] ='0'\n\nlabel2id['1'] = str(1)\nid2label[str(1)] ='1'\n","metadata":{"execution":{"iopub.status.busy":"2023-04-16T14:39:46.797898Z","iopub.execute_input":"2023-04-16T14:39:46.799003Z","iopub.status.idle":"2023-04-16T14:39:46.806234Z","shell.execute_reply.started":"2023-04-16T14:39:46.798940Z","shell.execute_reply":"2023-04-16T14:39:46.805300Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class SPRXrayGenderDataset(torch.utils.data.Dataset):\n    def __init__(self, image_files, labels,transforms):\n        self.image_files = image_files\n        self.labels = labels\n        self.transforms = transforms\n        \n    def __len__(self):\n        return len(self.image_files)\n\n    def __getitem__(self, index):\n        image_filepath = self.image_files[index]\n        image = cv2.imread(image_filepath)\n        image = Image.fromarray(image)\n    \n        return self.transforms(image), self.labels[index]\n\n\n","metadata":{"execution":{"iopub.status.busy":"2023-04-16T14:39:46.817720Z","iopub.execute_input":"2023-04-16T14:39:46.818531Z","iopub.status.idle":"2023-04-16T14:39:46.830153Z","shell.execute_reply.started":"2023-04-16T14:39:46.818480Z","shell.execute_reply":"2023-04-16T14:39:46.828812Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n\n\nnum_classes = 2  # Number of classes in your dataset\nbatch_size = 8\nimage_size = 384\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\nefficientnet = timm.create_model('efficientnet_b4', pretrained=False, num_classes=num_classes, in_chans=3)\nefficientnet.load_state_dict(torch.load('/kaggle/input/sprgenderpredicitioneffnetb4/efficientnet_image_classifier.pth'))\nefficientnet.eval()\nefficientnet.to(device)\n# Set device\n\nefficientnet.to(device)\n\n\n\n\ntest_transforms = transforms.Compose([\n    transforms.Resize((image_size, image_size)),\n    transforms.ToTensor(),\n    transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n])\n\n","metadata":{"execution":{"iopub.status.busy":"2023-04-16T14:39:46.834396Z","iopub.execute_input":"2023-04-16T14:39:46.834707Z","iopub.status.idle":"2023-04-16T14:39:46.844096Z","shell.execute_reply.started":"2023-04-16T14:39:46.834681Z","shell.execute_reply":"2023-04-16T14:39:46.843128Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_dataset = SPRXrayGenderDataset(test_x, test_y,test_transforms)\ntest_loader = DataLoader(test_dataset, batch_size=batch_size, shuffle=False, num_workers=2)\n\n\nefficientnet.eval()\nfilenames=[]\nfinalpredictions=[]\nfor inputs, files in test_loader:\n                #print(inputs)\n                #print(files)\n                inputs = inputs.to(device)\n                outputs = efficientnet(inputs)\n                _, preds = torch.max(outputs, 1)\n                finalpred=[]\n                for file in files:\n                    filenames.append(file)\n                for pred in preds:\n                    finalpredictions.append(id2label[str(pred.item())])\n                #print(finalpred)\n                ","metadata":{"execution":{"iopub.status.busy":"2023-04-16T14:45:19.091231Z","iopub.execute_input":"2023-04-16T14:45:19.092566Z","iopub.status.idle":"2023-04-16T14:50:39.734515Z","shell.execute_reply.started":"2023-04-16T14:45:19.092515Z","shell.execute_reply":"2023-04-16T14:50:39.733154Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n            \ntest_df['gender']=finalpredictions","metadata":{"execution":{"iopub.status.busy":"2023-04-16T14:50:39.736815Z","iopub.execute_input":"2023-04-16T14:50:39.737449Z","iopub.status.idle":"2023-04-16T14:50:39.750268Z","shell.execute_reply.started":"2023-04-16T14:50:39.737401Z","shell.execute_reply":"2023-04-16T14:50:39.748967Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df[['imageId', 'gender']].to_csv(\"submission.csv\", index=False)","metadata":{"execution":{"iopub.status.busy":"2023-04-16T14:50:39.753106Z","iopub.execute_input":"2023-04-16T14:50:39.754486Z","iopub.status.idle":"2023-04-16T14:50:39.791797Z","shell.execute_reply.started":"2023-04-16T14:50:39.754447Z","shell.execute_reply":"2023-04-16T14:50:39.790693Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df.head(10)","metadata":{"execution":{"iopub.status.busy":"2023-04-16T14:51:28.539151Z","iopub.execute_input":"2023-04-16T14:51:28.539711Z","iopub.status.idle":"2023-04-16T14:51:28.556391Z","shell.execute_reply.started":"2023-04-16T14:51:28.539672Z","shell.execute_reply":"2023-04-16T14:51:28.554965Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}