上課的時候的一個實驗,閑得無聊把3維的線性回歸矩陣化,以便以后可以對幾百幾千維的資料也可以使用該演算法(雖然直接sklearn更快),但畢竟是手搓出來的用起來好玩一點點,
線性回歸原理如下(原理很簡單,字是鬼畫符,不看也罷):

注:這里只是回歸,不是分類,多分類的問題的話需要訓練多組引數W和b,用softmax進行分類,其結構就類似沒有隱藏層只有輸出層的神經網路,這里就懶得弄了,
鳶尾花資料集鏈接如下:
鏈接:https://pan.baidu.com/s/1Lm5oKDfnnFGvWycuF9D1PA
提取碼:1234
具體代碼如下,注釋有詳細介紹:
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.preprocessing import LabelEncoder # 處理鳶尾花資料的
def compute_error(b, W, points):
'''
計算損失,這里采用簡單的(y-y^hat)**2這一損失函式
:param b: 偏差b,一個標量,
:param W: 形狀是(n, 1),對應鳶尾花資料集的話是(4, 1)
:param points:
:return:
'''
total_error = 0
# 遍歷每一個資料集,計算總損失
for i in range(0, len(points)):
X = points[i:i + 1, 0:4].T # X的維度是(4, 1)
y = points[i, 4]
total_error += (y - (np.dot(W.T, X)[0, 0]+b))**2
# 平均損失
return total_error / float(len(points))
def gradient(b_current, W_current, points, learning_rate):
'''
梯度下降演算法
:param b_current: 上一步的b
:param W_current: 上一步的W,形狀是(4, 1)
:param points: 傳入的資料集矩陣
:param learning_rate: 學習率
:return:new_b, new_W
'''
b_gradient = 0
W_gradient = np.zeros((4, 1))
cnt = float(len(points))
for i in range(0, len(points)):
X = points[i:i+1, 0:-1].T # shape: (4, 1)
y = points[i, -1] # y是個標量
# 損失函式(y-y^hat)**2對標量b和向量W求偏導得它們的梯度
b_gradient += (2 / cnt) * ((np.dot(W_current.T, X)[0, 0] + b_current) - y)
W_gradient += (2 / cnt) * ((np.dot(W_current.T, X)[0, 0]+b_current)-y) * X
# 梯度下降發更新引數
new_W = W_current - (learning_rate * W_gradient)
new_b = b_current - (learning_rate * b_gradient)
return new_b, new_W
def lr(points, starting_b, starting_W, learning_rate, num_iterations):
'''
線性回歸模型
:param points:
:param starting_b: 1個標量
:param starting_W: W引數向量,這里shape是(4, 1)
:param learning_rate:學習率
:param num_iterations:迭代次數
:return:
'''
b = starting_b
W = starting_W
# update for several times
for i in range(num_iterations):
b, W = gradient(b, W, np.array(points), learning_rate)
print('第{}次 損失:{}'.format(i+1, compute_error(b, W, points)))
return b, W
def main():
# 處理資料
df_data = pd.read_csv('Iris.csv')
non_numeric_features = ["Species"]
for feature in non_numeric_features:
df_data[feature] = LabelEncoder().fit_transform(df_data[feature])
x = df_data.iloc[:, 1:5]
y = df_data.iloc[:, 5:]
print(type(x))
points = np.hstack((x, y)) # points是鳶尾花資料集,其shape:(n, 5),最后一列是標簽y
# print(points)
x_shape = points[:, :-1].shape # (n, 特征數),這里是(n, 4)
learning_rate = 0.001
initial_b = 2 # 初始化b引數shape (4, 1)
initial_W = np.zeros((x_shape[1], 1)) # 初始化W引數shape (4, 1)
num_iterations = 1000
print("Running...")
b, W = lr(points, initial_b, initial_W, learning_rate, num_iterations)
print('最終損失:{}'.format(compute_error(b, W, points)))
if __name__ == '__main__':
main()
OKK!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/302963.html
標籤:AI
上一篇:貝葉斯定理簡單理解
