博客
关于我
Keras自定义网络进行十分类图像识别
阅读量:262 次
发布时间:2019-03-01

本文共 4177 字,大约阅读时间需要 13 分钟。

import osimport numpy as npimport tensorflow as tfimport randomimport seaborn as snsimport matplotlib.pyplot as pltfrom keras.models import Sequential, Modelfrom keras.layers import Dense, Dropout, Activation, Flatten, Inputfrom keras.layers.convolutional import Conv2D, MaxPooling2Dfrom keras.optimizers import RMSprop, Adam, SGDfrom keras.preprocessing import imagefrom keras.preprocessing.image import ImageDataGeneratorfrom keras.utils import np_utilsfrom sklearn.model_selection import train_test_split

图片预处理

def read_and_process_image(data_dir,width=32, height=32, channels=3, preprocess=False):        train_classes= [data_dir +  i for i in os.listdir(data_dir) ]    train_images = []    for train_class in train_classes:        train_images= train_images + [train_class + "/" + i for i in os.listdir(train_class)]        random.shuffle(train_images)        def read_image(file_path, preprocess):        img = image.load_img(file_path, target_size=(height, width))        x = image.img_to_array(img)        x = np.expand_dims(x, axis=0)        # if preprocess:            # x = preprocess_input(x)        return x        def prep_data(images, proprocess):        count = len(images)        data = np.ndarray((count, height, width, channels), dtype = np.float32)                for i, image_file in enumerate(images):            image = read_image(image_file, preprocess)            data[i] = image                return data        def read_labels(file_path):        labels = []        for i in file_path:            if 'airplane' in i:                label = 0            elif 'automobile' in i:                label = 1            elif 'bird' in i:                label = 2            elif 'cat' in i:                label = 3            elif 'deer' in i:                label = 4            elif 'dog' in i:                label = 5            elif 'frog' in i:                label = 6            elif 'horse' in i:                label = 7            elif 'ship' in i:                label = 8            elif 'truck' in i:                label = 9            labels.append(label)                return labels        X = prep_data(train_images, preprocess)    labels = read_labels(train_images)        assert X.shape[0] == len(labels)        print("Train shape: {}".format(X.shape))        return X, labels

读取训练集,以及测试集

# 读取训练集图片WIDTH = 32HEIGHT = 32CHANNELS = 3X, y = read_and_process_image('D:/Python Project/cifar-10/train/',width=WIDTH, height=HEIGHT, channels=CHANNELS)# 读取测试集图片WIDTH = 32HEIGHT = 32CHANNELS = 3test_X, test_y = read_and_process_image('D:/Python Project/cifar-10/test/',width=WIDTH, height=HEIGHT, channels=CHANNELS)# 统计ysns.countplot(y)# 统计ysns.countplot(test_y)

one-hot编码

train_y = np_utils.to_categorical(y)test_y = np_utils.to_categorical(test_y)

显示图片

# 显示图片def show_picture(X, idx):    plt.figure(figsize=(10,5), frameon=True)    img = X[idx,:,:,::-1]    img = img/255    plt.imshow(img)    plt.show()for idx in range(0,3):    show_picture(X, idx)

定义模型

num_classes=10model = Sequential()model.add(Conv2D(32 ,3 ,input_shape=(HEIGHT,WIDTH,CHANNELS),activation='relu',padding='same'))model.add(Conv2D(32 ,3 ,activation='relu',padding='same'))model.add(MaxPooling2D(pool_size=2))model.add(Conv2D(64 ,3 ,activation='relu',padding='same'))model.add(Conv2D(64 ,3 ,activation='relu',padding='same'))model.add(MaxPooling2D(pool_size=2))model.add(Conv2D(128 ,3 ,activation='relu',padding='same'))model.add(Conv2D(128 ,3 ,activation='relu',padding='same'))model.add(MaxPooling2D(pool_size=2))model.add(Conv2D(256 ,3 ,activation='relu',padding='same'))model.add(Conv2D(256 ,3 ,activation='relu',padding='same'))model.add(MaxPooling2D(pool_size=2))model.add(Flatten())model.add(Dense(256, activation='relu'))model.add(Dropout(0.5))model.add(Dense(256, activation='relu'))model.add(Dropout(0.5))model.add(Dense(num_classes, activation='softmax'))model.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy'])model.summary()

训练模型

history = model.fit(X,train_y, validation_data=(test_X, test_y),epochs=20,batch_size=100,verbose=True)score = model.evaluate(test_X, test_y, verbose=0)print("Large CNN Error: %.2f%%" %(100-score[1]*100))

 

转载地址:http://kshv.baihongyu.com/

你可能感兴趣的文章
mysql_secure_installation初始化数据库报Access denied
查看>>
MySQL_西安11月销售昨日未上架的产品_20161212
查看>>
Mysql——深入浅出InnoDB底层原理
查看>>
MySQL“被动”性能优化汇总
查看>>
MySQL、HBase 和 Elasticsearch:特点与区别详解
查看>>
MySQL、Redis高频面试题汇总
查看>>
MYSQL、SQL Server、Oracle数据库排序空值null问题及其解决办法
查看>>
mysql一个字段为空时使用另一个字段排序
查看>>
MySQL一个表A中多个字段关联了表B的ID,如何关联查询?
查看>>
MYSQL一直显示正在启动
查看>>
MySQL一站到底!华为首发MySQL进阶宝典,基础+优化+源码+架构+实战五飞
查看>>
MySQL万字总结!超详细!
查看>>
Mysql下载以及安装(新手入门,超详细)
查看>>
MySQL不会性能调优?看看这份清华架构师编写的MySQL性能优化手册吧
查看>>
MySQL不同字符集及排序规则详解:业务场景下的最佳选
查看>>
Mysql不同官方版本对比
查看>>
MySQL与Informix数据库中的同义表创建:深入解析与比较
查看>>
mysql与mem_细说 MySQL 之 MEM_ROOT
查看>>
MySQL与Oracle的数据迁移注意事项,另附转换工具链接
查看>>
mysql丢失更新问题
查看>>