Keras学习笔记---keras做回归问题

参考caffe做回归问题,这里主要是改caffe的回归代码为keras代码,顺便熟悉keras的流程。caffe的训练数据主要是通过这篇博客网址得到训练数据。这里主要是通过keras书写网络,同时做相应的预测。


首先看一下caffe的网络结构图:

Keras学习笔记---keras做回归问题_第1张图片

这里按照这个网络搭建keras的网络:

# coding=utf-8
from keras.layers import merge
from keras.layers.convolutional import Convolution2D, MaxPooling2D,ZeroPadding2D,AveragePooling2D
from keras.layers.core import Dense, Activation,Flatten,Dropout
from keras.layers.normalization import BatchNormalization
from keras.models import Model
from keras.layers import Input
from keras.utils import plot_model
from keras import losses
import h5py
import keras
#输入数据的块大小
inp = Input(shape=(1,100,100))
#网络结构
out = Convolution2D(96,kernel_size=(5,5),strides=(2,2))(inp)
out = Activation('relu')(out)
out = MaxPooling2D(pool_size=(3,3),strides=2)(out)
out = ZeroPadding2D(padding=(2,2))(out)


out = Convolution2D(filters=96,kernel_size=(3,3),strides=(1,1))(out)
out = Activation('relu')(out)
out = MaxPooling2D(pool_size=(3,3),strides=2)(out)
out = ZeroPadding2D(padding=(1,1))(out)


out = Convolution2D(filters=128,kernel_size=(3,3),strides=(1,1))(out)
out = Activation('relu')(out)
out = MaxPooling2D(pool_size=(3,3),strides=2)(out)

out = Flatten()(out)
out = Dense(units=192,activation='softmax')(out)
out = Activation('relu')(out)
out = Dropout(rate=0.5)(out)
out = Dense(units=1,activation='sigmoid')(out)
#net
model = Model(inp,out)

#做回归的问题采用mse损失函数
model.compile(loss=losses.mean_squared_error, optimizer='sgd')
#载入需要进行训练的数据

x_data = keras.utils.io_utils.HDF5Matrix('train.h5', 'data')
y_data = keras.utils.io_utils.HDF5Matrix('train.h5', 'score')
#shuffle the data
model.fit(x_data, y_data,validation_split=0.3,epochs=10, batch_size=16)
model.save('regression_model.h5')
plot_model(model, to_file='model2.png',show_shapes=True)

网络图如下:

Keras学习笔记---keras做回归问题_第2张图片

然后用来预测的代码如下:

# coding=utf-8
import numpy as np
from keras.layers import Dense
from keras.models import Model
from keras.preprocessing import image

from keras.models import load_model
model = load_model('regression_model.h5')
# model.load_weights('weight.h5')
print model.get_config()
image_path = './samples/00001_0.028184228311.jpg'
# 加载图像
img = image.load_img(image_path,  grayscale=True, target_size=(100, 100))
# 图像预处理
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)

# 对图像进行分类
preds = model.predict(x)
# 输出预测概率
print 'Predicted:', preds


重点都在代码中注释。

你可能感兴趣的:(计算机视觉和深度学习,Keras学习笔记)