{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"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 in \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 \"../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# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"#from keras.models import Sequential\nfrom keras import layers\nfrom keras.layers import Input, Dense, Activation, ZeroPadding2D, BatchNormalization, Flatten, Conv2D\nfrom keras.layers import AveragePooling2D, MaxPooling2D, Dropout, GlobalMaxPooling2D, GlobalAveragePooling2D\nfrom keras.models import Model\n\n# Nhung cai sau nay, minh co dung dau?\nfrom keras.preprocessing import image\nfrom keras.utils import layer_utils\nfrom keras.utils.data_utils import get_file\nfrom keras.applications.imagenet_utils import preprocess_input\nimport pydot\nfrom IPython.display import SVG\nfrom keras.utils.vis_utils import model_to_dot\nfrom keras.utils import plot_model\nfrom keras.utils.np_utils import to_categorical \n\nimport keras.backend as K\n\nK.set_image_data_format('channels_last')\n\nimport matplotlib.pyplot as plt\nfrom matplotlib.pyplot import imshow\n\n%matplotlib inline","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train = pd.read_csv('/kaggle/input/digit-recognizer/train.csv')\ntest = pd.read_csv('/kaggle/input/digit-recognizer/test.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"Y_train = train['label']\nX_train = train.drop(labels='label',axis=1)\n\n#Y_test = test['label']\n#X_test = test.drop(labels='label',axis=1)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Normalize\nX_train /= 255\ntest /= 255 # to do what?\n#X_test /= 255","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Преобразование X\nПотому что рисунка сохраняется как последовательность\nСейчас нужно преобразовать в тип рисунки и потом возможно конвертировать\n\n784px vectors to 28x28x1 3D matrices"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Reshape\nX_train = X_train.values.reshape(-1,28,28,1)\ntest = test.values.reshape(-1,28,28,1)\n\nprint(X_train.shape)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Преобразование Y поскольку  текущее значение Y 1-10, надо преобразовать на one_hot\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"# to one_hot \nY_train = to_categorical(Y_train, num_classes = 10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print (\"number of training examples = \" + str(X_train.shape[0]))\n#print (\"number of test examples = \" + str(X_test.shape[0]))\nprint (\"X_train shape: \" + str(X_train.shape))\nprint (\"Y_train shape: \" + str(Y_train.shape))\n#print (\"X_test shape: \" + str(X_test.shape))\n#print (\"Y_test shape: \" + str(Y_test.shape))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"import train"},{"metadata":{"trusted":true},"cell_type":"code","source":"random_seed = 2\nfrom sklearn.model_selection import train_test_split\nX_train, X_val, Y_train, Y_val = train_test_split(X_train, Y_train, test_size = 0.1, random_state=random_seed)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"                                  =====MODEL====="},{"metadata":{"trusted":true},"cell_type":"code","source":"# the model\n\ndef MaiHaiModel(input_shape):\n    X_input = Input(input_shape)\n    X = ZeroPadding2D((3,3))(X_input) \n    X = Conv2D(32,(7,7),strides=(1,1),name='conv0')(X)\n    X = BatchNormalization(axis=3, name='bn0')(X)\n    X = Activation('relu')(X)\n    \n    X = MaxPooling2D((2,2), name='max_pool')(X)\n    \n    X = Flatten()(X)\n    X = Dense(10, activation='softmax', name='fc')(X)\n    \n    model = Model(inputs= X_input, outputs = X, name='HapplyModel')\n    \n    return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"maihaiModel = MaiHaiModel(X_train.shape[1:]) ","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"//optimizer = adam\n//optimizer = RMSprop(lr=0.001, rho=0.9, epsilon=1e-08, decay=0.0)//\n\n\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"maihaiModel.compile(optimizer='adam',loss='categorical_crossentropy', metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"maihaiModel.fit(X_train,Y_train, epochs=1, batch_size=86)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"====Оценить====\n X_test, Y_test\n"},{"metadata":{"trusted":true},"cell_type":"code","source":"results = maihaiModel.predict(test)\n\nresults = np.argmax(results,axis = 1)\n\nresults = pd.Series(results,name=\"Label\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(results)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission = pd.concat([pd.Series(range(1,28001),name = \"ImageId\"),results],axis = 1)\n\nsubmission.to_csv(\"cnn_mnist_datagen.csv\",index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(test.shape)","execution_count":null,"outputs":[]}],"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":4,"nbformat_minor":1}