1. 程式人生 > >機器學習----線性迴歸原理---最下二乘法和梯度下降怎麼來的-----專案預測大學生是否被錄取程式碼案例

機器學習----線性迴歸原理---最下二乘法和梯度下降怎麼來的-----專案預測大學生是否被錄取程式碼案例

 

這節課說明了 最下二乘法  是怎麼來的。

 

接下來是面試需要問的

誤差,(機器學習是建立在獨立同分布的基礎上,事實上,根本無法證明獨立同分布而且是正態分佈,我們假設的,只要模型可用,就可以

獨立:   每個人的誤差是獨立同分布的,如何不獨立那就說明有關係了,黑關係,不能考慮這個,

同分布:假定是同一家銀行,如果不是同一家銀行,不成立。

高斯分佈:就是正態分佈  大塊面積處在-1 ,1 之間。

 

 

 

 

 

似然函式(就是根據資料樣本預測引數值的),這裡就是讓我的預測值與接近真實值,換句話說誤差的可能性越小越好

 

接下來推到最下二乘法:(矩陣求導怎麼做?)

 

梯度下降法:

 

 

 

 

ligistic regression

現實中,往往先拿邏輯迴歸試試效果怎樣,在去試試其他的演算法,優先選擇的演算法、

 

 

 

大學生按成績是否被錄取案例,程式碼分析

 

'''



'''
# %matplotlib inline     :表示在notebook中不需要plt.show()即可顯示影象,在pycharm中不行,報錯

pdData = pd.read_csv('LogiReg_data.txt', header=None, names=['Exam 1', 'Exam 2', 'Admitted'])
'''
我們發現讀取這個的檔案,第一行竟然是資料,沒有列名,因此讓header=none,自己指定列名
names=['Exam 1', 'Exam 2', 'Admitted'],第三列位標籤項,1:錄取;0:沒有被錄取

'''
positive = pdData[pdData['Admitted'] == 1]
negative = pdData[pdData['Admitted'] == 0]
'''
pdData['Admitted'] == 1   :表示返回一個100x1的矩陣,元素為true或者false
positive = pdData[pdData['Admitted'] == 1]  :則是讓true為索引的行全部拿出來
negative 同理

'''
fig, ax = plt.subplots(figsize=(10,5))
ax.scatter(positive['Exam 1'], positive['Exam 2'], s=30, c='b', marker='o', label='Admitted')
'''
subplots:建立一個子圖,大小(10,5),接下來畫錄取和沒有被錄取的散點圖,做好標記

'''
def model(X, theta):
    return sigmoid(np.dot(X, theta.T))

'''
np.dot(X, theta.T)  X:為100x3 的矩陣,theta為1x3的矩陣,沒毛病

'''
pdData.insert(0, 'Ones', 1)
'''
在第一列的前面插上一列,列名為one   值為1
'''

orig_data = pdData.as_matrix() # convert the Pandas representation of the data to an array useful for further computations
cols = orig_data.shape[1]
X = orig_data[:,0:cols-1]
y = orig_data[:,cols-1:cols]
'''
他這麼寫,感覺太麻煩了不就是把x和y分離嗎,
'''
def cost(X, y, theta):
    left = np.multiply(-y, np.log(model(X, theta)))
    right = np.multiply(1 - y, np.log(1 - model(X, theta)))
    return np.sum(left - right) / (len(X))
'''
multiply(a,b)就是個乘法,如果a,b是兩個陣列,那麼對應元素相乘

'''
def gradient(X, y, theta):
    grad = np.zeros(theta.shape)  #1x3的矩陣
    error = (model(X, theta) - y).ravel()
    for j in range(len(theta.ravel())):  # for each parmeter
        term = np.multiply(error, X[:, j])
        grad[0, j] = np.sum(term) / len(X)
'''
我們要求 theta的偏導數,這裡面有三個theta,因此求三個
j :代表每一列

----------------------------------------------------------
>>> x.ravel()
array([1, 2, 3, 4])
                    兩者預設均是行序優先
>>> x.flatten('F')
array([1, 3, 2, 4])
>>> x.ravel('F')
array([1, 3, 2, 4])
---------------------------------------------------------------
np.sum(term) #這裡term是矩陣怎麼求和呢,預設是把矩陣所有元素相加
np.sum   和Python自帶的sum不一樣,真可氣
np.sum(X,axis=1) 每一行相加 axis=0就是縱向相加

'''
def descent(data, theta, batchSize, stopType, thresh, alpha):
    # 梯度下降求解

    init_time = time.time()
    i = 0  # 迭代次數
    k = 0  # batch
    X, y = shuffleData(data)
    grad = np.zeros(theta.shape)  # 計算的梯度
    costs = [cost(X, y, theta)]  # 損失值
    while True:
        grad = gradient(X[k:k + batchSize], y[k:k + batchSize], theta)
        k += batchSize  # 取batch數量個數據
        if k >= n:
            k = 0
            X, y = shuffleData(data)  # 重新洗牌
        theta = theta - alpha * grad  # 引數更新
        costs.append(cost(X, y, theta))  # 計算新的損失
        i += 1

        if stopType == STOP_ITER:
            value = i
        elif stopType == STOP_COST:
            value = costs
        elif stopType == STOP_GRAD:
            value = grad
        if stopCriterion(stopType, value, thresh): break

    return theta, i - 1, costs, grad, time.time() - init_time
'''
核心程式碼就這
theta, iter, costs, grad, dur = descent(data, theta, batchSize, stopType, thresh, alpha)

其他都是修飾
'''
def runExpe(data, theta, batchSize, stopType, thresh, alpha):
    #import pdb; pdb.set_trace();
    theta, iter, costs, grad, dur = descent(data, theta, batchSize, stopType, thresh, alpha)


    name = "Original" if (data[:,1]>2).sum() > 1 else "Scaled"
    name += " data - learning rate: {} - ".format(alpha)
    if batchSize==n: strDescType = "Gradient"
    elif batchSize==1:  strDescType = "Stochastic"
    else: strDescType = "Mini-batch ({})".format(batchSize)
    name += strDescType + " descent - Stop: "
    if stopType == STOP_ITER: strStop = "{} iterations".format(thresh)
    elif stopType == STOP_COST: strStop = "costs change < {}".format(thresh)
    else: strStop = "gradient norm < {}".format(thresh)
    name += strStop
    print ("***{}\nTheta: {} - Iter: {} - Last cost: {:03.2f} - Duration: {:03.2f}s".format(
        name, theta, iter, costs[-1], dur))

    #--------------------------上面是列印結果,下面是畫圖
    fig, ax = plt.subplots(figsize=(12,4))
    ax.plot(np.arange(len(costs)), costs, 'r')
    ax.set_xlabel('Iterations')
    ax.set_ylabel('Cost')
    ax.set_title(name.upper() + ' - Error vs. Iteration')
    plt.show()
    return theta
'''
開始執行程式

'''
n=100
runExpe(orig_data, theta, n, STOP_ITER, thresh=5000, alpha=0.000001)


# runExpe(orig_data, theta, n, STOP_COST, thresh=0.000001, alpha=0.001)
# runExpe(orig_data, theta, n, STOP_GRAD, thresh=0.05, alpha=0.001)
# runExpe(orig_data, theta, 1, STOP_ITER, thresh=5000, alpha=0.001)
# runExpe(orig_data, theta, 1, STOP_ITER, thresh=15000, alpha=0.000002)
# runExpe(orig_data, theta, 16, STOP_ITER, thresh=15000, alpha=0.001)

全部程式碼

 

'''’
我們將建立一個邏輯迴歸模型來預測一個學生是否被大學錄取。
假設你是一個大學系的管理員,
你想根據兩次考試的結果來決定每個申請人的錄取機會。
你有以前的申請人的歷史資料,
你可以用它作為邏輯迴歸的訓練集。對於每一個培訓例子,
你有兩個考試的申請人的分數和錄取決定。為了做到這一點,
我們將建立一個分類模型,根據考試成績估計入學概率

'''


import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# %matplotlib inline

import os
path = 'data' + os.sep + 'LogiReg_data.txt'
pdData = pd.read_csv('LogiReg_data.txt', header=None, names=['Exam 1', 'Exam 2', 'Admitted'])
# print(pdData.shape)
# pdData.head()

positive = pdData[pdData['Admitted'] == 1] # returns the subset of rows such Admitted = 1, i.e. the set of *positive* examples
negative = pdData[pdData['Admitted'] == 0] # returns the subset of rows such Admitted = 0, i.e. the set of *negative* examples

fig, ax = plt.subplots(figsize=(10,5))
ax.scatter(positive['Exam 1'], positive['Exam 2'], s=30, c='b', marker='o', label='Admitted')
ax.scatter(negative['Exam 1'], negative['Exam 2'], s=30, c='r', marker='x', label='Not Admitted')
ax.legend()
ax.set_xlabel('Exam 1 Score')
ax.set_ylabel('Exam 2 Score')
# plt.show()


def sigmoid(z):
    return 1 / (1 + np.exp(-z))

nums = np.arange(-10, 10, step=1) #creates a vector containing 20 equally spaced values from -10 to 10
fig, ax = plt.subplots(figsize=(12,4))
ax.plot(nums, sigmoid(nums), 'r')


def model(X, theta):
    return sigmoid(np.dot(X, theta.T))


pdData.insert(0, 'Ones', 1) # in a try / except structure so as not to return an error if the block si executed several times


# set X (training data) and y (target variable)
orig_data = pdData.as_matrix() # convert the Pandas representation of the data to an array useful for further computations
cols = orig_data.shape[1]
X = orig_data[:,0:cols-1]
y = orig_data[:,cols-1:cols]

# convert to numpy arrays and initalize the parameter array theta
#X = np.matrix(X.values)
#y = np.matrix(data.iloc[:,3:4].values) #np.array(y.values)
theta = np.zeros([1, 3])


def cost(X, y, theta):
    left = np.multiply(-y, np.log(model(X, theta)))
    right = np.multiply(1 - y, np.log(1 - model(X, theta)))
    return np.sum(left - right) / (len(X))
print(X,y,theta)

def gradient(X, y, theta):
    grad = np.zeros(theta.shape)
    error = (model(X, theta) - y).ravel()
    for j in range(len(theta.ravel())):  # for each parmeter
        term = np.multiply(error, X[:, j])
        grad[0, j] = np.sum(term) / len(X)

    return grad

STOP_ITER = 0
STOP_COST = 1
STOP_GRAD = 2
def stopCriterion(type, value, threshold):
    #設定三種不同的停止策略
    if type == STOP_ITER:        return value > threshold
    elif type == STOP_COST:      return abs(value[-1]-value[-2]) < threshold
    elif type == STOP_GRAD:      return np.linalg.norm(value) < threshold

import numpy.random
#洗牌
def shuffleData(data):
    np.random.shuffle(data)
    cols = data.shape[1]
    X = data[:, 0:cols-1]
    y = data[:, cols-1:]
    return X, y


import time


def descent(data, theta, batchSize, stopType, thresh, alpha):
    # 梯度下降求解

    init_time = time.time()
    i = 0  # 迭代次數
    k = 0  # batch
    X, y = shuffleData(data)
    grad = np.zeros(theta.shape)  # 計算的梯度
    costs = [cost(X, y, theta)]  # 損失值
    while True:
        grad = gradient(X[k:k + batchSize], y[k:k + batchSize], theta)
        k += batchSize  # 取batch數量個數據
        if k >= n:
            k = 0
            X, y = shuffleData(data)  # 重新洗牌
        theta = theta - alpha * grad  # 引數更新
        costs.append(cost(X, y, theta))  # 計算新的損失
        i += 1

        if stopType == STOP_ITER:
            value = i
        elif stopType == STOP_COST:
            value = costs
        elif stopType == STOP_GRAD:
            value = grad
        if stopCriterion(stopType, value, thresh): break

    return theta, i - 1, costs, grad, time.time() - init_time


def runExpe(data, theta, batchSize, stopType, thresh, alpha):
    #import pdb; pdb.set_trace();
    theta, iter, costs, grad, dur = descent(data, theta, batchSize, stopType, thresh, alpha)


    name = "Original" if (data[:,1]>2).sum() > 1 else "Scaled"
    name += " data - learning rate: {} - ".format(alpha)
    if batchSize==n: strDescType = "Gradient"
    elif batchSize==1:  strDescType = "Stochastic"
    else: strDescType = "Mini-batch ({})".format(batchSize)
    name += strDescType + " descent - Stop: "
    if stopType == STOP_ITER: strStop = "{} iterations".format(thresh)
    elif stopType == STOP_COST: strStop = "costs change < {}".format(thresh)
    else: strStop = "gradient norm < {}".format(thresh)
    name += strStop
    print ("***{}\nTheta: {} - Iter: {} - Last cost: {:03.2f} - Duration: {:03.2f}s".format(
        name, theta, iter, costs[-1], dur))

    #--------------------------上面是列印結果,下面是畫圖
    fig, ax = plt.subplots(figsize=(12,4))
    ax.plot(np.arange(len(costs)), costs, 'r')
    ax.set_xlabel('Iterations')
    ax.set_ylabel('Cost')
    ax.set_title(name.upper() + ' - Error vs. Iteration')
    plt.show()
    return theta
n=100
runExpe(orig_data, theta, n, STOP_ITER, thresh=5000, alpha=0.000001)


# runExpe(orig_data, theta, n, STOP_COST, thresh=0.000001, alpha=0.001)
# runExpe(orig_data, theta, n, STOP_GRAD, thresh=0.05, alpha=0.001)
# runExpe(orig_data, theta, 1, STOP_ITER, thresh=5000, alpha=0.001)
# runExpe(orig_data, theta, 1, STOP_ITER, thresh=15000, alpha=0.000002)
# runExpe(orig_data, theta, 16, STOP_ITER, thresh=15000, alpha=0.001)
#