练习keras的卷积神经网络

https://www.cnblogs.com/lc1217/p/7324935.html

from PIL import Image
import pylab
import os
import numpy as np
from keras.models import Sequential
from keras.layers import Convolution2D,ZeroPadding2D,MaxPooling2D
from keras.optimizers import SGD

cwd = os.getcwd()
filepath = cwd + '/training-images/且/0aeab785376122c0463eec35c95e6b823f4fc988.jpg'

# 打开图片,获得PIL图像对象
pil_im = Image.open(filepath,'r')
# 把图片转换成数组形式,得到一个numpy数组对象
array_im = np.asarray(pil_im,dtype="float32")

width=array_im.shape[0]
height=array_im.shape[1]
data = np.empty((1,width,height,1),dtype="float32")
data[0,:,:,0]=array_im

# 设置sober权重
sober_weights =  [[[[[-1]],[[0]],[[1]]],[[[-2]],[[0]],[[2]]],[[[-1]],[[0]],[[1]]]]]
sober_weights = np.array(sober_weights)


# 组织卷积神经网络
model = Sequential()
model.add(ZeroPadding2D(padding=(2,2),batch_input_shape=(1,width,height,1)))
model.add(Convolution2D(filters=1,kernel_size=(3,3),strides=(1,1),activation='relu',name='conv1_1'))
model.set_weights(sober_weights)

model.add(ZeroPadding2D((1,1)))
model.add(Convolution2D(filters=1,kernel_size=(3,3),strides=(1,1),activation='relu',name='conv1_2'))
model.set_weights(sober_weights)

## 池化操作
model.add(ZeroPadding2D((1,1)))
model.add(MaxPooling2D(pool_size=1,strides=None))

# 优化函数,设定学习率等参数
sgd = SGD(lr=0.01,decay=1e-6,momentum=0.9,nesterov=True)

# 使用mse作为loss函数
model.compile(loss='mse',optimizer=sgd)

# 预测结果
predictresult = model.predict(data,batch_size=1,verbose=0)


squeezeresult = np.squeeze(predictresult)
result = squeezeresult[:179]



figs = np.hstack([array_im,result])
# 显示图片
pylab.imshow(figs)
pylab.show()


你可能感兴趣的:(python)