• 吴裕雄--天生自然神经网络与深度学习实战Python+Keras+TensorFlow:用预先训练好的卷积网络实现图像快速识别


    from keras.preprocessing import image
    from keras.preprocessing.image import ImageDataGenerator
    import os
    import matplotlib.pyplot as plt
    
    datagen = ImageDataGenerator(rotation_range = 40, width_shift_range = 0.2, height_shift_range = 0.2,
                                shear_range = 0.2, zoom_range = 0.2, horizontal_flip = True, fill_mode = 'nearest')
    
    fnames = [os.path.join(train_dogs_dir, fname) for fname in os.listdir(train_dogs_dir)]
    
    
    #从狗图片中选择一张
    img_path = fnames[3]
    print(img_path)
    
    img = image.load_img(img_path, target_size=(150,150))
    img = image.img_to_array(img)
    #把img变成3维向量形式[1,150,150]
    img = img.reshape((1,) + img.shape)
    i = 0
    #对图片做输入参数中指定的6种变换
    f, ax = plt.subplots(1, 6)
    for batch in datagen.flow(img, batch_size=1):
        imgplot = ax[i].imshow(image.array_to_img(batch[0]))
        ax[i].axis('off')
        i += 1
        if i % 6 == 0:
            break
    plt.show()
    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.Dropout(0.5))
    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()

    #执行这里的代码时,记住把网络构造部分的代码再执行一次以便确保我们训练的是一个新网络
    train_datagen = ImageDataGenerator(rescale = 1. / 255, rotation_range = 40, width_shift_range = 0.2,
                                      height_shift_range = 0.2, shear_range = 0.2, zoom_range = 0.2,
                                      horizontal_flip = True,)
    train_generator = train_datagen.flow(training_set, train_labels, batch_size = 32)
    validation_datagen = ImageDataGenerator(rescale = 1. / 255)
    validation_generator = validation_datagen.flow(validation_set, validation_labels, batch_size = 32)
    history = model.fit_generator(train_generator, steps_per_epoch=100,
                                 epochs = 30, validation_data = validation_generator,
                                 validation_steps = 50)

    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()
    from keras.preprocessing import image
    
    img_path = os.path.join(train_dogs_dir, 'dog.1.jpg')
    img = image.load_img(img_path, target_size=(150,150))
    img_tensor = image.img_to_array(img)
    img_tensor = np.expand_dims(img_tensor, axis=0)
    img_tensor /= 255.
    print(img_tensor.shape)
    plt.imshow(img_tensor[0])

    from keras.models import Model
    layer_outputs = [layer.output for layer in model.layers[:8]]
    activation_model = Model(inputs=model.input, outputs=layer_outputs)
    activations = activation_model.predict(img_tensor)
    
    layer_show = 0
    channel = 18
    
    layer_activation = activations[layer_show]
    plt.matshow(layer_activation[0,:,:,channel], cmap='viridis')

    fig, ax = plt.subplots(2, 4)
    plt.axis('off')
    
    for i in range(0, 2):
        for j in range(0, 4):
            layer_activation = activations[i*4 + j]
            ax[i, j].matshow(layer_activation[0,:,:,9], cmap='viridis')
            ax[i, j].set_xticks([])
            ax[i, j].set_yticks([])

  • 相关阅读:
    CorelDRAW X8完全学习教程
    Linux环境编程:从应用到内核
    Excel 2010 VBA 入门与实战
    iOS 用GDataXMLNode创建和解析XML
    iOS 使用SBJSON创建和解析JSON
    [iOS]MD5加密字符串
    Read and Write NSArray, NSDictionary and NSSet to a File
    ASIHTTPRequest类库简介和使用说明
    ios 调用webservice整理
    数据库迁移(SQL SERVER导入数据到MySql)
  • 原文地址:https://www.cnblogs.com/tszr/p/12232657.html
Copyright © 2020-2023  润新知