{"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\nfrom PIL import Image\nimport os\nprint(os.listdir(\"../input\"))\nfrom keras import backend as K\nK.tensorflow_backend._get_available_gpus()\n# Any results you write to the current directory are saved as output.","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"os.environ[\"CUDA_DEVICE_ORDER\"]=\"PCI_BUS_ID\"\n# The GPU id to use, usually either \"0\" or \"1\"\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"   \n","execution_count":null,"outputs":[]},{"metadata":{"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","trusted":true},"cell_type":"code","source":"ls=os.listdir('../input/dogs-vs-cats-redux-kernels-edition/train')[:5]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.preprocessing import image","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"img=image.load_img('../input/dogs-vs-cats-redux-kernels-edition/train/dog.1501.jpg',target_size=(224, 224))\nimg","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"后面会应用vgg6所以我把大小改成了244，244"},{"metadata":{"trusted":true},"cell_type":"code","source":"TRAIN_DIR='../input/dogs-vs-cats-redux-kernels-edition/train/'\nTEST_DIR = '../input/dogs-vs-cats-redux-kernels-edition/test/'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_dogs =   [TRAIN_DIR+i for i in os.listdir(TRAIN_DIR) if 'dog' in i]\ntrain_cats =   [TRAIN_DIR+i for i in os.listdir(TRAIN_DIR) if 'cat' in i]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_images =  [TEST_DIR+i for i in os.listdir(TEST_DIR)]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_images = train_dogs[:9000] + train_cats[:9000]","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"猫狗各9000个"},{"metadata":{"trusted":true},"cell_type":"code","source":"import random","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"random.shuffle(train_images)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"打乱列表元素"},{"metadata":{"trusted":true},"cell_type":"code","source":"train_images[:5]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import cv2 ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ROWS=244\nCOLS=244\nCHANNELS=3","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def read_image(file_path):\n    img = cv2.imread(file_path, cv2.IMREAD_COLOR) #cv2.IMREAD_GRAYSCALE\n    return cv2.resize(img, (ROWS, COLS), interpolation=cv2.INTER_CUBIC)\n\n\ndef prep_data(images):\n    count = len(images)\n    data = np.ndarray((count,  ROWS, COLS,CHANNELS), dtype=np.uint8)\n\n    for i, image_file in enumerate(images):\n        image = read_image(image_file)\n        data[i] = image\n        if i%1000 == 0: print('Processed {} of {}'.format(i, count))\n    \n    return data\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_images =  test_images[:25]","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"把数据用ndarry储存起来"},{"metadata":{"trusted":true},"cell_type":"code","source":"train = prep_data(train_images)\ntest = prep_data(test_images)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"Train shape: {}\".format(train.shape))\nprint(\"Test shape: {}\".format(test.shape))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import seaborn as sns\nimport matplotlib.pyplot as plt","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"labels = []\nfor i in train_images:\n    if 'dog.' in i:\n        labels.append(1)\n    else:\n        labels.append(0)\n\nsns.countplot(labels)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def show_cats_and_dogs(idx):\n    cat = read_image(train_cats[idx])\n    dog = read_image(train_dogs[idx])\n    pair = np.concatenate((cat, dog), axis=1)\n    plt.figure(figsize=(10,5))\n    plt.imshow(pair)\n    plt.show()\n    \nfor idx in range(0,5):\n    show_cats_and_dogs(idx)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"numpy这个连接函数结合plt挺厉害的"},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras import backend as k","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.applications.vgg16 import VGG16\nvgg16_weights = '../input/vgg16/vgg16_weights_tf_dim_ordering_tf_kernels.h5'\nvgg16_model = VGG16(weights=vgg16_weights,input_shape=(244,244,3))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.layers import Dense,GlobalAveragePooling1D,Dropout\n\nfrom keras.models import Model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for i in vgg16_model.layers:\n    i.trainable = False","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"x =  vgg16_model.output\nx = Dense(256, activation='relu')(x)   \nx = Dense(256, activation='relu')(x)   \nx = Dense(1, activation='sigmoid')(x)  ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = Model(inputs=vgg16_model.input, outputs=x)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import ReduceLROnPlateau, EarlyStopping\nfrom keras.optimizers import Adam,SGD","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.compile(loss='categorical_hinge', optimizer=Adam(), metrics=['binary_crossentropy'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"epochs=10\nbatch_size=50\nred =ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=10, verbose=0, mode='auto', epsilon=0.0001, cooldown=0, min_lr=0)\nearly_stopping = EarlyStopping(monitor='val_loss', patience=50, verbose=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history=model.fit(train,labels, batch_size=batch_size,epochs = epochs,verbose =1,validation_split=0.3,callbacks=[red,early_stopping])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.plot(history.history['loss'], label='train')\nplt.plot(history.history['val_loss'], label='test')\nplt.legend()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predictions=model.predict(test)[:,0]\npredictions","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig = plt.figure(figsize=(40, 40))\nfor i,j in enumerate(test):\n    str1=''\n    if predictions[i] >= 0.5: \n        str1=('I am {:.2%} sure this is a Dog'.format(predictions[i]))\n    else: \n        str1=('I am {:.2%} sure this is a Cat'.format(1-predictions[i]))\n    ax = fig.add_subplot(5, 5, i+1, xticks=[], yticks=[])    \n    plt.imshow(j)\n    ax.set_title(str1)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"不提交分数了,需要的时间太长了。。。"},{"metadata":{"trusted":true},"cell_type":"code","source":"model.save('../input/vgg_model.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"os.listdir('../input')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras.models  import load_model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"new_model = load_model(\"../input/vgg_model.h5\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"predictions=new_model.predict(test)[:,0]\npredictions","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig = plt.figure(figsize=(40, 40))\nfor i,j in enumerate(test):\n    str1=''\n    if predictions[i] >= 0.5: \n        str1=('I am {:.2%} sure this is a Dog'.format(predictions[i]))\n    else: \n        str1=('I am {:.2%} sure this is a Cat'.format(1-predictions[i]))\n    ax = fig.add_subplot(5, 5, i+1, xticks=[], yticks=[])    \n    plt.imshow(j)\n    ax.set_title(str1)","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"name":"python","version":"3.6.4","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"}},"nbformat":4,"nbformat_minor":1}