{"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":"# 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","execution":{"iopub.status.busy":"2022-05-01T05:01:56.558139Z","iopub.execute_input":"2022-05-01T05:01:56.558923Z","iopub.status.idle":"2022-05-01T05:01:56.595418Z","shell.execute_reply.started":"2022-05-01T05:01:56.558818Z","shell.execute_reply":"2022-05-01T05:01:56.59455Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import keras\nimport pandas as pd\nimport tensorflow as tf\nfrom keras.layers import Dense\nfrom keras.layers import Conv2D\nfrom keras.layers import Dropout\nfrom keras.layers import MaxPooling2D\nfrom keras.layers import Flatten\nfrom sklearn.model_selection import train_test_split\nfrom keras.callbacks import EarlyStopping\nfrom keras.layers import MaxPool2D,BatchNormalization","metadata":{"execution":{"iopub.status.busy":"2022-05-01T05:01:59.415593Z","iopub.execute_input":"2022-05-01T05:01:59.41625Z","iopub.status.idle":"2022-05-01T05:02:04.946995Z","shell.execute_reply.started":"2022-05-01T05:01:59.416213Z","shell.execute_reply":"2022-05-01T05:02:04.946193Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train = pd.read_csv(\"/kaggle/input/Kannada-MNIST/train.csv\")\nX = train.iloc[:,1:].values\ntrain_y = train.iloc[:,0].values\n\n\n#train_x, train_y = (train.drop(['label'], axis=1), train.label)\n#train_x,train_y = shuffle(train_x,train_y)\n\ntrain_x = X.reshape(X.shape[0],28,28,1).astype('float32')\ntrain_x = train_x / 255\n\ntrain_y = tf.keras.utils.to_categorical(train_y, 10)\n\ntrain_x,valid_x,train_y,valid_y = train_test_split(train_x,train_y,train_size=0.85,random_state=10)\n\n#校验集\nval = pd.read_csv(\"../input/Kannada-MNIST/Dig-MNIST.csv\")\nX = val.iloc[:,1:].values\nval_y = val.iloc[:,0].values\n\nval_x = X.reshape(X.shape[0],28,28,1).astype('float32')\nval_x = val_x / 255\n\nval_y = tf.keras.utils.to_categorical(val_y, 10)\n","metadata":{"execution":{"iopub.status.busy":"2022-05-01T05:02:07.005787Z","iopub.execute_input":"2022-05-01T05:02:07.006054Z","iopub.status.idle":"2022-05-01T05:02:12.939739Z","shell.execute_reply.started":"2022-05-01T05:02:07.006024Z","shell.execute_reply":"2022-05-01T05:02:12.938983Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 建立模型\nmodel = keras.Sequential()\n# 一层卷积\nmodel.add(Conv2D(filters=32,kernel_size=(3, 3),kernel_initializer = 'he_normal',padding='same',input_shape=(28, 28, 1),activation='relu', kernel_regularizer='l2'))\n#model.add(BatchNormalization())\n# 二层卷积\n#model.add(Conv2D(filters=32, kernel_size=(3, 3),kernel_initializer = 'he_normal', padding='same', kernel_regularizer='l2'))\n#model.add(BatchNormalization())\n\n#model.add(Conv2D(filters=64, kernel_size=(3, 3), padding='same', activation='relu'))\n\n\nmodel.add(Conv2D(filters=64, kernel_size=(3, 3), padding='same', activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.4))\n\nmodel.add(Flatten())  # 平坦层\nmodel.add(Dense(128, activation='relu'))  # 全连接层\nmodel.add(Dropout(0.4))\nmodel.add(Dense(10, activation='softmax')) # 激活函数","metadata":{"execution":{"iopub.status.busy":"2022-05-01T09:34:24.586284Z","iopub.execute_input":"2022-05-01T09:34:24.58655Z","iopub.status.idle":"2022-05-01T09:34:24.608941Z","shell.execute_reply.started":"2022-05-01T09:34:24.586521Z","shell.execute_reply":"2022-05-01T09:34:24.607947Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nmodel.compile(loss=keras.losses.CategoricalCrossentropy(),optimizer='sgd',metrics=['accuracy'])\n\nearly_stopping = EarlyStopping(monitor='val_acc', patience=2, verbose=1)\nhistory=model.fit(train_x,train_y,batch_size=200,epochs=20,verbose=1, validation_data=(val_x,val_y))","metadata":{"execution":{"iopub.status.busy":"2022-05-01T05:12:33.200073Z","iopub.execute_input":"2022-05-01T05:12:33.200487Z","iopub.status.idle":"2022-05-01T05:13:25.444383Z","shell.execute_reply.started":"2022-05-01T05:12:33.200452Z","shell.execute_reply":"2022-05-01T05:13:25.44358Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title('Model loss')\nplt.ylabel('Loss')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Test'], loc='upper left')\nplt.show()\nplt.savefig('loss.png')","metadata":{"execution":{"iopub.status.busy":"2022-05-01T05:20:02.179882Z","iopub.execute_input":"2022-05-01T05:20:02.180635Z","iopub.status.idle":"2022-05-01T05:20:02.392641Z","shell.execute_reply.started":"2022-05-01T05:20:02.180595Z","shell.execute_reply":"2022-05-01T05:20:02.39184Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.plot(history.history['accuracy'])\nplt.plot(history.history['val_accuracy'])\nplt.title('Model accuracy')\nplt.ylabel('Accuracy')\nplt.xlabel('Epoch')\nplt.legend(['Train', 'Test'], loc='upper left')\nplt.show()\nplt.savefig('acc.png')","metadata":{"execution":{"iopub.status.busy":"2022-05-01T05:18:05.581165Z","iopub.execute_input":"2022-05-01T05:18:05.581457Z","iopub.status.idle":"2022-05-01T05:18:05.789734Z","shell.execute_reply.started":"2022-05-01T05:18:05.581426Z","shell.execute_reply":"2022-05-01T05:18:05.788806Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.save('model/m1.h5')\nmodel.save_weights('model/m2.h5')","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test=pd.read_csv(\"../input/Kannada-MNIST/Dig-MNIST.csv\")\ntest_x = test.iloc[:,1:].values\ntest_y = test.iloc[:,0].values\ntest_x = test_x.reshape(test_x.shape[0],28,28,1)\ntest_x = test_x / 255\ntest_y = tf.keras.utils.to_categorical(test_y, 10)\n\nloss,accuracy=model.evaluate(test_x,test_y,verbose=1)\nprint('test score:', loss)\nprint('test accuracy:',accuracy)","metadata":{"execution":{"iopub.status.busy":"2022-05-01T03:10:12.072623Z","iopub.execute_input":"2022-05-01T03:10:12.072912Z","iopub.status.idle":"2022-05-01T03:10:14.185794Z","shell.execute_reply.started":"2022-05-01T03:10:12.07288Z","shell.execute_reply":"2022-05-01T03:10:14.184974Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test=pd.read_csv(\"../input/Kannada-MNIST/test.csv\")\ntest_x = test.iloc[:,1:].values\ntest_x = test_x.reshape(test_x.shape[0],28,28,1)\ntest_x = test_x / 255\n\nmodel = keras.models.load_model('model/m1.h5')\nans = np.argmax(model.predict(test_x ,batch_size=32), axis=1)\nans = ans.reshape(test_x.shape[0],1)\ntmp = pd.DataFrame(ans, columns=['label'])\ntmp.to_csv('submission.csv',index=True,index_label='id')","metadata":{"execution":{"iopub.status.busy":"2022-05-01T03:10:18.668559Z","iopub.execute_input":"2022-05-01T03:10:18.669116Z","iopub.status.idle":"2022-05-01T03:10:19.311598Z","shell.execute_reply.started":"2022-05-01T03:10:18.669077Z","shell.execute_reply":"2022-05-01T03:10:19.310508Z"},"trusted":true},"execution_count":null,"outputs":[]}]}