keras 的使用例子
生活随笔
收集整理的這篇文章主要介紹了
keras 的使用例子
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
keras 搭建簡單模型
扁平化model.add(Flatten()) 可以用? 全局平均池化代替?model.add(GlobalAveragePooling2D())
方法1
# 序列模型 # 序列模型屬于通用模型的一種,因為很常見,所以這里單獨列出來進行介紹,這種模型各層之間 # 是依次順序的線性關系,在第k層和第k+1層之間可以加上各種元素來構造神經網絡 # 這些元素可以通過一個列表來制定,然后作為參數傳遞給序列模型來生成相應的模型from keras.models import Sequential from keras.layers import Dense from keras.layers import Activation# Dense相當于構建一個全連接層,32指的是全連接層上面神經元的個數 layers = [Dense(32, input_shape=(784,)),Activation('relu'),Dense(10),Activation('softmax')] model = Sequential(layers)#輸出模型結構 model.summary()
方法2?
效果同方法1一樣
from keras.models import Sequential from keras.layers import Dense from keras.layers import Activationmodel = Sequential() model.add(Dense(32, input_shape=(784,))) model.add(Activation('relu')) model.add(Dense(10)) model.add(Activation('softmax')) model.summary()?
一個稍復雜的例子
# 通用模型 # 通用模型可以用來設計非常復雜、任意拓撲結構的神經網絡,例如有向無環圖網絡 # 類似于序列模型,通用模型通過函數化的應用接口來定義模型 # 使用函數化的應用接口有好多好處,比如:決定函數執行結果的唯一要素是其返回值,而決定 # 返回值的唯一要素則是其參數,這大大減輕了代碼測試的工作量# 在通用模型中,定義的時候,從輸入的多維矩陣開始,然后定義各層及其要素,最后定義輸出層 # 將輸入層和輸出層作為參數納入通用模型中就可以定義一個模型對象from keras.layers import Input from keras.layers import Dense from keras.models import Model# 定義輸入層 input = Input(shape=(784,)) # 定義各個連接層,假設從輸入層開始,定義兩個隱含層,都有64個神經元,都使用relu激活函數 x = Dense(64, activation='relu')(input) x = Dense(64, activation='relu')(x) # 定義輸出層,使用最近的隱含層作為參數 y = Dense(10, activation='softmax')(x)# 所有要素都齊備以后,就可以定義模型對象了,參數很簡單,分別是輸入和輸出,其中包含了 # 中間的各種信息 model = Model(inputs=input, outputs=y)# 當模型對象定義完成之后,就可以進行編譯了,并對數據進行擬合,擬合的時候也有兩個參數 # 分別對應于輸入和輸出 model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy']) model.fit(data, labels)?
一個更加復雜的例子
import numpy as np from keras.datasets import mnist from keras.models import Sequential from keras.layers import Dense from keras.layers import Dropout from keras.layers import Flatten from keras.layers.convolutional import Conv2D from keras.layers.convolutional import MaxPooling2D# 先讀入數據 (X_train, y_train), (X_test, y_test) = mnist.load_data("../test_data_home") # 看一下數據集的樣子 print(X_train[0].shape) print(y_train[0])# 下面把訓練集中的手寫黑白字體變成標準的四維張量形式,即(樣本數量,長,寬,1) # 并把像素值變成浮點格式 X_train = X_train.reshape(X_train.shape[0], 28, 28, 1).astype('float32') X_test = X_test.reshape(X_test.shape[0], 28, 28, 1).astype('float32')# 由于每個像素值都介于0到255,所以這里統一除以255,把像素值控制在0-1范圍 X_train /= 255 X_test /= 255# 由于輸入層需要10個節點,所以最好把目標數字0-9做成One Hot編碼的形式 def tran_y(y):y_ohe = np.zeros(10)y_ohe[y] = 1return y_ohe# 把標簽用One Hot編碼重新表示一下 y_train_ohe = np.array([tran_y(y_train[i]) for i in range(len(y_train))]) y_test_ohe = np.array([tran_y(y_test[i]) for i in range(len(y_test))])# 搭建卷積神經網絡 model = Sequential() # 添加一層卷積層,構造64個過濾器,每個過濾器覆蓋范圍是3*3*1 # 過濾器步長為1,圖像四周補一圈0,并用relu進行非線性變化 model.add(Conv2D(filters=64, kernel_size=(3, 3), strides=(1, 1), padding='same',input_shape=(28, 28, 1), activation='relu')) # 添加一層最大池化層 model.add(MaxPooling2D(pool_size=(2, 2))) # 設立Dropout層,Dropout的概率為0.5 model.add(Dropout(0.5))# 重復構造,搭建深度網絡 model.add(Conv2D(128, kernel_size=(3, 3), strides=(1, 1), padding='same',activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.5)) model.add(Conv2D(256, kernel_size=(3, 3), strides=(1, 1), padding='same',activation='relu')) model.add(MaxPooling2D(pool_size=(2, 2))) model.add(Dropout(0.5))# 把當前層節點展平 model.add(Flatten())# 構造全連接層神經網絡層 model.add(Dense(128, activation='relu')) model.add(Dense(64, activation='relu')) model.add(Dense(32, activation='relu')) model.add(Dense(10, activation='softmax'))# 定義損失函數,一般來說分類問題的損失函數都選擇采用交叉熵 model.compile(loss='categorical_crossentropy', optimizer='adagrad', metrics=['accuracy'])# 放入批量樣本,進行訓練 model.fit(X_train, y_train_ohe, validation_data=(X_test, y_test_ohe), epochs=20, batch_size=128)# 在測試集上評價模型的準確率 # verbose : 進度表示方式。0表示不顯示數據,1表示顯示進度條 scores = model.evaluate(X_test, y_test_ohe, verbose=0)?
遷移學習的例子
# 使用遷移學習的思想,以VGG16作為模板搭建模型,訓練識別手寫字體 # 引入VGG16模塊 from keras.applications.vgg16 import VGG16# 其次加載其他模塊 from keras.layers import Input from keras.layers import Flatten from keras.layers import Dense from keras.layers import Dropout from keras.models import Model from keras.optimizers import SGD# 加載字體庫作為訓練樣本 from keras.datasets import mnist# 加載OpenCV(在命令行中窗口中輸入pip install opencv-python),這里為了后期對圖像的處理, # 大家使用pip install C:\Users\28542\Downloads\opencv_python-3.4.1+contrib-cp35-cp35m-win_amd64.whl # 比如尺寸變化和Channel變化。這些變化是為了使圖像滿足VGG16所需要的輸入格式 import cv2 import h5py as h5py import numpy as np# 建立一個模型,其類型是Keras的Model類對象,我們構建的模型會將VGG16頂層去掉,只保留其余的網絡 # 結構。這里用include_top = False表明我們遷移除頂層以外的其余網絡結構到自己的模型中(意思是頂層不用) # weights='imagenet'使用imagenet大賽第一名的參數。 # VGG模型對于輸入圖像數據要求高寬至少為48個像素點,由于硬件配置限制,我們選用48個像素點而不是原來 # VGG16所采用的224個像素點。即使這樣仍然需要24GB以上的內存,或者使用數據生成器 model_vgg = VGG16(include_top=False, weights='imagenet', input_shape=(48, 48, 3)) for layer in model_vgg.layers:#遍歷vgg模型的每一層layer.trainable = False #每層的,參數都設置為不可變更的,使用初始參數 model = Flatten(name='flatten')(model_vgg.output) # 扁平化,將vgg模型的輸出。當做自己模型的輸入 model = Dense(4096, activation='relu', name='fc1')(model) model = Dense(4096, activation='relu', name='fc2')(model) model = Dropout(0.5)(model) model = Dense(10, activation='softmax')(model) model_vgg_mnist = Model(inputs=model_vgg.input, outputs=model, name='vgg16')# 打印模型結構,包括所需要的參數 model_vgg_mnist.summary()model_vgg = VGG16(include_top=False, weights='imagenet', input_shape=(224, 224, 3)) for layer in model_vgg.layers:layer.trainable = False model = Flatten()(model_vgg.output) model = Dense(4096, activation='relu', name='fc1')(model) model = Dense(4096, activation='relu', name='fc2')(model) model = Dropout(0.5)(model) model = Dense(10, activation='softmax', name='prediction')(model) model_vgg_mnist_pretrain = Model(model_vgg.input, model, name='vgg16_pretrain')model_vgg_mnist_pretrain.summary()# 新的模型不需要訓練原有卷積結構里面的1471萬個參數,但是注意參數還是來自于最后輸出層前的兩個 # 全連接層,一共有1.2億個參數需要訓練 sgd = SGD(lr=0.05, decay=1e-5) #sgd 隨機梯度下降法,作為優化器 model_vgg_mnist.compile(loss='categorical_crossentropy',optimizer=sgd, metrics=['accuracy'])# 因為VGG16對網絡輸入層的要求,我們用OpenCV把圖像從32*32變成48*48,函數cv2.COLOR_GRAY2RGB 把黑白圖像轉成RGB圖像 # 并把訓練數據轉化成張量形式,供keras輸入 (X_train, y_train), (X_test, y_test) = mnist.load_data("../test_data_home") X_train, y_train = X_train[:10000], y_train[:10000] X_test, y_test = X_test[:1000], y_test[:1000] X_train = [cv2.cvtColor(cv2.resize(i, (48, 48)), cv2.COLOR_GRAY2RGB)for i in X_train] X_train = np.concatenate([arr[np.newaxis] for arr in X_train]).astype('float32') X_test = [cv2.cvtColor(cv2.resize(i, (48, 48)), cv2.COLOR_GRAY2RGB)for i in X_test] X_test = np.concatenate([arr[np.newaxis] for arr in X_test]).astype('float32')print(X_train.shape) print(X_test.shape)X_train = X_train / 255 X_test = X_test / 255def tran_y(y):y_ohe = np.zeros(10)y_ohe[y] = 1return y_ohey_train_ohe = np.array([tran_y(y_train[i]) for i in range(len(y_train))]) y_test_ohe = np.array([tran_y(y_test[i]) for i in range(len(y_test))])model_vgg_mnist.fit(X_train, y_train_ohe, validation_data=(X_test, y_test_ohe),epochs=100, batch_size=50)?
轉載于:https://www.cnblogs.com/HL-blog/p/9437461.html
總結
以上是生活随笔為你收集整理的keras 的使用例子的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 多个Spring Boot项目部署在一个
- 下一篇: 我的python渗透测试工具箱之自制ne