{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.14","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":3004,"databundleVersionId":861823,"sourceType":"competition"}],"dockerImageVersionId":30804,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","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\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","trusted":true,"execution":{"iopub.status.busy":"2024-12-09T09:28:54.444499Z","iopub.execute_input":"2024-12-09T09:28:54.445063Z","iopub.status.idle":"2024-12-09T09:28:55.335148Z","shell.execute_reply.started":"2024-12-09T09:28:54.445021Z","shell.execute_reply":"2024-12-09T09:28:55.334273Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"train_df=pd.read_csv(\"/kaggle/input/digit-recognizer/train.csv\")\nsubmit_df = pd.read_csv(\"/kaggle/input/digit-recognizer/test.csv\")\nprint(train_df.info())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-09T09:28:55.336723Z","iopub.execute_input":"2024-12-09T09:28:55.337187Z","iopub.status.idle":"2024-12-09T09:28:59.746238Z","shell.execute_reply.started":"2024-12-09T09:28:55.337145Z","shell.execute_reply":"2024-12-09T09:28:59.745421Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.utils.data import Dataset,DataLoader\nclass ConvNet(nn.Module):\n    def __init__(self):\n        super(ConvNet, self).__init__()\n        self.conv1 = nn.Conv2d(in_channels=1, out_channels=128, kernel_size=5)\n        self.conv2 = nn.Conv2d(128, 64, 5)\n        self.conv3 = nn.Conv2d(64, 32, 5)\n        self.fc1 = nn.Linear(800, 512)\n        self.fc2 = nn.Linear(512, 256)\n        self.fc3 = nn.Linear(256, 128)\n        self.fc4 = nn.Linear(128, 64)\n        self.fc5 = nn.Linear(64, 32)\n        self.fc6 = nn.Linear(32, 16)\n        self.fc7 = nn.Linear(16, 10)\n \n    def forward(self, x):\n        x = F.relu(self.conv1(x))\n        x = F.relu(self.conv2(x))\n        x = F.max_pool2d(F.relu(self.conv3(x)), 3)\n        x = x.view(-1, self.num_flat_features(x))\n        x = F.relu(self.fc1(x))\n        x = F.relu(self.fc2(x))\n        x = F.relu(self.fc3(x))\n        x = F.relu(self.fc4(x))\n        x = F.relu(self.fc5(x))\n        x = F.relu(self.fc6(x))\n        x = self.fc7(x)\n        return x\n \n    def num_flat_features(self, x):\n        size = x.size()[1:]  # all dimensions except the batch dimension\n        num_features = 1\n        for s in size:\n            num_features *= s\n        return num_features\n        \nclass DigitDataSet(Dataset):\n    def __init__(self):\n        label=train_df['label']\n        data = train_df.drop('label',axis = 1)\n        self.data = data.to_numpy(dtype='float32')\n        self.label = label.to_numpy(dtype='long')\n\n    def __getitem__(self,index):\n        return self.data[index].reshape(-1,28)[None,:,:],self.label[index]\n\n    def __len__(self):\n        return len(self.data)\n\ngpu_open = True\ndataset = DigitDataSet()\ndata_loader = DataLoader(\n    dataset=dataset,\n    batch_size=256,\n    shuffle=True,  \n    num_workers=4  # 加速数据加载\n)\nnet = ConvNet()\nif torch.cuda.device_count() > 1:\n    net = nn.DataParallel(net)\nloss_function = nn.CrossEntropyLoss()\nif gpu_open:\n    net = net.cuda()\n    loss_function = loss_function.cuda()\noptimizer = optim.SGD(net.parameters(), lr=0.01)\nloop= 300\nfor epoch in range(loop):\n    loss_sum = 0\n    for input,label in data_loader:\n        if gpu_open:\n            input=input.cuda()\n            label = label.cuda()\n        optimizer.zero_grad()\n        output = net(input)\n        loss=loss_function(output,label)\n        loss.backward()\n        optimizer.step()\n        loss_sum+=loss.item()\n    print('epoch %d:%f'%(epoch+1,loss_sum/len(data_loader)))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2024-12-09T09:28:59.747451Z","iopub.execute_input":"2024-12-09T09:28:59.747778Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"submit_data=submit_df.to_numpy(dtype=\"float32\")\nsubmit_data = torch.tensor(submit_data.reshape(-1,1,28,28))\nif gpu_open:\n    submit_data = submit_data.cuda()\nnet.eval()\nwith torch.no_grad():\n    pred = net(submit_data)\n    max_values, max_indices = pred.max(dim=1)\n    result_df = pd.DataFrame({'ImageId':range(1,len(max_indices)+1),\"Label\":max_indices.cpu()})\n    print(result_df)\n    result_df.to_csv('/kaggle/working/result.csv',index=False)\n    \n    ","metadata":{"trusted":true},"outputs":[],"execution_count":null}]}