{"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 the files in the input directory\n\nimport os\nprint(os.listdir(\"../input\"))\n\n# Any results you write to the current directory are saved as output.\n\nimport matplotlib.pyplot as plt\n%matplotlib inline","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"df = pd.read_csv(\"../input/train.csv\");\ndf.info();","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"17ea49f2449b18349096b4b8a4429a1775a542f0"},"cell_type":"code","source":"df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"6682c5ac21c5023192597e62d72b1bbd8269d1ba"},"cell_type":"code","source":"df.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"1ce946de63544808ecb64e1357f5db443718b7b5"},"cell_type":"code","source":"trainX = (df.iloc[:,1:].values).astype('float32')\ntrainY = (df.iloc[:,0].values).astype('float32')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"1a0d650418534aa1625296958bef3b8f5891047f"},"cell_type":"code","source":"trainY","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"4fe433b222687908da8f556a156881ef90d31ba3"},"cell_type":"code","source":"trainX = trainX.reshape(trainX.shape[0], 28, 28)\nfor i in range(6, 9):\n    plt.subplot(330 + (i+1))\n    plt.imshow(trainX[i], cmap=plt.get_cmap('gray'))\n    plt.title(trainY[i]);","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"dda9c4eb0de9480fe811ea95abf50fad6dffbd1a"},"cell_type":"code","source":"trainX= trainX.reshape(trainX.shape[0],28,28,1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"589b062812abaa648c1de90bb494ebc2179487e0"},"cell_type":"code","source":"trainX.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"f8c6e3a7cc836f0bc4e09f9063f522a03e1db2c0"},"cell_type":"code","source":"mean_px = trainX.mean().astype(np.float32)\nstd_px = trainX.std().astype(np.float32)\n\ndef standardize(x): \n    return (x-mean_px)/std_px","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"97780a89d36fce61c2ede658865069e90fc9c1cd"},"cell_type":"code","source":"mean_px","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"7d4371ddb9f9756021818fbf2e7d38900ff5e457"},"cell_type":"code","source":"std_px","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"93ec6e0157a9a307fa117d97185a98bac394ead9"},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"694d1cf055ae58b638daf2bbb66d4afcbacadb83"},"cell_type":"code","source":"testX = pd.read_csv(\"../input/test.csv\");","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"8c3f0f4663fd493bb77ad83d1a49c0628d4ec705"},"cell_type":"code","source":"testX = testX.values.astype('float32')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"5a44fd4f9343af932c565db156b35cac8a5f5145"},"cell_type":"code","source":"testX = testX.reshape(testX.shape[0], 28, 28, 1);","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"b93c3bbb17376e308da094e421f53e3a53079fc7"},"cell_type":"code","source":"testX.shape","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"f7fb22823b102d16269f024a6a84918d0a0590a3"},"cell_type":"code","source":"from keras.utils.np_utils import to_categorical\ntrainY = to_categorical(trainY)\nnum_classes = trainY.shape[1]\nnum_classes","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"371d47dac669ac4ffa9edf6036654b2764544372"},"cell_type":"code","source":"trainY","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"5560926fcfbf9de58cd5bd5529578e4f44a71fb0"},"cell_type":"code","source":"plt.title(trainY[9])\nplt.plot(trainY[9])\nplt.xticks(range(10));","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"cab2f6883a382ab361a26e3dcf5a8520c62e65de"},"cell_type":"code","source":"# fix random seed for reproducibility\nseed = 43\nnp.random.seed(seed)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"1de699beb172d34b0692dcf459b505590863c4f6"},"cell_type":"code","source":"from keras.models import  Sequential\nfrom keras.layers.core import  Lambda , Dense, Flatten, Dropout\nfrom keras.callbacks import EarlyStopping\nfrom keras.layers import BatchNormalization, Convolution2D , MaxPooling2D","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"014841135cc47988dd434ff9582d63aab61c35cc"},"cell_type":"code","source":"model = Sequential();\nmodel.add(Lambda(standardize, input_shape=(28, 28, 1)))\nmodel.add(Flatten())\nmodel.add(Dense(10, activation='softmax'))\nprint(\"input shape \",model.input_shape)\nprint(\"output shape \",model.output_shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"4c5974206ae8ed51417ff23f2b3b7d52f624bf82"},"cell_type":"code","source":"from keras.optimizers import RMSprop\nmodel.compile(optimizer=RMSprop(lr=0.001), loss='categorical_crossentropy', metrics=['accuracy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"0e1d5355a4e015544909602ea94504d6d36e2a66"},"cell_type":"code","source":"from keras.preprocessing import image\ngen = image.ImageDataGenerator()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"3df1f5ab3dc8ca7d24983a1a0a5b90c02cc7dfae"},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\nX = trainX\nY = trainY\ntrainX, X_val, trainY, Y_val = train_test_split(trainX, trainY, test_size=0.1, random_state=42);\nbatches = gen.flow(trainX, trainY, batch_size=64)\nval_batches = gen.flow(X_val, Y_val, batch_size=64);","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"3dba0e8f805a09b51785f15ac6de8b9bfa6f7200"},"cell_type":"code","source":"history = model.fit_generator(generator=batches, steps_per_epoch=batches.n, epochs=3, validation_data=val_batches, validation_steps=val_batches.n);","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"a73d1a5e8e637e8be913f9ff6f3188a20c342891"},"cell_type":"code","source":"history_dict = history.history\nhistory_dict.keys()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"35ada0a7402111db8a3689139b0f7530eb422d86"},"cell_type":"code","source":"import matplotlib.pyplot as plt\n%matplotlib inline\nloss_values = history_dict['loss']\nval_loss_values = history_dict['val_loss']\nepochs = range(1, len(loss_values) + 1)\n\n# \"bo\" is for \"blue dot\"\nplt.plot(epochs, loss_values, 'bo')\n# b+ is for \"blue crosses\"\nplt.plot(epochs, val_loss_values, 'b+')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"540ca434b42c5d612c52d034a91b53a338e582ce"},"cell_type":"code","source":"plt.clf()   # clear figure\nacc_values = history_dict['acc']\nval_acc_values = history_dict['val_acc']\n\nplt.plot(epochs, acc_values, 'bo')\nplt.plot(epochs, val_acc_values, 'b+')\nplt.xlabel('Epochs')\nplt.ylabel('Accuracy')\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"4b7bb413122620436ae9dd52dd11f351559081ef"},"cell_type":"code","source":"def get_fc_model():\n    model = Sequential([\n        Lambda(standardize, input_shape=(28,28,1)),\n        Flatten(),\n        Dense(512, activation='relu'),\n        Dense(10, activation='softmax')\n        ])\n    model.compile(optimizer='Adam', loss='categorical_crossentropy',\n                  metrics=['accuracy'])\n    return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"0a56a488f84464a8eff61cc7f191643da0618a8c"},"cell_type":"code","source":"fc = get_fc_model()\nfc.optimizer.lr=0.01","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"a5fce741b9434917c7cbb8b95e6f565be215355c"},"cell_type":"code","source":"history=fc.fit_generator(generator=batches, steps_per_epoch=batches.n, epochs=1, \n                    validation_data=val_batches, validation_steps=val_batches.n)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"f16b8c328de2ed50c37f8756e777d990b1708f6f"},"cell_type":"code","source":"from keras.layers import Convolution2D, MaxPooling2D\nfrom keras.optimizers import Adam\n\ndef get_cnn_model():\n    model = Sequential([\n        Lambda(standardize, input_shape=(28,28,1)),\n        Convolution2D(32, (3,3), activation='relu'),\n        Convolution2D(32, (3,3), activation='relu'),\n        MaxPooling2D(),\n        Convolution2D(64, (3,3), activation='relu'),\n        Convolution2D(64, (3,3), activation='relu'),\n        MaxPooling2D(),\n        Flatten(),\n        Dense(512, activation='relu'),\n        Dense(10, activation='softmax')\n    ]);\n    model.compile(Adam(), loss='categorical_crossentropy',\n        metrics=['accuracy']);\n    return model;","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"3959b87242bc597d3078440ec7db2725bc0b10e5"},"cell_type":"code","source":"model = get_cnn_model();\nmodel.optimizer.lr=0.01;","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"68093cb21d91008a954d642555026c32f514a0a7"},"cell_type":"code","source":"history=model.fit_generator(generator=batches, steps_per_epoch=batches.n, epochs=1, \n                    validation_data=val_batches, validation_steps=val_batches.n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"238c22de7eb86b672aee61a060505bfe2e539925"},"cell_type":"code","source":"model.optimizer.lr=0.01\ngen = image.ImageDataGenerator()\nbatches = gen.flow(trainX, trainY, batch_size=64)\nhistory=model.fit_generator(generator=batches, steps_per_epoch=batches.n, epochs=3)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_uuid":"f1f620cbbe8a3faf0c82d2634b0610679039ac7a"},"cell_type":"code","source":"predictions = model.predict_classes(testX, verbose=0)\n\nsubmissions=pd.DataFrame({\"ImageId\": list(range(1,len(predictions)+1)),\n                         \"Label\": predictions})\nsubmissions.to_csv(\"DR.csv\", index=False, header=True)","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.6","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}