邏輯回歸 鳶尾花資料集

2021-08-29 20:17:12 字數 4092 閱讀 6948

import numpy as np

import pandas as pd

data = pd.read_csv("iris.csv")

#去掉不需要的列

data.drop("id",axis=1,inplace=true)

data.drop_duplicates(inplace=true)

#實現對映操作

data['species'] = data['species'].map()

#對資料進行篩選,只選取型別為0,1的資料,進行邏輯回歸二分類

data = data[data['species'] != 2]

data

class logisticregression:

"""使用python實現邏輯回歸演算法"""

def __init__(self,alpha,times):

"""初始化方法:

parameters:

----

alpah:float

學習率times : int

迭代次數

"""self.alpha = alpha

self.times = times

def sigmoid(self,z):

"""sigmoid函式的實現

parameters:

----

z: float

自變數,值為:z = w.t * x

return:

----

result:float,值為[0,1]之間

返回樣本屬於類別一的概率值,用於結果的**

當s > 0.5(z>=0)時,判定為類別一,否則判定為類別0

"""return 1.0 / (1.0 + np.exp(-z))

def fit(self, x, y):

"""根據訓練資料,對模型進行訓練

parameters:

----

x : 類陣列型別,形狀[樣本數量,特徵數量]

待訓練的樣本的特徵屬性

y : 類陣列型別。形狀為[樣本數量]

每個樣本的目標值(標籤)

"""#將x,y轉換成ndarray陣列

x = np.asarray(x)

y = np.asarray(y)

#初始化權重,初始值為0,長度比特徵數多1,多出來的乙個為截距

self.w_ = np.zeros(1 + x.shape[1])

#建立損失列表,用來儲存每次迭代後的損失值

self.loss_ =

for i in range(self.times):

z = np.dot(x,self.w_[1:]) + self.w_[0]

#計算概率值(判定結果一的概率值)

p = self.sigmoid(z)

#損失值,根據邏輯回歸的目標函式,計算損失值。

#目標函式:j(w) = - sum(yi * log(s(zi)) + (1-yi) * log(1-s(zi)))【i從1到n】

cost = -np.sum((y * np.log(p)) + (1 - y) * np.log(1-p))

#更新權重,公式:權重(j) = 權重(j) + 學習率 * sum((y - s(zi))* xj)

self.w_[0] += self.w_[0] + self.alpha * np.sum(y - p)

self.w_[1:] += self.w_[1:] + self.alpha * np.dot(x.t,y-p)

def predict_proba(self,x):

"""根據引數傳遞的樣本,對樣本資料進行**

parameters

-----

x:類陣列型別,形狀為[樣本數量,樣本特徵數量]

待測試樣本的屬性特徵

return

----

result:陣列型別

**的結果(概率值)

"""x = np.asarray(x)

z = np.dot(x,self.w_[1:]) + self.w_[0]

p = self.sigmoid(z)

#將**結果轉換成二維結構

p = p.reshape(-1,1)

#將兩個資料進行拼接

return np.concatenate([1-p,p],axis=1)

def predict(self,x):

"""根據引數傳遞的樣本,對樣本資料進行**

parameters:

----

x:類陣列型別,形狀[樣本數量,特徵數量]

待測試的樣本特徵(屬性)

returns:

-----

result: 陣列型別

**結果(分類值)

"""return np.argmax(self.predict_proba(x),axis = 1)

#構建測試集與訓練街

t0 = data[data['species'] == 0]

t1 = data[data['species'] == 1]

t0 = t0.sample(len(t0),random_state = 0)

t1 = t1.sample(len(t1),random_state = 0)

train_x = pd.concat([t0.iloc[:40,:-1],t1.iloc[:40,:-1]],axis = 0)

train_y = pd.concat([t0.iloc[:40,-1],t1.iloc[:40,-1]],axis = 0)

test_x = pd.concat([t0.iloc[40:,:-1],t1.iloc[40:,:-1]],axis = 0)

test_y = pd.concat([t0.iloc[40:,-1],t1.iloc[40:,-1]],axis = 0)

#鳶尾花特徵列都在同乙個數量級,這裡可以不用標準化處理

lr = logisticregression(alpha=0.01,times=20)

lr.fit(train_x,train_y)

#**概率值

display(lr.predict_proba(test_x))

#類別**

result = lr.predict(test_x)

display(result)

#計算準確性

np.sum(result == test_y) / len(test_x)

#對計算結果進行視覺化展示

import matplotlib as mpl

import matplotlib.pyplot as plt

#設定matplotlib 支援中文顯示

mpl.rcparams['font.family'] = 'simhei' #設定字型為黑體

mpl.rcparams['axes.unicode_minus'] = false #設定在中文字型是能夠正常顯示負號(「-」)

#設定畫布大小

plt.figure(figsize=(8,8))

#繪製**值

plt.plot(result,"ro",ms = 15,label="**值")

plt.plot(test_y.values,"go",label="真實值")

plt.title("邏輯回歸")

plt.xlabel("樣本序號")

plt.ylabel("類別")

#繪製目標函式損失值

邏輯回歸 鳶尾花資料調包

from sklearn.model selection import train test split from sklearn.linear model import logisticregression from sklearn import datasets 匯入資料 iris datase...

鳶尾花資料集

from sklearn import datasets iris datasets.load iris iris是乙個字典集keys iris.keys dict keys data target target names descr feature names data iris.data.sh...

鳶尾花 Iris 資料集

2.pandas庫基礎操作 3.資料視覺化 tf.keras.utils.get file fname,origin,cache dir 引數 說明fname origin 檔案的url位址 cache dir train url train path tf.keras.utils.get file...