訓練數據識別小貓圖片

import numpy as np
import matplotlib.pyplot as plt
import h5py
import scipy
from PIL import Image
from scipy import ndimage
import lr_utils
from scipy.misc import imread
from numpy import *

def sigmoid(z):#active函數加入非線性因素
    s = 1.0/(1+np.exp(-z))
    return s

def initialize_with_zeros(dim):
    w, b = np.zeros((dim,1)), 0#初始化w爲一維零向量,b爲0

    assert(w.shape == (dim, 1))#判斷w的維數
    assert(isinstance(b, float) or isinstance(b, int))#判斷b的數據類型

    return w, b

def propagate(w, b, X, Y):#反向傳播函數計算梯度下降的w,b導數
    m = X.shape[1]

    A = sigmoid(np.dot(w.T,X)+b)
    cost = -(1/m)*np.sum(Y*np.log(A) + (1-Y)*np.log(1-A))  #成本函數計算預測值和實際值的誤差             

    dw = 1/m*np.dot(X,(A-Y).T)
    db = 1/m*np.sum(A-Y)

    assert(dw.shape == w.shape)
    assert(db.dtype == float)
    cost = np.squeeze(cost)#壓縮函數去掉維數爲1的維
    assert(cost.shape == ())

    grads = {"dw": dw,
             "db": db}

    return grads, cost

def optimize(w, b, X, Y, num_iterations, learning_rate, print_cost = False):#優化函數反覆訓練數據,得到最佳w,b

    costs = []#成本函數數組,存儲每次迭代的成本函數
    for i in range(num_iterations):
        grads, cost = propagate(w, b, X, Y)
        costs.append(cost)

        dw = grads["dw"]
        db = grads["db"]

        w = w - learning_rate*dw#梯度下降不斷接近最佳值
        b = b - learning_rate*db

        if i % 100 == 0:
            costs.append(cost)#每迭代100次存入一次成本函數
        if print_cost and i % 100 == 0:
            print ("Cost after iteration %i: %f" %(i, cost))

    params = {"w": w,
              "b": b}

    grads = {"dw": dw,
             "db": db}

    return params, grads, costs

def predict(w, b, X):#預測函數識別圖片

    m = X.shape[1]
    Y_prediction = np.zeros((1,m))
    w = w.reshape(X.shape[0], 1)

    A =sigmoid(np.dot(w.T,X)+b)

    for i in range(A.shape[1]):#數值轉換成識別結果
        if A[0,i]<=0.5:
            Y_prediction[0,i] = 0
        else:
            Y_prediction[0,i] = 1

    assert(Y_prediction.shape == (1, m))

    return Y_prediction

def model(X_train, Y_train, X_test, Y_test, num_iterations = 2000, learning_rate = 0.5, print_cost = False):#模型函數求整體預測誤差
    w, b = initialize_with_zeros(X_train.shape[0])

    parameters, grads, costs = optimize(w, b, X_train, Y_train, num_iterations, learning_rate, print_cost)

    w = parameters["w"]
    b = parameters["b"]

    Y_prediction_test = predict(w, b, X_test)
    Y_prediction_train = predict(w, b, X_train)

    print("train accuracy: {} %".format(100 - np.mean(np.abs(Y_prediction_train - Y_train)) * 100))
    print("test accuracy: {} %".format(100 - np.mean(np.abs(Y_prediction_test - Y_test)) * 100))

    d = {"costs": costs,
         "Y_prediction_test": Y_prediction_test, 
         "Y_prediction_train" : Y_prediction_train, 
         "w" : w, 
         "b" : b,
         "learning_rate" : learning_rate,
         "num_iterations": num_iterations}

    return d

img = imread('c.jpg')
img2=imread('d.jpg')
img3=imread('e.jpg')
img4=imread('y.jpg')
#把圖片轉換成(num_x,num_x,3)的矩陣

img=img.reshape((img.shape[0]*img.shape[1]*img.shape[2],1))
img2=img.reshape((img2.shape[0]*img2.shape[1]*img2.shape[2],1))
img3=img.reshape((img3.shape[0]*img3.shape[1]*img3.shape[2],1))
img4=img.reshape((img4.shape[0]*img4.shape[1]*img4.shape[2],1))
#轉成(num_x*num_x*3,1)的矩陣

train_set_x=hstack((img,img2,img3,img4))#水平合併四個矩陣
train_set_y=array([[1,1,1,0]])#測試集是(4,1)的矩陣,表示有4個模型,且值爲1,1,1,0

img = imread('f.jpg')
img2=imread('z.jpg')
img=img.reshape((img.shape[0]*img.shape[1]*img.shape[2],1))
img2=img.reshape((img2.shape[0]*img2.shape[1]*img2.shape[2],1))
test_set_x=hstack((img,img2))
test_set_y=array([[1,0]])

learning_rates = [0.01, 0.001, 0.0001]
models = {}
for i in learning_rates:#三種學習速度各運行一次,比較各自的訓練和測試準確度
    print ("learning rate is: " + str(i))
    models[str(i)] = model(train_set_x, train_set_y, test_set_x, test_set_y, num_iterations = 1500, learning_rate = i, print_cost = False)
    print ('\n' + "-------------------------------------------------------" + '\n')

for i in learning_rates:
    plt.plot(np.squeeze(models[str(i)]["costs"]), label= str(models[str(i)]["learning_rate"]))

plt.ylabel('cost')
plt.xlabel('iterations')

legend = plt.legend(loc='upper center', shadow=True)
frame = legend.get_frame()
frame.set_facecolor('0.90')
plt.show()#把學習速度和準確度畫成曲線圖

my_image = "timg.jpg"   # change this to the name of your image file #建立圖片文件存儲圖表

fname = "images/" + my_image
image = np.array(ndimage.imread(fname, flatten=False))
my_image = scipy.misc.imresize(image, size=(num_px,num_px)).reshape((1, num_px*num_px*3)).T
my_predicted_image = predict(d["w"], d["b"], my_image)

plt.imshow(image)
print("y = " + str(np.squeeze(my_predicted_image)) + ", your algorithm predicts a \"" + classes [int(np.squeeze(my_predicted_image)),].decode("utf-8") +  "\" picture.")

訓練集
貓1
貓1
貓2
貓2
貓3
貓3
狗1
狗1

測試集
貓4
貓4
狗2
狗2

採用sigmoid激活函數
計算結果
採用tanh激活函數
這裏寫圖片描述
爲啥三種學習速度的預測準確度沒啥區別?

曲線圖
爲啥沒啥變化。。。

注意:訓練集和測試集的圖片像素必須相同,如果不同,在數據預處理時應該壓縮成相同大小。
是因爲樣本太小嗎,在梯度下降的過程中,我發現w和b的值成週期性變化,所以迭代多少次結果都不變。。
這裏寫圖片描述

發佈了42 篇原創文章 · 獲贊 5 · 訪問量 2萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章