視頻學習來源
https://www.bilibili.com/video/av40787141?from=search&seid=17003307842787199553
筆記
首先安裝pydot
conda install pydot
會自動安裝graphviz
如果出現TypeError: softmax() got an unexpected keyword argument 'axis' 錯誤,可降級keras或者用本文代碼標黃的部分解決
切換cpu和gpu運算
https://www.cnblogs.com/jins-note/p/9756050.html
conda安裝keras-gpu (conda會自動查詢依賴安裝需要的相關包,如TensorFlow)
(如果環境出現問題,用conda移除相關包,重新安裝keras-gpu即可)
在導入keras前,插入代碼
import os os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" # The GPU id to use, usually either "0" or "1" os.environ["CUDA_VISIBLE_DEVICES"] = "0" #使用gpu os.environ["CUDA_VISIBLE_DEVICES"] = "-1" #為使用CPU
import numpy as np from keras.datasets import mnist #將會從網絡下載mnist數據集 from keras.utils import np_utils from keras.models import Sequential #序列模型 #Convolution2D 是2維卷積 #MaxPooling2D 是2維最大池化 #Flatten 數據扁平化(降維) from keras.layers import Dense,Dropout,Convolution2D,MaxPooling2D,Flatten #在這里導入dropout from keras.optimizers import Adam from keras.utils.vis_utils import plot_model import matplotlib.pyplot as plt import tensorflow as tf #需要安裝pydot和graphviz #graphviz需要在官網安裝,安裝后需要添加環境變量,程序所在目錄的bin文件夾加入系統變量
#載入數據 (x_train,y_train),(x_test,y_test)=mnist.load_data() #查看格式 #(60000,28,28) print('x_shape:',x_train.shape) #(60000) print('y_shape:',y_train.shape) #轉化為4維 #最后一個維度圖片深度,1表示黑白,3表示彩色 #rgb是紅綠藍三通道0-255表示各個通道的顏色深度 #(60000,28,28)->(60000,28,28,1) #-1表示自動設置 #除以255是做數據歸一化處理 x_train=x_train.reshape(-1,28,28,1)/255.0 #轉換數據格式 x_test=x_test.reshape(-1,28,28,1)/255.0 #轉換數據格式 #label標簽轉換成 one hot 形式 y_train=np_utils.to_categorical(y_train,num_classes=10) #分成10類 y_test=np_utils.to_categorical(y_test,num_classes=10) #分成10類 #定義序列模型 model=Sequential() #第一個卷積層 #input_shape 輸入平面 #filters 卷積核/濾波器個數 #kernel_size 卷積窗口大小 #strides 步長 #padding padding方式 same/valid #activation 激活函數 model.add(Convolution2D( input_shape=(28,28,1),#只需要在第一次添加輸入平面 filters=32, kernel_size=5, strides=1, padding='same', activation='relu' )) #平面大小28x28,用same padding得到的和上一次一樣,也是28x28,有32個特征圖 #池化后變成14x14,32個特征圖 #第一個池化層 model.add(MaxPooling2D( pool_size=2, # 池化窗口大小 2x2的窗口 strides=2, padding='same' )) #第二個卷積層 #filters=64 kernel_seize=5 model.add(Convolution2D(64,5,strides=1,padding='same',activation='relu')) #第二個卷積層后64個特征圖,14x14 #第二個池化層后64個特征圖,7x7 #第二個池化層 model.add(MaxPooling2D(2,2,'same')) #把第二個池化層的輸出扁平化為1維 #長度 64x7x7 model.add(Flatten()) #第一個全連接層 #1024個神經元 model.add(Dense(1024,activation='relu')) #Dropout #訓練時百分之40個神經元不工作 model.add(Dropout(0.4)) #第二個全連接層 model.add(Dense(10,activation=(tf.nn.softmax))) ##定義優化器 ##學習速率為10的負4次方 #adam=Adam(lr=1e-4) # # ##定義優化器,損失函數,訓練效果中計算准確率 #model.compile( # optimizer=adam, #sgd優化器 # loss='categorical_crossentropy', #損失用交叉熵,速度會更快 # metrics=['accuracy'], #計算准確率 #) # ##訓練 ##六萬張,每次訓練64張,訓練10個周期(六萬張全部訓練完算一個周期) #model.fit(x_train,y_train,batch_size=64,epochs=10) # ##評估模型 #loss,accuracy=model.evaluate(x_test,y_test) # #print('\ntest loss',loss) #print('\ntest accuracy',accuracy) # #loss,accuracy=model.evaluate(x_train,y_train) # #print('\ntrain loss',loss) #print('\ntrain accuracy',accuracy)
#TB代表從上往下,LR表示從左往右 plot_model(model,to_file='model.png',show_shapes=True,show_layer_names='False',rankdir='TB') plt.figure(figsize=(20,20)) img=plt.imread('model.png') plt.imshow(img) plt.axis('off') plt.show()