{"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":"2021-07-15T08:53:07.258533Z","iopub.execute_input":"2021-07-15T08:53:07.258839Z","iopub.status.idle":"2021-07-15T08:53:07.265549Z","shell.execute_reply.started":"2021-07-15T08:53:07.258815Z","shell.execute_reply":"2021-07-15T08:53:07.264695Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow","metadata":{"execution":{"iopub.status.busy":"2021-07-15T08:53:09.844123Z","iopub.execute_input":"2021-07-15T08:53:09.844515Z","iopub.status.idle":"2021-07-15T08:53:14.128187Z","shell.execute_reply.started":"2021-07-15T08:53:09.844483Z","shell.execute_reply":"2021-07-15T08:53:14.127219Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"TRAIN_BASE_DIR = \"content/train\"\nCATEGORYS = ['airplane','automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']\n\nprint(len(CATEGORYS))","metadata":{"execution":{"iopub.status.busy":"2021-07-15T08:53:15.453158Z","iopub.execute_input":"2021-07-15T08:53:15.453513Z","iopub.status.idle":"2021-07-15T08:53:15.458577Z","shell.execute_reply.started":"2021-07-15T08:53:15.453484Z","shell.execute_reply":"2021-07-15T08:53:15.457642Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install natsort","metadata":{"execution":{"iopub.status.busy":"2021-07-15T08:57:35.346509Z","iopub.execute_input":"2021-07-15T08:57:35.346854Z","iopub.status.idle":"2021-07-15T08:57:43.453018Z","shell.execute_reply.started":"2021-07-15T08:57:35.346818Z","shell.execute_reply":"2021-07-15T08:57:43.452084Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.preprocessing.image import  load_img,img_to_array,array_to_img\nfrom glob import glob\nimport csv\nfrom natsort import natsorted\nfile_dir=\"/kaggle/input/cifar-10/train.7z\"\ntrain_img = []\ntrain_label = []\nfiles = glob(file_dir + \"/*.png\")\n\ncsv_file = open(\"/kaggle/input/cifar-10/trainLabels.csv\", \"r\", encoding=\"utf_8\", errors=\"\", newline=\"\")\nlabel_read = csv.reader(csv_file, delimiter=\",\", doublequote=True, lineterminator=\"\\r\\n\", quotechar='\"', skipinitialspace=True)\nlabel_list = []\nfor row in label_read:\n    label_list.append(row)\n\nprint(label_list[1])\ni = 0\nfor file_name in natsorted(files):\n    # print(file_name)\n    img = load_img(file_name,color_mode=\"rgb\", target_size=(32,32))\n    array = img_to_array(img)\n    train_img.append(array)\n    categorys_num = CATEGORYS.index(label_list[i+1][1])\n    train_label.append(categorys_num)\n    i += 1\n\nprint(train_label[0])","metadata":{"execution":{"iopub.status.busy":"2021-07-15T09:00:05.243633Z","iopub.execute_input":"2021-07-15T09:00:05.244031Z","iopub.status.idle":"2021-07-15T09:00:05.328894Z","shell.execute_reply.started":"2021-07-15T09:00:05.243999Z","shell.execute_reply":"2021-07-15T09:00:05.326964Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom tensorflow.keras.utils import to_categorical\ntrain_img = np.array(train_img)\ntrain_label = np.array(train_label)\ntrain_img = train_img.astype('float32') / 255\ntrain_label = to_categorical(train_label,10)\n\"\"\"\nprint(type(train_img[0]))\nprint(train_img[0])\nnp_img = train_img[0]\nplt.imshow(np_img)\nplt.show()\n\"\"\"\nfor i in range(len(train_img)):\n    plt.imshow(train_img[i])\n    print(CATEGORYS[np.argmax(train_label[i])])\n    plt.show()\n    if i == 9:\n        break","metadata":{"execution":{"iopub.status.busy":"2021-07-15T09:00:51.208801Z","iopub.execute_input":"2021-07-15T09:00:51.209143Z","iopub.status.idle":"2021-07-15T09:00:51.218376Z","shell.execute_reply.started":"2021-07-15T09:00:51.209114Z","shell.execute_reply":"2021-07-15T09:00:51.217561Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.datasets import cifar10\n\n(a,b), (val_img, val_label) = cifar10.load_data()\nval_img = val_img.astype(\"float32\")/255\nval_label = to_categorical(val_label, 10)","metadata":{"execution":{"iopub.status.busy":"2021-07-15T09:01:26.902215Z","iopub.execute_input":"2021-07-15T09:01:26.90255Z","iopub.status.idle":"2021-07-15T09:01:32.846354Z","shell.execute_reply.started":"2021-07-15T09:01:26.902521Z","shell.execute_reply":"2021-07-15T09:01:32.845393Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(val_img[i])\nfor i in range(11,21):\n    plt.imshow(val_img[i])\n    print(\"label\", CATEGORYS[np.argmax(val_label[i])])\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2021-07-15T09:01:36.652857Z","iopub.execute_input":"2021-07-15T09:01:36.653232Z","iopub.status.idle":"2021-07-15T09:01:38.050702Z","shell.execute_reply.started":"2021-07-15T09:01:36.653201Z","shell.execute_reply":"2021-07-15T09:01:38.049899Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, Activation, Flatten, Dense,MaxPool2D\nfrom tensorflow.keras.optimizers import SGD\n\nmodel = Sequential()\nmodel.add(Conv2D(6, (5,5), padding='valid'))\nmodel.add(Activation('relu'))\nmodel.add(MaxPool2D())\nmodel.add(Conv2D(16, (5,5), padding='valid'))\nmodel.add(Activation('relu'))\nmodel.add(MaxPool2D())\nmodel.add(Flatten())\nmodel.add(Dense(120))\nmodel.add(Activation('relu'))\nmodel.add(Dense(84))\nmodel.add(Activation('relu'))\nmodel.add(Dense(10))\nmodel.add(Activation('softmax'))\n\nmodel.compile(loss='categorical_crossentropy', optimizer=SGD(),metrics=['accuracy'])\ninput_shape = train_img[0].shape\nprint(input_shape)\n# model.summary()\nhistory = model.fit(train_img, train_label, batch_size=16, epochs=150,verbose=1,validation_data=(val_img,val_label))\n","metadata":{"execution":{"iopub.status.busy":"2021-07-15T09:03:02.899952Z","iopub.execute_input":"2021-07-15T09:03:02.900395Z","iopub.status.idle":"2021-07-15T09:03:02.953049Z","shell.execute_reply.started":"2021-07-15T09:03:02.90035Z","shell.execute_reply":"2021-07-15T09:03:02.951462Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.plot(history.history[\"accuracy\"])\nplt.plot(history.history[\"val_accuracy\"])\nplt.title(\"Model accuracy\")\nplt.xlabel(\"epoch\")\nplt.ylabel(\"accuracy\")\nplt.legend(['Train', 'Test'], loc='upper left')\nplt.show()\n\nplt.plot(history.history[\"loss\"])\nplt.plot(history.history[\"val_loss\"])\nplt.title(\"model loss\")\nplt.xlabel(\"epoch\")\nplt.ylabel(\"loss\")\nplt.legend(['Train', 'Test'], loc='upper left')\nplt.show()","metadata":{},"execution_count":null,"outputs":[]}]}