練習keras的卷積神經網路

2021-09-19 06:48:30 字數 1842 閱讀 6464

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()

卷積神經網路 Keras 由淺入深

python mathematics 卷積神經網路能夠有效的處理影象檔案,當然換一種說法就是能夠有效處理矩陣。其關鍵部分就是 卷積核 過濾器 的生成。當然還有一些其他的基礎操作。對於卷積核 卷積核的特徵 init filters,kernel size,strides 1 1 padding val...

keras卷積神經網路舉例

特徵圖深度在增加 從32到128,但尺寸在變小 from keras import layers from keras import model 輸入尺寸為150 150 3,展平後是7 7 128 model model.sequential 二維卷積核 提取的圖塊大小 一般3 3 9個特徵向量,...

Keras實現卷積神經網路

1 coding utf 8 2 3created on sun jan 20 11 25 29 201945 author zhen 6 78 import numpy as np 9from keras.datasets import mnist 10from keras.models impo...