Mnist database: [Link](https://storage.googleapis.com/tensorflow/tf-keras-datasets/mnist.npz) ## 資料前處理 ```python= import tensorflow as tf #import tensorflow.keras import numpy from keras.datasets import mnist (x_train_image,y_train_label),(x_test_image,y_test_label)=mnist.load_data() print('train data= ',len(x_train_image)) print('test data=', len(x_test_image)) # train data= 60000 # test data= 10000 from keras.src import utils # 影像資料------------------------------------- # 代表 train image 總共有6萬張,每一張是28*28的圖片 # label 也有6萬個 # 所以要把二維的圖片矩陣先轉換成一維 # 這裡的784是因為 28*28 x_Train=x_train_image.reshape(60000,784).astype('float32') x_Test=x_test_image.reshape(10000,784).astype('float32') # 由於是圖片最大的是255,所以全部除以255 x_Train_normalize=x_Train/255 x_Test_normalize=x_Test/255 # 標註資料-------------------------------------- y_TrainOneHot=utils.np_utils.to_categorical(y_train_label) y_TestOneHot=utils.np_utils.to_categorical(y_test_label) ``` ## 建立模型 ```python= from keras.models import Sequential from keras.layers import Dense # 建立模型 model = Sequential() # 建立輸入層和隱藏層 model.add(Dense(units=256,input_dim=784,kernel_initializer='normal',activation='selu')) # 定義隱藏層神經元個數256 # 輸入為28*28=784 個float 數字 # 使用 normal distribution 常態分布的亂數,初始化 weight權重 bias 偏差 # 定義激活函數為 relu # 建立輸出層 model.add(Dense(units=10,kernel_initializer='normal',activation='softmax')) # 定義輸出層為10個 (數字0~9) # 也是使用常態分佈初始化 # 定義激活函數是 softmax # 這裡建立的Dense 層,不用設定 input dim ,因為keras 會自動照上一層的256設定 print(model.summary()) model.compile(loss='categorical_crossentropy',optimizer='adam',metrics=['accuracy']) train_history=model.fit(x=x_Train_normalize,y=y_TrainOneHot, validation_split=0.2,epochs=10,batch_size=200,verbose=2) ```