1. 程式人生 > >100天專案 Day 6 邏輯迴歸例子

100天專案 Day 6 邏輯迴歸例子

       第四天的時候學習邏輯迴歸可使用sigmod函式做一個比較合理的預測,因為sigmod函式值域範圍恰好為【-1,1】,而且導數比較容易得到。今天就用一個簡單的例子來說明。

       該資料集包含了社交網路中使用者的資訊。這些資訊涉及使用者ID,性別,年齡以及預估薪資。一家汽車公司剛剛推出了他們新型的豪華SUV,我們嘗試預測哪些使用者會購買這種全新SUV。並且在最後一列用來表示使用者是否購買。我們將建立一種模型來預測使用者是否購買這種SUV,該模型基於兩個變數,分別是年齡和預計薪資。因此我們的特徵矩陣將是這兩列。我們嘗試尋找使用者年齡與預估薪資之間的某種相關性,以及他是否購買SUV的決定。

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import warnings
warnings.filterwarnings('ignore')  ##這個是可能涉及版本問題或其他有警告,我加了引數忽略

data = pd.read_csv(r'd:\Users\lulib\Desktop\data.txt',sep='\t')

X = data.iloc[:,[2,3]].values  ##挑出年齡和預計薪資這兩個特徵
Y = data.iloc[:,-1].values     #y 值為最後一列結果值
from sklearn.model_selection import train_test_split   ## 將資料及區分為測試集和訓練集
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size = 0.25, random_state = 0)

from sklearn.preprocessing import StandardScaler   ##特徵縮放
sc = StandardScaler()
X_train = sc.fit_transform(X_train)
X_test = sc.transform(X_test)

## 邏輯迴歸的庫是線性模型庫,也就是說購買和不購買兩類使用者會被一條直線分割,然後匯入邏輯迴歸類。也就是說我們可以先建立邏輯迴歸類,建立的類可以作為我們資料訓練集的分類器。

from sklearn.linear_model import LogisticRegression
classifier = LogisticRegression()
classifier.fit(X_train, y_train)

## 建立並訓練好的類可以用來預測資料
y_pred = classifier.predict(X_test)

## 混淆矩陣可以評估邏輯迴歸模型對我們的訓練集是否有正確的學習和理解
from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test, y_pred)

## 資料視覺化檢驗
from matplotlib.colors import ListedColormap

X_set,y_set=X_train,y_train
X1,X2=np.meshgrid(np.arange(start=X_set[:,0].min()-1, stop=X_set[:, 0].max()+1, step=0.01),
                   np. arange(start=X_set[:,1].min()-1, stop=X_set[:,1].max()+1, step=0.01))
                   
plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(),X2.ravel()]).T).reshape(X1.shape),
             alpha = 0.75, cmap = ListedColormap(('red', 'green')))
             
plt.xlim(X1.min(),X1.max())
def plot1():
    plt.contourf(X1, X2, classifier.predict(np.array([X1.ravel(),X2.ravel()]).T).reshape(X1.shape),
             alpha = 0.75, cmap = ListedColormap(('red', 'green')))
    plt.xlim(X1.min(),X1.max())
    plt.ylim(X2.min(),X2.max())
    for i,j in enumerate(np. unique(y_set)):
        plt.scatter(X_set[y_set==j,0],X_set[y_set==j,1],c = ListedColormap(('red', 'green'))(i), label=j)
    plt. title(' LOGISTIC(Training set)')
    plt. xlabel(' Age')
    plt. ylabel(' Estimated Salary')
    plt. legend()
    plt. show()
    
plot1()