• 吴裕雄--天生自然神经网络与深度学习实战Python+Keras+TensorFlow:构造一个识别猫、狗图片的卷积网络


    import os
    base_dir = '/Users/apple/Documents/cat-and-dog'
    train_cats_dir = os.path.join(base_dir, 'training_set/cats')
    train_dogs_dir = os.path.join(base_dir, 'training_set/dogs')
    test_cats_dir = os.path.join(base_dir, 'test_set/cats')
    test_dogs_dir = os.path.join(base_dir, 'test_set/dogs')
    
    print('total trainning cat images: ', len(os.listdir(train_cats_dir)))
    print('total trainning dog images: ', len(os.listdir(train_dogs_dir)))
    print('total testing cat images: ', len(os.listdir(test_cats_dir)))
    print('total testing cat images: ', len(os.listdir(test_dogs_dir)))

    model = models.Sequential()
    model.add(layers.Conv2D(32, (3,3),  activation='relu', input_shape=(150,150,3)))
    model.add(layers.MaxPooling2D((2,2)))
    model.add(layers.Conv2D(64, (3,3), activation='relu'))
    model.add(layers.MaxPooling2D((2,2)))
    model.add(layers.Conv2D(128, (3,3), activation='relu'))
    model.add(layers.MaxPooling2D((2,2)))
    model.add(layers.Conv2D(128, (3,3), activation='relu'))
    model.add(layers.MaxPooling2D((2,2)))
    model.add(layers.Flatten())
    model.add(layers.Dense(512, activation='relu'))
    model.add(layers.Dense(1, activation="sigmoid"))
    model.compile(loss='binary_crossentropy', optimizer='rmsprop', metrics=['acc'])
    model.summary()

    from keras import preprocessing
    from keras.preprocessing import image
    
    import numpy as np 
    
    path_cats = []
    for path in os.listdir(train_cats_dir):
        if '.jpg' in path:
            path_cats.append(os.path.join(train_cats_dir, path))
    path_dogs = []
    for path in os.listdir(train_dogs_dir):
        if '.jpg' in path:
            path_dogs.append(os.path.join(train_dogs_dir, path))
    
    
    training_set = np.zeros((6000, 150, 150, 3), dtype='float32')
    train_dog_imgs = 3000
    train_cat_imgs = 3000
    for i in range(0, train_dog_imgs):
        img = preprocessing.image.load_img(path_dogs[i], target_size=(150,150))
        training_set[i] = preprocessing.image.img_to_array(img)
    for j in range(0, train_cat_imgs):
        img = preprocessing.image.load_img(path_cats[j], target_size=(150,150))
        training_set[train_dog_imgs+j] = preprocessing.image.img_to_array(img)
    
    
    validation_set = np.zeros((2000, 150, 150, 3), dtype='float32')
    validation_dog_imgs = 1000
    validation_cat_imgs = 1000
    for i in range(validation_dog_imgs):
        path = path_dogs[i + train_dog_imgs] 
        img = preprocessing.image.load_img(path, target_size=(150,150))
        validation_set[i] = preprocessing.image.img_to_array(img)
    for j in range(validation_cat_imgs):
        path = path_cats[j+train_cat_imgs]
        img = preprocessing.image.load_img(path, target_size=(150,150))
        validation_set[j+validation_dog_imgs] = preprocessing.image.img_to_array(img)
    train_labels = np.zeros((3000,))
    #猫图片打标签1
    train_labels = np.concatenate((train_labels, np.ones(3000, )))
    validation_labels = np.zeros((1000, ))
    validation_labels = np.concatenate((validation_labels, np.ones(1000, )))
    train_datagen = preprocessing.image.ImageDataGenerator(rescale=1./255)
    train_generator = train_datagen.flow(training_set, train_labels, 
                                             batch_size = 32)
    validation_generator = train_datagen.flow(validation_set, validation_labels,
                                             batch_size=32)
    
    history = model.fit_generator(train_generator, steps_per_epoch=100,
                                 epochs = 30, validation_steps=50,
                                 validation_data=validation_generator)

    model.save('cats_and_dogs_small_1.h5')
    import matplotlib.pyplot as plt
    
    acc = history.history['acc']
    val_acc = history.history['val_acc']
    loss = history.history['loss']
    val_loss = history.history['val_loss']
    
    epochs = range(1, len(acc) + 1)
    
    plt.plot(epochs, acc, 'bo', label='Training acc')
    plt.plot(epochs, val_acc, 'b', label='Validation acc')
    plt.title('Training and validation accuracy')
    plt.legend()
    plt.figure()
    plt.plot(epochs, loss, 'bo', label='Training loss')
    plt.plot(epochs, val_loss, 'b', label='Validation loss')
    plt.title('Training and validation loss')
    plt.legend()
    plt.show()

     

  • 相关阅读:
    5.线性回归算法
    4.K均值算法--应用
    3.K均值算法
    机器学习2
    机器学习1
    第十五次作业
    第十三次作业
    第十一次作业
    P1250 种树
    P1516 青蛙的约会
  • 原文地址:https://www.cnblogs.com/tszr/p/12232643.html
Copyright © 2020-2023  润新知