深度學習——學習筆記(1)神經網路基礎
阿新 • • 發佈:2020-12-25
# -*- coding: utf-8 -*- # @Time : 2020/12/25 16:30 # @Author : Renlele # @File : 2_1.py # @Software: Pycharm def func1(): # 載入資料集 from keras.datasets import mnist (train_images, train_labels), (test_images, test_labels) = mnist.load_data() print(train_images.shape) # (60000, 28, 28) print(train_labels) # [5 0 4 ... 5 6 8] # 檢視資料型別 print(train_images.dtype) # uint8 print(test_images.shape) # (10000, 28, 28) print(test_labels) # [7 2 1 ... 4 5 6] # 使用matplotlib庫顯示數字 import matplotlib.pyplot as plt digit = train_images[4] plt.imshow(digit,cmap = plt.cm.binary) plt.show() from keras import models from keras import layers network = models.Sequential() # Dense層 全連線 network.add(layers.Dense(512, activation='relu', input_shape=(28 * 28,))) network.add(layers.Dense(10, activation='softmax')) # 編譯 # categorical_crossentropy 損失函式,學習權重張量的反饋訊號,應使他最小化 # rmsprop 優化器 network.compile(optimizer='rmsprop', loss='categorical_crossentropy', metrics=['accuracy']) # 準備影象資料 train_images = train_images.reshape((60000, 28 * 28)) train_images = train_images.astype('float32') / 255 test_images = test_images.reshape((10000, 28 * 28)) test_images = test_images.astype('float32') / 255 # 準備標籤 from keras.utils import to_categorical train_labels = to_categorical(train_labels) test_labels = to_categorical(test_labels) # 呼叫fit方法完成在訓練資料上的擬合 network.fit(train_images, train_labels, epochs=5, batch_size=128) # output # Epoch 1/5 # 469/469 [==============================] - 4s 8ms/step - loss: 0.2580 - accuracy: 0.9250 # Epoch 2/5 # 469/469 [==============================] - 3s 7ms/step - loss: 0.1039 - accuracy: 0.9697 # Epoch 3/5 # 469/469 [==============================] - 3s 7ms/step - loss: 0.0688 - accuracy: 0.9794 # Epoch 4/5 # 469/469 [==============================] - 4s 8ms/step - loss: 0.0497 - accuracy: 0.9855 # Epoch 5/5 # 469/469 [==============================] - 4s 8ms/step - loss: 0.0380 - accuracy: 0.9887 # 檢查在測試集上的效能 test_loss, test_acc = network.evaluate(test_images, test_labels) print('test_acc:', test_acc) def func2(): import numpy as np # 0D張量 x = np.array(12) print(x) # 12 print(x.ndim) # 0 # 1D張量 == 向量 x = np.array([12, 3, 6, 14, 7]) print(x) # [12 3 6 14 7] print(x.ndim) # 1 # 矩陣(2D張量) 行與列 x = np.array([[5, 78, 2, 34, 0], [6, 79, 3, 35, 1], [7, 80, 4, 36, 2]]) print(x) # [[ 5 78 2 34 0] [ 6 79 3 35 1] [ 7 80 4 36 2]] print(x.ndim) # 2 # 3D張量 x = np.array([[[5, 78, 2, 34, 0], [6, 79, 3, 35, 1], [7, 80, 4, 36, 2]], [[5, 78, 2, 34, 0], [6, 79, 3, 35, 1], [7, 80, 4, 36, 2]], [[5, 78, 2, 34, 0], [6, 79, 3, 35, 1], [7, 80, 4, 36, 2]] ]) print(x.ndim) # 3