#目的:Basic classification: Classify images of clothing #1.步驟1:import tensorflow library # TensorFlow and tf.keras import tensorflow as tf # Helper libraries import numpy as np import matplotlib.pyplot as plt print("tensorflow的版本 = ",tf.__version__) #2.步驟2:Import the Fashion MNIST dataset fashion_mnist = tf.keras.datasets.fashion_mnist (train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data() #3.步驟3:These correspond to the class of clothing the image class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot'] #4.步驟4:印出訓練用資料,測試用資料的大小 #there are 60,000 images in the training set, with each image represented as 28 x 28 pixels print("訓練用資料集:圖片(train_images)的陣列大小=",train_images.shape) #print("印出訓練資料樣式名稱(test_labels)資料集的陣列大小=",train_labels.shape) print("訓練用資料集:樣式名稱(test_labels)的陣列大小=",len(train_labels)) print(train_labels) print("測試用資料集:圖片(test_images)的陣列大小=",test_images.shape) print("測試用資料集:樣式名稱(test_labels)的陣列大小=",test_labels.shape) #5.步驟5:畫出訓練用資料的第1個圖片 plt.figure() #打開一張畫紙 plt.imshow(train_images[0]) plt.colorbar() plt.grid(True) #plt.show() #印出第1個圖片的樣式標籤名稱 plt.xlabel(class_names[train_labels[0]]) #6.步驟6:把資料圖片像素的色階由0~255,正規化成0~1 train_images = train_images / 255.0 test_images = test_images / 255.0 #7.步驟7:畫出前面8張圖片 plt.figure(figsize=(2,2)) #打開一張2x2的畫紙 plt.imshow(train_images[1]) plt.xlabel(class_names[train_labels[1]]) plt.figure(figsize=(2,2)) #打開一張2x2的畫紙 plt.imshow(train_images[2]) plt.xlabel(class_names[train_labels[2]]) plt.figure(figsize=(2,2)) #打開一張2x2的畫紙 plt.imshow(train_images[3]) plt.xlabel(class_names[train_labels[3]]) plt.figure(figsize=(2,2)) #打開一張2x2的畫紙 plt.imshow(train_images[4]) plt.xlabel(class_names[train_labels[4]]) #畫出黑白圖(設定cmap參數,cmap意思是color map) #顏色方案, #(1).gray:0-255級灰度,0:黑色,1:白色,黑底白字; #(2).gray_r:翻轉gray的顯示,如果gray將圖像顯示為黑底白字,gray_r 會將其顯示為白底黑字; #(3).binary:binary代表是白底黑字,binary是白→黑(0→1) #(4).bone是黑→白(0→1) #(1).diverging colormaps:兩端發散的色圖 plt.figure(figsize=(2,2)) #打開一張2x2的畫紙 plt.imshow(train_images[5], cmap=plt.cm.binary) plt.xlabel(class_names[train_labels[5]]) plt.figure(figsize=(2,2)) #打開一張2x2的畫紙 plt.imshow(train_images[6], cmap=plt.cm.binary) plt.xlabel(class_names[train_labels[6]]) plt.figure(figsize=(2,2)) #打開一張2x2的畫紙 plt.imshow(train_images[7], cmap=plt.cm.binary) plt.xlabel(class_names[train_labels[7]]) #畫出5x5=25個圖片 plt.figure(figsize=(10,10)) for i in range(25): plt.subplot(5,5,i+1) plt.xticks([]) plt.yticks([]) plt.grid(False) plt.imshow(train_images[i], cmap=plt.cm.binary) plt.xlabel(class_names[train_labels[i]]) plt.show() #8.步驟8:建立類神經網路模型 model = tf.keras.Sequential( [ tf.keras.layers.Flatten(input_shape=[28, 28]), tf.keras.layers.Dense(128, activation='relu'), tf.keras.layers.Dense(10, activation='softmax') ]) #9.步驟9:確立求解的目標函數,設定求解方法: #方法:用keras的model.compile()函數來設定(A.損失函數(loss)、B.優化函數(optimizer),C.成效衡量指標(mertrics) #Loss function —This measures how accurate the model is during training. You want to minimize this function to "steer" the model in the right direction. #Optimizer —This is how the model is updated based on the data it sees and its loss function. #Metrics —Used to monitor the training and testing steps. The following example uses accuracy, the fraction of the images that are correctly classified. model.compile( #第1種寫法:使用參數設定(例如‘adam') #optimizer='adam', #loss = 'sparse_categorical_crossentropy', #metrics=['accuracy'] #第2種寫法:使用物件類別(例如Adam()) optimizer=tf.keras.optimizers.Adam(), loss=tf.keras.losses.SparseCategoricalCrossentropy(), #若是用以下這行會出現錯誤 #metrics=tf.keras.metrics.Accuracy() #要修改成其它物件類別,才能run #metrics=tf.keras.metrics.SparseCategoricalAccuracy() #或是改成這個(但是這些不同參數的設定,都會改變結果的預測,尤其是i=12,sneaker或sandal) metrics=tf.keras.metrics.SparseCategoricalCrossentropy() ) #10.步驟10:訓練模型: #方法:用model.fit()函數進行訓練, model.fit(train_images, train_labels, epochs=10) #11.步驟11:『評估(Evaluation)』該模型的成效 #方法:該模型經過訓練完後,用model.evaluate()函數,針對test_images新的測試數據,來計算其成效分數,以評估模型好壞 #訓練的結果,會傳回test_loss(測試數據的誤差值), test_acc(測試數據的準確率) test_loss, test_acc = model.evaluate(test_images, test_labels, verbose=2) print('\n評估test數據的預測正確度(Test accuracy):', test_acc) #12.步驟12:『預測(Prediction)』新數據x(鞋子圖test_image)所對應的y值(鞋子樣式編號=classifications) #方法:經過反覆訓練,有了可信模型後,用model.predict()函數,針對test_images新的測試數據,來預測對應的y值(鞋子樣式編號=classifications) #注意:鞋子樣式編號=classifications,是一個陣列 pred_classifications = model.predict(test_images) #13.步驟13:給一個測試x數據(test_images[0]),預測其所屬的鞋子樣式編號(pred_classifications[0]) #類神經網路AI對於(第一個)測試樣品的預測(10個樣品中的哪一個?)(向量陣列編號0~9,若是編號9代表短靴) print('類神經網路AI對於(第一個)測試樣品的預測(10個樣品中的哪一個?)=', pred_classifications[0]) #使用np.argmax()函數:傳回最大值索引號 print("預測:第1個測試數據test_images[0]的所預測的產品樣式編號=", np.argmax(pred_classifications[0])) #驗證:印出test_labels[0]是哪種樣式產品編號 print("驗證:第1個test_labels[0]的產品樣式編號=", test_labels[0]) #14.步驟14:第0個物品,畫圖(原始圖 vs 預測結果) plt.figure(figsize=(6,3)) #x寬度6,y高度3 #畫第1個子圖(test圖片) plt.subplot(1,2,1) plt.imshow(test_images[0]) plt.xlabel(class_names[np.argmax(pred_classifications[0])]) #畫第2個子圖(預測的數字圖) plt.subplot(1,2,2) plt.xticks(range(10)) plt.yticks([]) #matplotlib.pyplot.bar(left, height, alpha=1, width=0.8, color=, edgecolor=, label=, lw=3) #matplotlib.pyplot.bar(x, height, width=0.8, bottom=None, *, align='center', data=None, **kwargs) #x = np.array(["A", "B", "C", "D"]) #y = np.array([3, 8, 1, 10]) #plt.bar(x,y) plt.bar(range(10), pred_classifications[0], color="#777777") #ylim:設定y軸刻度最小值及最大值(語法:ylim(ymin,ymax)) plt.ylim([0,1]) #15.步驟15:第12個物品,畫圖(原始圖 vs 預測結果) i=1 plt.figure(figsize=(6,3)) #x寬度6,y高度3 #畫第1個子圖(test圖片) plt.subplot(1,2,1) plt.imshow(test_images[i]) plt.xlabel(class_names[np.argmax(pred_classifications[i])]) print(np.argmax(pred_classifications[i])) #畫第2個子圖(預測的數字圖) plt.subplot(1,2,2) plt.xticks(range(10)) plt.yticks([]) plt.bar(range(10), pred_classifications[i], color="#777777") plt.ylim([0,1]) #印出第2~15個物品 for i in range(2,15): plt.figure(figsize=(6,3)) #x寬度6,y高度3 #畫第1個子圖(test圖片) plt.subplot(1,2,1) plt.imshow(test_images[i]) plt.xlabel(class_names[np.argmax(pred_classifications[i])]) #畫第2個子圖(預測的數字圖) plt.subplot(1,2,2) plt.xticks(range(10)) plt.yticks([]) plt.bar(range(10), pred_classifications[i], color="#777777") plt.ylim([0,1])