import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow as tf
from sklearn.model_selection import train_test_split
from tensorflow.python import keras
from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.layers import Dense, Flatten, Conv2D, Dropout
# Import Data
train = pd.read_csv("train.csv")
test = pd.read_csv("test.csv")
num_classes = 10
img_rows = img_cols = 28
def data_prep(raw):
out_y = keras.utils.to_categorical(raw.label, num_classes)
num_images = raw.shape[0]
x_as_array = raw.values[:,1:]
x_shaped_array = x_as_array.reshape(num_images, img_rows, img_cols, 1)
out_x = x_shaped_array / 255
return out_x, out_y
x_train, y_train = data_prep(train)
x_test = test.values.reshape(test.shape[0], img_rows, img_cols, 1)
model = Sequential()
model.add(Conv2D(20, kernel_size=(3, 3),
activation='relu',
input_shape=(img_rows, img_cols, 1)))
model.add(Conv2D(20, kernel_size=(3, 3), activation='relu'))
model.add(Flatten())
model.add(Dense(128, activation='relu'))
model.add(Dense(num_classes, activation='softmax'))
model.compile(loss=keras.losses.categorical_crossentropy,
optimizer='adam',
metrics=['accuracy'])
model.fit(x_train, y_train,
batch_size=128,
epochs=2,
validation_split = 0.2)
Train on 33600 samples, validate on 8400 samples Epoch 1/2 33600/33600 [==============================] - 82s 2ms/sample - loss: 0.2185 - acc: 0.9376 - val_loss: 0.0815 - val_acc: 0.9730 Epoch 2/2 33600/33600 [==============================] - 82s 2ms/sample - loss: 0.0600 - acc: 0.9822 - val_loss: 0.0567 - val_acc: 0.9829
<tensorflow.python.keras.callbacks.History at 0x24c1071c438>
preds = pd.DataFrame(model.predict(x_test))
def decode(row):
dev = []
for c in preds.columns:
dev.append(abs(1 - row[c]))
return(np.where(dev == np.amin(dev))[0][0])
output = pd.DataFrame(preds.apply(decode, axis = 1), dtype = "int", columns = ["Label"])
output.index.name = "ImageId"
output.index += 1
output.to_csv('submission.csv')
output
# arr = [2, 3, 4, 1]
# np.where(arr == np.amin(arr))[0][0]
Label | |
---|---|
ImageId | |
1 | 2 |
2 | 0 |
3 | 9 |
4 | 0 |
5 | 3 |
6 | 7 |
7 | 0 |
8 | 3 |
9 | 0 |
10 | 3 |
11 | 5 |
12 | 7 |
13 | 4 |
14 | 0 |
15 | 4 |
16 | 3 |
17 | 3 |
18 | 1 |
19 | 9 |
20 | 0 |
21 | 9 |
22 | 1 |
23 | 1 |
24 | 5 |
25 | 7 |
26 | 4 |
27 | 2 |
28 | 7 |
29 | 4 |
30 | 7 |
... | ... |
27971 | 5 |
27972 | 0 |
27973 | 4 |
27974 | 8 |
27975 | 0 |
27976 | 3 |
27977 | 6 |
27978 | 0 |
27979 | 1 |
27980 | 9 |
27981 | 3 |
27982 | 1 |
27983 | 1 |
27984 | 0 |
27985 | 4 |
27986 | 5 |
27987 | 2 |
27988 | 2 |
27989 | 9 |
27990 | 6 |
27991 | 7 |
27992 | 6 |
27993 | 1 |
27994 | 9 |
27995 | 7 |
27996 | 9 |
27997 | 7 |
27998 | 3 |
27999 | 9 |
28000 | 2 |
28000 rows × 1 columns