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()

猜你喜欢

转载自blog.csdn.net/li9669/article/details/85537715
今日推荐