ML Day6逻辑回归

机器学习100天,每天进步一点点。跟着GitHub开始学习!

英文项目地址https://github.com/Avik-Jain/100-Days-Of-ML-Code

中文项目地址https://github.com/MLEveryday/100-Days-Of-ML-Code


逻辑回归被用来处理不同的分类问题,使用基础逻辑函数通过估算概率来测量因变量和一个或者多个自变量之间的关系。概率值需转换为二进制数,以便实际中进行预测。这是逻辑函数的任务,也被称为sigmoid函数。然后使用阈值分类器将(0,1)范围的值转化成0和1的值来表示结果。

Sigmoid函数是一个S型曲线,可将任意真实值映射为值域范围为0-1的值。

逻辑回归VS线性回归:

逻辑回归给出离散的输出结果,线性回归给出连续的输出结果。

数据集|社交网络

该数据集包含了社交网络中用户的信息。这些信息涉及用户ID,性别,年龄以及预估薪资。一家汽车公司刚刚推出了他们新型的豪华SUV,我们尝试预测哪些用户会购买这种全新SUV。并且在最后一列用来表示用户是否购买。我们将建立一种模型来预测用户是否购买这种SUV,该模型基于两个变量,分别是年龄和预计薪资。因此我们的特征矩阵将是这两列。我们尝试寻找用户年龄与预估薪资之间的某种相关性,以及他是否购买SUV的决定。

逻辑回归的处理步骤:

1 数据预处理

导入库、导入数据集、将数据集分为训练集和测试集、特征缩放

2 逻辑回归模型

将逻辑回归应用于训练集

3 预测

预测测试集结果

4 评估预测

生成混淆矩阵、可视化

混淆矩阵confusion matrix),又称为可能性表格或是错误矩阵。它是一种特定的矩阵用来呈现算法性能的效果,通常用于监督学习。

classification_report函数在报告中显示每个类的精确度/召回率/F1值。

精确度/召回率/F1值

如下图所示,假设有若干张图片,其中12张是狗的图片其余是猫的图片。现在利用程序去识别狗的图片,结果在识别出的8张图片中有5张是狗的图片,3张是猫的图片。

图中,实心小圆代表狗的图片,虚心小圆代表猫的图片,圆形区域代表识别结果。则该程序的精度precision=5/8,召回率recall=5/12。

F1值是精确度和召回率的调和平均值。精确度和召回率都高时,F1值也会高。F1值最佳为1,最差为0。

代码:

# Importing the Libraries
import numpy as np  #包含数学计算函数
import matplotlib.pyplot as plt
import pandas as pd  #用于导入和管理数据集

# Importing the dataset
dataset = pd.read_csv('../datasets/Social_Network_Ads.csv')
X = dataset.iloc[:, [2, 3]].values  #iloc是取矩阵的某行某列
y = dataset.iloc[:, 4].values

# Splitting the dataset into the Training set and Test set
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)

# Feature Scaling
from sklearn.preprocessing import StandardScaler
sc = StandardScaler()  #针对某一特征维度进行标准化,经处理后的数据符合标准正态分布,均值为0,标准差为1
X_train = sc.fit_transform(X_train)  
X_test = sc.transform(X_test)

# Fitting Logistic Regression to the Training set
from sklearn.linear_model import LogisticRegression
classifier = LogisticRegression()
classifier.fit(X_train, y_train)

# Predicting the Test set results
y_pred = classifier.predict(X_test)

# Making the Confusion Matrix
from sklearn.metrics import confusion_matrix
from sklearn.metrics import classification_report
cm = confusion_matrix(y_test, y_pred)  #生成混淆矩阵
print(cm)  # print confusion_matrix
print(classification_report(y_test, y_pred))   # print classification report,在报告中显示每个类的精确度,召回率,F1值等信息。

#Visualization
from matplotlib.colors import ListedColormap
X_set,y_set=X_train,y_train
#X,Y=np. meshgrid(x,y):输入的x,y是网格点的横纵坐标列向量,输出的X,Y是坐标矩阵
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))
#contourf绘制等高线
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)):
    #scatter绘制散点图
    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()

X_set,y_set=X_test,y_test
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())
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(Test set)')
plt. xlabel(' Age')
plt. ylabel(' Estimated Salary')
plt. legend()
plt. show()

结果:

猜你喜欢

转载自blog.csdn.net/weixin_40277254/article/details/86239636
ML