keras训练自己数据-------goodlenet模型

首先要把对自己的数据进行处理:

文件名为load_img.py

# -*- coding: utf-8 -*-
import numpy as np
import os
from PIL import Image
def load_data(file_dir,nums):
    j = 0
    i = 0
    A0 = 0
    A1 = 0
    A2 = 0
    A3 = 0
    # 从data里面选择前number张作为总数据
    number = nums
    # 分为4类,从每个类的数量里面取前validation_split * number个样本
    number1 = int(nums/4)
    data = np.empty((number, 224, 224, 3), dtype="float32")
    label = np.empty((number,), dtype="uint8")

    for file in os.listdir(file_dir):
        for file1 in os.listdir(file_dir + '/' + file):
            for file2 in os.listdir(file_dir + '/' + file + '/' + file1):
                for file3 in os.listdir(file_dir + '/' + file + '/' + file1 + '/' + file2):
                    dir = file_dir + '/' + file + '/' + file1 + '/' + file2 + '/' + file3

                    if 'C.jpg' in file3:
                        # print(Image.open(dir))
                        try:
                            image = Image.open(dir)
                        except IOError:
                            print(dir)
                            print ("Error: 没有找到文件或读取文件失败")
                        else:
                            if i == number:
                                j = j + 1
                            else:
                                if A0 == number1:
                                    j = j + 1
                                else:

                                    if image.mode == 'RGB':
                                        # print(dir)
                                        img = Image.open(dir)
                                        # img= img.convert('L')   # 3通道图转化为单通道图
                                        img = img.resize((224, 224), Image.ANTIALIAS)

                                        arr = np.asarray(img, dtype="float32")

                                        data[i, :, :, :] = arr
                                        label[i] = int(0)
                                        A0 = A0 + 1
                                        i = i + 1
                                        if i % 500 == 0:
                                            print(i)
                                    else:
                                        j = j + 1
                    elif 'CB.jpg' in file3:
                        # print(Image.open(dir))
                        try:
                            image = Image.open(dir)
                        except IOError:
                            print(dir)
                            print("Error: 没有找到文件或读取文件失败")
                        else:
                            if i == number:
                                j = j + 1
                            else:
                                if A3 == number1:
                                    j = j + 1
                                else:

                                    if image.mode == 'RGB':
                                        # print(dir)
                                        img = Image.open(dir)
                                        # img = img.convert('L')  # 3通道图转化为单通道图
                                        img = img.resize((224, 224), Image.ANTIALIAS)

                                        arr = np.asarray(img, dtype="float32")

                                        data[i, :, :, :] = arr
                                        label[i] = int(3)
                                        A3 = A3 + 1
                                        i = i + 1
                                        if i % 500 == 0:
                                            print(i)
                                    else:
                                        j = j + 1
                    elif 'CA.jpg' in file3:
                        # print(Image.open(dir))
                        try:
                            image = Image.open(dir)
                        except IOError:
                            print(dir)
                            print ("Error: 没有找到文件或读取文件失败")
                        else:
                            if i == number:
                                j = j + 1
                            else:
                                if A1 == number1:
                                    j = j + 1
                                else:
                                    if image.mode == 'RGB':
                                        # print(dir)
                                        img = Image.open(dir)
                                        # img = img.convert('L')  # 3通道图转化为单通道图
                                        img = img.resize((224, 224), Image.ANTIALIAS)

                                        arr = np.asarray(img, dtype="float32")

                                        data[i, :, :, :] = arr
                                        label[i] = int(1)
                                        A1 = A1 + 1
                                        i = i + 1
                                        if i % 500 == 0:
                                            print(i)
                                    else:
                                        j = j + 1
                    elif ('C.jpg' not in file3) and ('CA.jpg' not in file3) and ('CB.jpg' not in file3) and (
                            '.jpg' in file3):
                        # print(Image.open(dir))
                        try:
                            image = Image.open(dir)
                        except IOError:
                            print(dir)
                            print ("Error: 没有找到文件或读取文件失败")
                        else:
                            if i == number:
                                j = j + 1
                            else:
                                if A2 == number1:
                                    j = j + 1
                                else:

                                    if image.mode == 'RGB':
                                        # print(dir)
                                        img = Image.open(dir)
                                        # img = img.convert('L')  # 3通道图转化为单通道图
                                        img = img.resize((224, 224), Image.ANTIALIAS)

                                        arr = np.asarray(img, dtype="float32")

                                        data[i, :, :, :] = arr
                                        label[i] = int(2)
                                        A2 = A2 + 1
                                        i = i + 1
                                        if (i % 500 == 0):
                                            print(i)

                                    else:
                                        j = j + 1
                    else:
                        j = j + 1

    print(i)
    return data, label

第二部就要把自己的数据导入goodlenet网络里;

# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
# 1. 导入各种模块
# 基本形式为:
# import 模块名
# from 某个文件 import 某个模块

# 指定GPU+固定显存
import os
import tensorflow as tf
os.environ["CUDA_VISIBLE_DEVICES"]="3"  # 调用gpu哪块显卡
from keras.backend.tensorflow_backend import set_session
config = tf.ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = 0.9  # 为显卡利用率设置阈值
set_session(tf.Session(config=config))

from PIL import Image  # 图像读写
import numpy as np   # 数组或者矩阵计算
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential   # 新建模型时用到
from keras.layers.advanced_activations import PReLU  # 比较新的激活函数
from keras.optimizers import SGD, Adadelta, Adagrad  # 各种优化器
from keras.utils import np_utils, generic_utils #标签二值化

from keras.utils.vis_utils import plot_model    # 画出网络模型
from six.moves import range
from keras.layers import Input, Dense, Dropout, BatchNormalization, Conv2D, MaxPooling2D, AveragePooling2D,\
concatenate,Activation, Flatten
from keras.layers.convolutional import Conv2D, MaxPooling2D, AveragePooling2D
from load_img import load_data    # 加载数据集,返回data,label
from keras.models import Model    # 构建网络模型需要用的模块
from keras import backend as K  # 去除历史计算图
from sklearn.cross_validation import train_test_split  # 用于分类train :test
from keras.wrappers import scikit_learn
from keras.callbacks import ModelCheckpoint
import copy
import types
np.random.seed(1337)  # for reproducibility


# load and pre-process data
def preprocess_input(x):
    return x.astype('float32').reshape((-1,) + input_shape) / 255


def preprocess_output(y):
    return np_utils.to_categorical(y)

def Conv2d_BN(x, nb_filter, kernel_size, padding='same', strides=(1, 1), name=None):
    if name is not None:
        bn_name = name + '_bn'
        conv_name = name + '_conv'
    else:
        bn_name = None
        conv_name = None
    x = Conv2D(nb_filter, kernel_size, padding=padding, strides=strides, activation='relu', name=conv_name)(x)
    x = BatchNormalization(axis=3, name=bn_name)(x)
    return x


def Inception(x, nb_filter):

    branch1x1 = Conv2d_BN(x, nb_filter, (1, 1), padding='same', strides=(1, 1), name=None)
    branch3x3 = Conv2d_BN(x, nb_filter, (1, 1), padding='same', strides=(1, 1), name=None)
    branch3x3 = Conv2d_BN(branch3x3, nb_filter, (3, 3), padding='same', strides=(1, 1), name=None)
    branch5x5 = Conv2d_BN(x, nb_filter, (1, 1), padding='same', strides=(1, 1), name=None)
    branch5x5 = Conv2d_BN(branch5x5, nb_filter, (1, 1), padding='same', strides=(1, 1), name=None)
    branchpool = MaxPooling2D(pool_size=(3, 3), strides=(1, 1), padding='same')(x)
    branchpool = Conv2d_BN(branchpool, nb_filter, (1, 1), padding='same', strides=(1, 1), name=None)

    x = concatenate([branch1x1, branch3x3, branch5x5, branchpool], axis=3)

    return x


def create_model(dropout):

    input_shape = (224, 224, 3)
    inputTensor = Input(input_shape)
    # padding = 'same',填充为(步长-1)/2,还可以用ZeroPadding2D((3,3))
    # model = Sequential()
    x = Conv2d_BN(inputTensor, 64, (7, 7), strides=(2, 2), padding='same')
    # print('1 x_Conv2d_BN shape:', x.shape)
    x = MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding='same')(x)
    # print(' x_MaxPooling2D shape:', x.shape)
    x = Conv2d_BN(x, 192, (3, 3), strides=(1, 1), padding='same')
    # print('2 x_Conv2d_BN shape:', x.shape)
    x = MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding='same')(x)
    x = Inception(x, 64)  # 256
    # print('3 x_Inception shape:', x.shape)
    x = Inception(x, 120)  # 480
    # print('4 x_Inception shape:', x.shape)
    x = MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding='same')(x)
    x = Inception(x, 128)  # 512
    # print('5 x_Inception shape:', x.shape)
    x = Inception(x, 128)
    # print('6 x_Inception shape:', x.shape)
    x = Inception(x, 128)
    # print('7 x_Inception shape:', x.shape)
    x = Inception(x, 132)  # 528
    # print('8 x_Inception shape:', x.shape)
    x = Inception(x, 208)  # 832
    # print('9 x_Inception shape:', x.shape)
    x = MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding='same')(x)
    x = Inception(x, 208)
    # print('10 x_Inception shape:', x.shape)
    x = Inception(x, 256)  # 1024
    # print('11 x_Inception shape:', x.shape)
    x = AveragePooling2D(pool_size=(7, 7), strides=(7, 7), padding='same')(x)
    x = Flatten(name='flatten')(x)
    x = Dropout(dropout)(x)
    # print('11 x_Dropout(0.4) shape:', x.shape)

    # print('12 x_Flatten shape:', x.shape)
    x = Dense(1000, activation='relu')(x)
    # print('12 x_Dense_1 shape:', x.shape)
    x1 = Dense(4, activation='softmax')(x)
    # print('13 x_Dense_2 shape:', x1.shape)
    model = Model(input=inputTensor, output=x1)
    return model


if __name__ == '__main__':

    # 对数据进行预处理
    num_classes = 4  # number of classes
    batch_size = 100
    epochs = 40
    # 加载数据
    input_shape = (224, 224, 3)
    if K.image_data_format() == 'channels_first':
        input_shape = (3, 224, 224)  # image shape
    else:
        input_shape = (224, 224, 3)  # image shape

    Data_Path = '/home/4T/2018_runpu_data/原始数据/河北数据4_20180409'
    data, label = load_data(Data_Path, 40000)
    label = np_utils.to_categorical(label, 4)
    x_train, x_test, y_train, y_test = train_test_split(data, label, test_size=0.2, random_state=20)
    print('Loading data...')
    print('x_train shape:', x_train.shape, 'y_train shape:', y_train[1].shape)
    print('x_test shape:', x_test.shape, 'y_test shape', y_test[1].shape)

    save_dir = '/home/4T/wdd/keras_study/For_Classification/model'
    model_name = 'pan_obj_googlenet_40000.h5'
    # model_name='googlenet-ep{epoch:03d}-loss{loss:.3f}-val_loss{val_loss:.3f}.h5'
    model_path = os.path.join(save_dir, model_name)
    model = create_model(0.4)
    model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy'])
    # 该回调函数将在最好的epoch后保存模型到model_path
    checkpoint = ModelCheckpoint(model_name,
                                 monitor='val_acc', verbose=1, save_best_only=True, mode='max')
    model.fit(data, label, batch_size=batch_size, epochs=epochs, verbose=1,callbacks=[checkpoint],
              validation_data=(x_test, y_test),shuffle=True, initial_epoch=0)
    model.save('pan_obj_googlenet_40000.h5')
    print('Saved trained model at %s ' % model_path)


    K.clear_session()

也可以测试不同的bach和epoch

# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
# 1. 导入各种模块
# 基本形式为:
# import 模块名
# from 某个文件 import 某个模块

# 指定GPU+固定显存
import os
import tensorflow as tf
os.environ["CUDA_VISIBLE_DEVICES"]="1"  # 调用gpu哪块显卡
from keras.backend.tensorflow_backend import set_session
config = tf.ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = 0.9  # 为显卡利用率设置阈值
set_session(tf.Session(config=config))

from PIL import Image  # 图像读写
import numpy as np   # 数组或者矩阵计算
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential   # 新建模型时用到
from keras.layers.advanced_activations import PReLU  # 比较新的激活函数
from keras.optimizers import SGD, Adadelta, Adagrad  # 各种优化器
from keras.utils import np_utils, generic_utils
# from keras.utils.np_utils import to_categorical  # 标签二值化
from keras.utils.vis_utils import plot_model    # 画出网络模型
from six.moves import range
from keras.layers import Input, Dense, Dropout, BatchNormalization, Conv2D, MaxPooling2D, AveragePooling2D,\
concatenate,Activation, Flatten
from keras.layers.convolutional import Conv2D, MaxPooling2D, AveragePooling2D
from load_img import load_data    # 加载数据集,返回data,label
from keras.models import Model    # 构建网络模型需要用的模块
from keras import backend as K  # 去除历史计算图
from sklearn.cross_validation import train_test_split  # 用于分类train :test
from sklearn.model_selection import GridSearchCV
from keras.wrappers import scikit_learn
from keras.wrappers.scikit_learn import KerasClassifier
from keras.callbacks import ModelCheckpoint,Callback
import copy
import types
np.random.seed(1337)  # for reproducibility


class LossHistory(Callback):
    def on_train_begin(self,logs={}):
        self.losses = []

    def on_batch_end(self, batch, logs={}):
        self.losses.append(logs.get('loss'))

# load and pre-process data
def preprocess_input(x):
    return x.astype('float32').reshape((-1,) + input_shape) / 255


def preprocess_output(y):
    return np_utils.to_categorical(y)

def Conv2d_BN(x, nb_filter, kernel_size, padding='same', strides=(1, 1), name=None):
    if name is not None:
        bn_name = name + '_bn'
        conv_name = name + '_conv'
    else:
        bn_name = None
        conv_name = None
    x = Conv2D(nb_filter, kernel_size, padding=padding, strides=strides, activation='relu', name=conv_name)(x)
    x = BatchNormalization(axis=3, name=bn_name)(x)
    return x


def Inception(x, nb_filter):

    branch1x1 = Conv2d_BN(x, nb_filter, (1, 1), padding='same', strides=(1, 1), name=None)
    branch3x3 = Conv2d_BN(x, nb_filter, (1, 1), padding='same', strides=(1, 1), name=None)
    branch3x3 = Conv2d_BN(branch3x3, nb_filter, (3, 3), padding='same', strides=(1, 1), name=None)
    branch5x5 = Conv2d_BN(x, nb_filter, (1, 1), padding='same', strides=(1, 1), name=None)
    branch5x5 = Conv2d_BN(branch5x5, nb_filter, (1, 1), padding='same', strides=(1, 1), name=None)
    branchpool = MaxPooling2D(pool_size=(3, 3), strides=(1, 1), padding='same')(x)
    branchpool = Conv2d_BN(branchpool, nb_filter, (1, 1), padding='same', strides=(1, 1), name=None)

    x = concatenate([branch1x1, branch3x3, branch5x5, branchpool], axis=3)

    return x


def create_model(dropout):

    input_shape = (224, 224, 3)
    inputTensor = Input(input_shape)
    # padding = 'same',填充为(步长-1)/2,还可以用ZeroPadding2D((3,3))
    # model = Sequential()
    x = Conv2d_BN(inputTensor, 64, (7, 7), strides=(2, 2), padding='same')
    # print('1 x_Conv2d_BN shape:', x.shape)
    x = MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding='same')(x)
    # print(' x_MaxPooling2D shape:', x.shape)
    x = Conv2d_BN(x, 192, (3, 3), strides=(1, 1), padding='same')
    # print('2 x_Conv2d_BN shape:', x.shape)
    x = MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding='same')(x)
    x = Inception(x, 64)  # 256
    # print('3 x_Inception shape:', x.shape)
    x = Inception(x, 120)  # 480
    # print('4 x_Inception shape:', x.shape)
    x = MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding='same')(x)
    x = Inception(x, 128)  # 512
    # print('5 x_Inception shape:', x.shape)
    x = Inception(x, 128)
    # print('6 x_Inception shape:', x.shape)
    x = Inception(x, 128)
    # print('7 x_Inception shape:', x.shape)
    x = Inception(x, 132)  # 528
    # print('8 x_Inception shape:', x.shape)
    x = Inception(x, 208)  # 832
    # print('9 x_Inception shape:', x.shape)
    x = MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding='same')(x)
    x = Inception(x, 208)
    # print('10 x_Inception shape:', x.shape)
    x = Inception(x, 256)  # 1024
    # print('11 x_Inception shape:', x.shape)
    x = AveragePooling2D(pool_size=(7, 7), strides=(7, 7), padding='same')(x)
    x = Flatten(name='flatten')(x)
    x = Dropout(dropout)(x)
    # print('11 x_Dropout(0.4) shape:', x.shape)

    # print('12 x_Flatten shape:', x.shape)
    x = Dense(1000, activation='relu')(x)
    # print('12 x_Dense_1 shape:', x.shape)
    x1 = Dense(4, activation='softmax')(x)
    # print('13 x_Dense_2 shape:', x1.shape)
    model = Model(input=inputTensor, output=x1)
    model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy'])
    # model.summary()  # 打印出模型概况,它实际调用的是keras.utils.print_summary
    return model


if __name__ == '__main__':

    # 对数据进行预处理
    # num_classes = 4  # number of classes
    # batch_size = 256
    # epochs = 50
    # 加载数据
    input_shape = (224, 224, 3)
    if K.image_data_format() == 'channels_first':
        input_shape = (3, 224, 224)  # image shape
    else:
        input_shape = (224, 224, 3)  # image shape

    Data_Path = '/home/4T/2018_runpu_data/原始数据/河北数据4_20180409'
    data, label = load_data(Data_Path, 30000)
    label = np_utils.to_categorical(label, 4)
    x_train, x_test, y_train, y_test = train_test_split(data, label, test_size=0.2, random_state=20)
    # x_train, x_test = map(preprocess_input, [x_train, x_test])
    # y_train, y_test = map(preprocess_output,[y_train, y_test])
    print('Loading data...')
    print('x_train shape:', x_train.shape, 'y_train shape:', y_train[1].shape)
    print('x_test shape:', x_test.shape, 'y_test shape', y_test[1].shape)

    # 设置参数候选值
    batch_size = [32, 64,100]
    epochs = [20,40,60]
    my_classifier = scikit_learn.KerasClassifier(build_fn=create_model,dropout=0.4)
    # 创建GridSearchCV,并训练
    param_grid = dict(batch_size=batch_size, epochs=epochs)
    grid = GridSearchCV(estimator=my_classifier, param_grid=param_grid, n_jobs=1)
    grid_result = grid.fit(x_train, y_train,validation_data=(x_test, y_test))

    # 打印结果
    print('Best: {} using {}'.format(grid_result.best_score_, grid_result.best_params_))
    means = grid_result.cv_results_['mean_test_score']
    stds = grid_result.cv_results_['std_test_score']
    params = grid_result.cv_results_['params']

    for mean, std, param in zip(means, stds, params):
        print("%f (%f) with: %r" % (mean, std, param))
    checkpointer = ModelCheckpoint(filepath="model/googlenet_best.hdf5", verbose=1, save_best_only=True)
    history = LossHistory()
    with open('log_googlenet_train.txt','w') as f:
        f.write(str(history.history))
    # model.fit(data, label, batch_size=32, epochs=1, verbose=1,validation_split=0.2,shuffle=True, initial_epoch=0)
    # 神经网络模型可视化
    # plot_model(model, to_file='model.png',show_shapes=True)

    # 保存模型数据的文件
    # 用于保存验证集误差最小的参数,当验证集误差减少时,立马保存下来
    # save_dir = '/home/4T/wdd/keras_study/'
    # model_name = 'pan_obj_googlenet_24000.h5'
    # model_path = os.path.join(save_dir, model_name)
    # model_1.save(model_path)
    # print('Saved trained model at %s ' % model_path)

    K.clear_session()


最后一步就是,训练好模型以后,怎嘛进行调用(c++也是可以调用的)

# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
# 1. 导入各种模块
# 基本形式为:
# import 模块名
# from 某个文件 import 某个模块

# 指定GPU+固定显存
import os
import tensorflow as tf
os.environ["CUDA_VISIBLE_DEVICES"]="0"  # 调用gpu哪块显卡
from keras.backend.tensorflow_backend import set_session
config = tf.ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = 0.9  # 为显卡利用率设置阈值
#set_session(tf.Session(config=config))

from PIL import Image  # 图像读写
import numpy as np   # 数组或者矩阵计算
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential   # 新建模型时用到
from keras.layers.advanced_activations import PReLU  # 比较新的激活函数
from keras.optimizers import SGD, Adadelta, Adagrad  # 各种优化器
from keras.utils import np_utils, generic_utils
# from keras.utils.np_utils import to_categorical  # 标签二值化
from keras.utils.vis_utils import plot_model    # 画出网络模型
from six.moves import range
from keras.layers import Input, Dense, Dropout, BatchNormalization, Conv2D, MaxPooling2D, AveragePooling2D,\
concatenate,Activation, Flatten
from keras.layers.convolutional import Conv2D, MaxPooling2D, AveragePooling2D
#from load_img import load_data    # 加载数据集,返回data,label
from keras.models import Model    # 构建网络模型需要用的模块
from keras.models import load_model
from keras import backend as K  # 去除历史计算图
from sklearn.cross_validation import train_test_split  # 用于分类train :test
from sklearn.model_selection import GridSearchCV
from keras.wrappers import scikit_learn
from keras.wrappers.scikit_learn import KerasClassifier
from keras.callbacks import ModelCheckpoint,Callback
import copy
import types
import cv2
np.random.seed(1337)  # for reproducibility


# load and pre-process data

def preprocess_input(x):
    return x.astype('float32').reshape((-1,) + input_shape) / 255


def preprocess_output(y):
    return np_utils.to_categorical(y)


def Conv2d_BN(x, nb_filter, kernel_size, padding='same', strides=(1, 1), name=None):
    if name is not None:
        bn_name = name + '_bn'
        conv_name = name + '_conv'
    else:
        bn_name = None
        conv_name = None
    x = Conv2D(nb_filter, kernel_size, padding=padding, strides=strides, activation='relu', name=conv_name)(x)
    x = BatchNormalization(axis=3, name=bn_name)(x)
    return x


def Inception(x, nb_filter):

    branch1x1 = Conv2d_BN(x, nb_filter, (1, 1), padding='same', strides=(1, 1), name=None)
    branch3x3 = Conv2d_BN(x, nb_filter, (1, 1), padding='same', strides=(1, 1), name=None)
    branch3x3 = Conv2d_BN(branch3x3, nb_filter, (3, 3), padding='same', strides=(1, 1), name=None)
    branch5x5 = Conv2d_BN(x, nb_filter, (1, 1), padding='same', strides=(1, 1), name=None)
    branch5x5 = Conv2d_BN(branch5x5, nb_filter, (1, 1), padding='same', strides=(1, 1), name=None)
    branchpool = MaxPooling2D(pool_size=(3, 3), strides=(1, 1), padding='same')(x)
    branchpool = Conv2d_BN(branchpool, nb_filter, (1, 1), padding='same', strides=(1, 1), name=None)
    x = concatenate([branch1x1, branch3x3, branch5x5, branchpool], axis=3)

    return x


def create_model(dropout):

    input_shape = (224, 224, 3)
    inputTensor = Input(input_shape)
    # padding = 'same',填充为(步长-1)/2,还可以用ZeroPadding2D((3,3))
    # model = Sequential()
    x = Conv2d_BN(inputTensor, 64, (7, 7), strides=(2, 2), padding='same')
    # print('1 x_Conv2d_BN shape:', x.shape)
    x = MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding='same')(x)
    # print(' x_MaxPooling2D shape:', x.shape)
    x = Conv2d_BN(x, 192, (3, 3), strides=(1, 1), padding='same')
    # print('2 x_Conv2d_BN shape:', x.shape)
    x = MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding='same')(x)
    x = Inception(x, 64)  # 256
    # print('3 x_Inception shape:', x.shape)
    x = Inception(x, 120)  # 480
    # print('4 x_Inception shape:', x.shape)
    x = MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding='same')(x)
    x = Inception(x, 128)  # 512
    # print('5 x_Inception shape:', x.shape)
    x = Inception(x, 128)
    # print('6 x_Inception shape:', x.shape)
    x = Inception(x, 128)
    # print('7 x_Inception shape:', x.shape)
    x = Inception(x, 132)  # 528
    # print('8 x_Inception shape:', x.shape)
    x = Inception(x, 208)  # 832
    # print('9 x_Inception shape:', x.shape)
    x = MaxPooling2D(pool_size=(3, 3), strides=(2, 2), padding='same')(x)
    x = Inception(x, 208)
    # print('10 x_Inception shape:', x.shape)
    x = Inception(x, 256)  # 1024
    # print('11 x_Inception shape:', x.shape)
    x = AveragePooling2D(pool_size=(7, 7), strides=(7, 7), padding='same')(x)
    x = Flatten(name='flatten')(x)
    x = Dropout(dropout)(x)
    # print('11 x_Dropout(0.4) shape:', x.shape)

    # print('12 x_Flatten shape:', x.shape)
    x = Dense(1000, activation='relu')(x)
    # print('12 x_Dense_1 shape:', x.shape)
    x1 = Dense(4, activation='softmax')(x)
    # print('13 x_Dense_2 shape:', x1.shape)
    model = Model(inputs=inputTensor, output=x1)
    model.compile(loss='categorical_crossentropy', optimizer='sgd', metrics=['accuracy'])
    # model.summary()  # 打印出模型概况,它实际调用的是keras.utils.print_summary

    return model

def load_testdata(test_image):
    testImg = Image.open(test_image)
    testImg = testImg.resize((224, 224), Image.ANTIALIAS)
    imgArr = np.asarray(testImg, dtype="float32")
    testData = np.empty((1, 224, 224, 3), dtype="float32")
    testData[0, :, :,:] = imgArr
    return testData




if __name__ == '__main__':

    # 对数据进行预处理
    num_classes = 4  # number of classes
    batch_size = 100
    epochs = 10
    # 加载数据
    input_shape = (224, 224, 3)
    #if K.image_data_format() == 'channels_first':
    if K.image_dim_ordering() == 'th':
        input_shape = (3, 224, 224)  # image shape
    else:
        input_shape = (224, 224, 3)  # image shape

    # Data_Path = '/home/4T/2018_runpu_data/原始数据/河北数据4_20180409'
    # #data, label = load_data(Data_Path, 200)
    # label = np_utils.to_categorical(label, 4)
    # x_train, x_test, y_train, y_test = train_test_split(data, label, test_size=0.2, random_state=20)
    # # x_train, x_test = map(preprocess_input, [x_train, x_test])
    # # y_train, y_test = map(preprocess_output,[y_train, y_test])
    # print('Loading data...')
    # print('x_train shape:', x_train.shape, 'y_train shape:', y_train[1].shape)
    # print('x_test shape:', x_test.shape, 'y_test shape', y_test[1].shape)

    model = create_model(dropout=0.4)
    # model.fit(data, label, batch_size=32, epochs=1, verbose=1,validation_split=0.2,shuffle=True, initial_epoch=0)
    #model.fit(x_train, y_train,batch_size = batch_size,epochs=epochs,verbose=1,validation_data=(x_test, y_test),shuffle=True)

    # 保存模型数据的文件
    # save_dir = '/home/4T/wdd/keras_study/'
    # model_name = 'pan_obj_googlenet_24000.h5'
    # model_path = os.path.join(save_dir, model_name)
    # model.save(model_path)
    #print('Saved trained model at %s ' % model_path)
    # 神经网络模型可视化
    # plot_model(model, to_file='model.png',show_shapes=True)
    test_image = '/home/4T/2018_runpu_data/测试样本抽取/12/1/裁定书/(2017)冀0109财保10号/2CB.jpg'
    #src=cv2.imread(test_image)
    #cv2.imshow("test image: ",src)


    model_path='/home/4T/2018_runpu_data/pan_obj_googlenet_40000.h5'
    model=load_model(model_path)
    # model.load_weights(model_path)
    testData=load_testdata(test_image)

    yy=model.predict(testData, batch_size=1, verbose=0)
    result=np.argmax(yy)
    print('待测的图片是 : ',result)
    K.clear_session()


这里这能进行一张一张的测试,进行批测试,需要修改一下代码

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值