{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.11","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"none","dataSources":[{"sourceId":3004,"databundleVersionId":861823,"sourceType":"competition"}],"dockerImageVersionId":31040,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"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":"2025-07-02T19:56:38.505066Z","iopub.execute_input":"2025-07-02T19:56:38.505459Z","iopub.status.idle":"2025-07-02T19:56:38.515994Z","shell.execute_reply.started":"2025-07-02T19:56:38.505434Z","shell.execute_reply":"2025-07-02T19:56:38.514760Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Input, Conv2D, MaxPooling2D, Flatten, Dense, Dropout\nfrom tensorflow.keras.utils import to_categorical\nfrom sklearn.model_selection import train_test_split","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-02T20:01:19.146612Z","iopub.execute_input":"2025-07-02T20:01:19.146895Z","iopub.status.idle":"2025-07-02T20:01:19.151772Z","shell.execute_reply.started":"2025-07-02T20:01:19.146876Z","shell.execute_reply":"2025-07-02T20:01:19.150702Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Carregar os dados CSV pelo no Kaggle \ntrain_df = pd.read_csv(\"/kaggle/input/digit-recognizer/train.csv\")\ntest_df = pd.read_csv(\"/kaggle/input/digit-recognizer/test.csv\")\n\n# Separar X e y\nX = train_df.drop(\"label\", axis=1).values\ny = train_df[\"label\"].values","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-02T20:01:21.937231Z","iopub.execute_input":"2025-07-02T20:01:21.937568Z","iopub.status.idle":"2025-07-02T20:01:26.030970Z","shell.execute_reply.started":"2025-07-02T20:01:21.937536Z","shell.execute_reply":"2025-07-02T20:01:26.029834Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# 2. Pre-processamento\n# Normaliza para [0,1]\nX = X.astype(\"float32\") / 255.0\nX_test = test_df.values.astype(\"float32\") / 255.0\n\n# Redimensionamento\nX = X.reshape(-1, 28, 28, 1)\nX_test = X_test.reshape(-1, 28, 28, 1)\n\n# Definir Labels\ny_cat = to_categorical(y, num_classes=10)\n\n# Separar treino/validação\nX_train, X_val, y_train, y_val = train_test_split(X, y_cat, test_size=0.1, random_state=42)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-02T20:01:28.507595Z","iopub.execute_input":"2025-07-02T20:01:28.507911Z","iopub.status.idle":"2025-07-02T20:01:29.059644Z","shell.execute_reply.started":"2025-07-02T20:01:28.507883Z","shell.execute_reply":"2025-07-02T20:01:29.058659Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Definir o modelo CNN simples\nmodel = Sequential([\n    Input(shape=(28, 28, 1)),\n    Conv2D(32, (3,3), activation='relu'),\n    MaxPooling2D((2,2)),\n    Conv2D(64, (3,3), activation='relu'),\n    MaxPooling2D((2,2)),\n    Flatten(),\n    Dense(128, activation='relu'),\n    Dropout(0.5),\n    Dense(10, activation='softmax')\n])\n\n# Compilar o modelo\nmodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n\nmodel.summary()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-02T20:01:33.233211Z","iopub.execute_input":"2025-07-02T20:01:33.233626Z","iopub.status.idle":"2025-07-02T20:01:33.304230Z","shell.execute_reply.started":"2025-07-02T20:01:33.233587Z","shell.execute_reply":"2025-07-02T20:01:33.303418Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Treinar o modelo\nmodel.fit(X_train, y_train, epochs=10, batch_size=128, validation_data=(X_val, y_val))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-02T20:01:38.732499Z","iopub.execute_input":"2025-07-02T20:01:38.732854Z","iopub.status.idle":"2025-07-02T20:04:07.088153Z","shell.execute_reply.started":"2025-07-02T20:01:38.732828Z","shell.execute_reply":"2025-07-02T20:04:07.087447Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Fazer predições no conjunto de teste\npredictions = model.predict(X_test)\ny_pred = np.argmax(predictions, axis=1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-02T20:05:08.402377Z","iopub.execute_input":"2025-07-02T20:05:08.402713Z","iopub.status.idle":"2025-07-02T20:05:13.728894Z","shell.execute_reply.started":"2025-07-02T20:05:08.402687Z","shell.execute_reply":"2025-07-02T20:05:13.727920Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# Gerar o arquivo submission.csv\nsubmission = pd.DataFrame({\n    \"ImageId\": np.arange(1, len(y_pred)+1),\n    \"Label\": y_pred\n})\n\nsubmission.to_csv(\"submission.csv\", index=False)\nprint(\"Arquivo 'submission.csv' criado com sucesso!\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-02T20:05:24.853463Z","iopub.execute_input":"2025-07-02T20:05:24.853767Z","iopub.status.idle":"2025-07-02T20:05:24.891052Z","shell.execute_reply.started":"2025-07-02T20:05:24.853746Z","shell.execute_reply":"2025-07-02T20:05:24.889814Z"}},"outputs":[],"execution_count":null}]}