{"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\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 5GB 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","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd \nfrom keras.preprocessing.image import ImageDataGenerator, load_img\nfrom keras.utils import to_categorical\nfrom sklearn.model_selection import train_test_split\nimport matplotlib.pyplot as plt\nimport random\nimport os\nprint(os.listdir('../input/dogs-vs-cats'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(os.listdir('./'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!unzip ../input/dogs-vs-cats/train.zip","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(os.listdir('./'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!unzip ../input/dogs-vs-cats/test1.zip","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(os.listdir('./train'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"## 将猫的图片放到一个train/cats 文件夹下。\n## 将狗的图片放到一个train/dogs 文件夹下。\n\nroot_path = './train'\ntrain_cats_path = os.path.join(root_path,'cats')\ntrain_dogs_path = os.path.join(root_path,'dogs')\n\nif not os.path.exists(train_cats_path):\n    os.mkdir(train_cats_path)\nif not os.path.exists(train_dogs_path):\n    os.mkdir(train_dogs_path)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import shutil  #用于拷贝文件。\nimport glob # 用于列出特定文件地址。\n\nlist_cat_path = glob.glob(root_path+'/cat.*.jpg')\nlist_dog_path = glob.glob(root_path+'/dog.*.jpg')\nlen(list_cat_path)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"len(list_dog_path)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"## 总共12500 张猫和狗的图像。\n# 然后将他们分别拷贝到特定文件夹小。\nfor cat_path in list_cat_path:\n    src = cat_path\n    dst = train_cats_path\n    \n    shutil.move(src,dst)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for dog_path in list_dog_path:\n    src = dog_path\n    dst = train_dogs_path\n#     if not os.path.exists(dst):\n    shutil.move(src,dst)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"## 对测试集进行同样的操作。\nroot_test_path = './test1'\ntest_cats_path = os.path.join(root_test_path,'cats')\ntest_dogs_path = os.path.join(root_test_path,'dogs')\nif not os.path.exists(test_cats_path):\n    os.mkdir(test_cats_path)\nif not os.path.exists(test_dogs_path):\n    os.mkdir(test_dogs_path)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# 进行移动\nlist_path_test_dogs = glob.glob(root_test_path+'/dog.*.jpg')\nlist_path_test_cats = glob.glob(root_test_path+'/cat.*.jpg')\n\nfor dog_path in list_path_test_dogs:\n    src = dog_path\n    dst = test_dogs_path\n    shutil.move(src,dst)\nfor cat_path in list_path_test_cats:\n    src = cat_path\n    dst = test_cats_path\n    shutil.move(src,dst)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"## 验证集。\nval_root = './val'\nif not os.path.exists(val_root):\n    os.mkdir(val_root)\npath_val_cats = os.path.join(val_root,'cats')\npath_val_dogs = os.path.join(val_root,'dogs')\n\nif not os.path.exists(path_val_cats):\n    os.mkdir(path_val_cats)\nif not os.path.exists(path_val_dogs):\n    os.mkdir(path_val_dogs)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"list_cat_path[-2:]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"len(list_dog_path)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# 一部分训练集的图片移动到验证集中。\n# 移动2500张图片分别到猫狗文件夹中。list_cat_path的最后2500张，和list_dog_path的最后2500张。\n# train_cats_path and train_dogs_path文件夹下的最后2500张图片。\n\nlist1 = glob.glob(train_cats_path+'/cat.*.jpg')\nlist2 = glob.glob(train_dogs_path+'/dog.*.jpg')\n\n\nfor path in list1[-2500:]:\n    src = path\n    dst = path_val_cats\n    \n    shutil.move(src,dst)\n    \nfor path in list2[-2500:]:\n    src = path\n    dst = path_val_dogs\n   \n    shutil.move(src,dst)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x =os.listdir(path_val_cats)\nlen(x)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"## 运用keras 的imagegeneator来生成训练数据。\nfrom keras.preprocessing.image import ImageDataGenerator\n\ntrain_datagen = ImageDataGenerator(rescale=1.0/255,\n                                  rotation_range=40,\n                                  shear_range=0.2,\n                                  width_shift_range=0.2,\n                                  height_shift_range=0.2,\n                                  zoom_range=0.2,\n                                  horizontal_flip=True)\ntest_datagen = ImageDataGenerator(rescale=1.0/255)\n\n# 从文件夹生成数据。\n\ntrain_generator = train_datagen.flow_from_directory(root_path,\n                                                   target_size=(150,150),\n                                                   batch_size=20,\n                                                   class_mode='binary')\n\ntest_generator = test_datagen.flow_from_directory(val_root,\n                                                 target_size=(150,150),\n                                                 batch_size=20,\n                                                 class_mode='binary')\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras import models\nfrom keras import layers\n#### 用vgg16 来进行训练。\nfrom keras.applications import VGG16,ResNet50V2\nconv_base = ResNet50V2(weights='imagenet',\n                  include_top=False,\n                  input_shape=(150,150,3))\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"conv_base.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# conv_base.summary()\nfrom keras import metrics,optimizers\nmodel = models.Sequential()\nmodel.add(conv_base)\nmodel.add(layers.Flatten())\n# model.add(layers.Dropout(0.4))  #天机dropout层。\nmodel.add(layers.Dense(1024,activation='relu'))\nmodel.add(layers.Dropout(0.5))\nmodel.add(layers.Dense(512,activation='relu'))\nmodel.add(layers.Dropout(0.5))\nmodel.add(layers.Dense(1,activation='sigmoid'))\n\n# print(model.summary())\n\nconv_base.trainable = True\n\nset_trainable = False\nfor layer in conv_base.layers:  # balock5 后边的所有层都可训练。\n    if layer.name == 'conv5_block1_1_conv':   # 这里可以根据前边的baselayer 打印的出的层的名字，来选择冻结层。\n        set_trainable = True\n    if set_trainable:\n        layer.trainable = True\n    else:\n        layer.trainable = False\n        \nmodel.compile(loss='binary_crossentropy',\n              optimizer = optimizers.RMSprop(lr=1e-5),\n              metrics=['acc'])\nhistory = model.fit_generator(train_generator,\n                              steps_per_epoch=100,\n                              epochs=50,\n                              validation_data=test_generator,\n                              validation_steps=50)\n\nmodel.save('./first_cat_dogmod.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"## 画出损失和准确率的图形。\n\n#### 使曲线变得平滑。\n# 应用移动平均。\ndef smooth_curve(points, factor=0.8):\n    smoot_points = []\n    for point in points:\n        if smoot_points:\n            prev_point = smoot_points[-1]\n            temp_point = prev_point*factor + point*(1-factor)\n            smoot_points.append(temp_point)\n        else:\n            smoot_points.append(point)\n    return smoot_points\n# 画出更加平滑的曲线。\n#  训练过程的损失函数和准确率。。\nimport matplotlib.pyplot as plt\nacc = history.history['acc']\nval_acc = history.history['val_acc']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs = range(1,len(acc)+1)\nplt.plot(epochs,smooth_curve(acc),'b--',label='training acc')\nplt.plot(epochs,smooth_curve(val_acc),'b',label='validation acc')\nplt.title('trianing and validation accuracy')\nplt.legend()\nplt.grid()\nplt.figure()\nplt.plot(epochs,smooth_curve(loss),'b--',label='trainning loss')\nplt.plot(epochs,smooth_curve(val_loss),'b',label='validation loss')\nplt.title('trainning and validation loss')\nplt.grid()\nplt.legend()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import cv2\nfrom keras.preprocessing import image\ndef prepare_data(list_of_images):\n    \"\"\"\n    Returns two arrays: \n        x is an array of resized images\n        y is an array of labels\n    \"\"\"\n    x = [] # images as arrays\n    y = [] # labels\n    \n    for imagex in list_of_images:\n#         x.append(cv2.resize(cv2.imread(image), (img_width=150,img_height=150), interpolation=cv2.INTER_CUBIC))\n        img = image.load_img(imagex, target_size=(150,150))\n        imgx = image.img_to_array(img)\n        x.append(imgx)\n    for i in list_of_images:\n        if 'dog' in i:\n            y.append(1)\n        elif 'cat' in i:\n            y.append(0)\n        #else:\n            #print('neither cat nor dog name present in images')\n            \n    return x, y","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# 这里对测试集进行预测，然后提交结果。\n# test_images_dogs_cats = os.listdir('./test1')\ntest_images_dogs_cats = glob.glob('./test1'+'/*.jpg')\n\n\nX_test, Y_test = prepare_data(test_images_dogs_cats) #Y_test in this case will be []\n\ntest_datagen = ImageDataGenerator(rescale=1. / 255)\n\ntest_generator = test_datagen.flow(np.asarray(X_test), batch_size=1)\nprediction_probabilities = model.predict_generator(test_generator, verbose=1)\n\n\ncounter = range(1, len(test_images_dogs_cats) + 1)\nsolution = pd.DataFrame({\"id\": counter, \"label\":list(prediction_probabilities)})\ncols = ['label']\n\nfor col in cols:\n    solution[col] = solution[col].map(lambda x: str(x).lstrip('[').rstrip(']')).astype(float)\n\nsolution.to_csv(\"dogsVScats.csv\", index = False)\n\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"os.listdir('./test1')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","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":4}