zoukankan      html  css  js  c++  java
  • keras例程-简单CNN猫狗分类

    from keras.models import Sequential
    from keras.layers import Conv2D,MaxPool2D,Activation,Dropout,Flatten,Dense
    from keras.optimizers import Adam
    from keras.preprocessing.image import ImageDataGenerator,img_to_array,load_img
    
    # 定义模型
    model = Sequential()
    model.add(Conv2D(input_shape=(150,150,3),filters=32,kernel_size=3,padding='same',activation='relu'))
    model.add(Conv2D(filters=32,kernel_size=3,padding='same',activation='relu'))
    model.add(MaxPool2D(pool_size=2, strides=2))
    
    model.add(Conv2D(filters=64,kernel_size=3,padding='same',activation='relu'))
    model.add(Conv2D(filters=64,kernel_size=3,padding='same',activation='relu'))
    model.add(MaxPool2D(pool_size=2, strides=2))
    
    model.add(Conv2D(filters=128,kernel_size=3,padding='same',activation='relu'))
    model.add(Conv2D(filters=128,kernel_size=3,padding='same',activation='relu'))
    model.add(MaxPool2D(pool_size=2, strides=2))
    
    model.add(Flatten())
    model.add(Dense(64,activation='relu'))
    model.add(Dropout(0.5))
    model.add(Dense(2,activation='softmax'))
    
    # 定义优化器
    adam = Adam(lr=1e-4)
    
    # 定义优化器,代价函数,训练过程中计算准确率
    model.compile(optimizer=adam,loss='categorical_crossentropy',metrics=['accuracy'])
    
    
    #训练集图像增强
    train_datagen = ImageDataGenerator(
        rotation_range = 40,     # 随机旋转度数
        width_shift_range = 0.2, # 随机水平平移
        height_shift_range = 0.2,# 随机竖直平移
        rescale = 1/255,         # 数据归一化
        shear_range = 20,       # 随机错切变换
        zoom_range = 0.2,        # 随机放大
        horizontal_flip = True,  # 水平翻转
        fill_mode = 'nearest',   # 填充方式
    ) 
    #测试集数据增强
    test_datagen = ImageDataGenerator(
        rescale = 1/255,         # 数据归一化
    ) 
    
    batch_size = 32
    
    # 生成训练数据
    train_generator = train_datagen.flow_from_directory(
        'image/train',
        target_size=(150,150),
        batch_size=batch_size,
        )
    
    # 测试数据
    test_generator = test_datagen.flow_from_directory(
        'image/test',
        target_size=(150,150),
        batch_size=batch_size,
        )
    #打印训练集分类   
    train_generator.class_indices#{'cat': 0, 'dog': 1}
    #分类每个文件夹表示一个类别,可以用flow_from_directory()+fit_generator()
    #如果是回归问题,要先准备好样本和标签,同时放进fit里面
    model.fit_generator(train_generator,
                        steps_per_epoch=len(train_generator),
                                 epochs=30,
                                 validation_data=test_generator,
                                 validation_steps=len(test_generator))
  • 相关阅读:
    Dijkstra-leetcode 743.网络延迟时间
    BFS-leetcode787 K站中转内最便宜的航班
    图论基础——单源最短路径问题
    DFS leetcode-547 朋友圈
    SpringBoot 使用注解向容器中注册Bean的方法总结
    SpringBoot对SpringMVC的支持
    数据源简介
    Spring MVC简介
    2020-2-10 Python 列表切片陷阱:引用、复制与深复制
    2020-2-2 语法糖
  • 原文地址:https://www.cnblogs.com/yunshangyue71/p/13584444.html
Copyright © 2011-2022 走看看