机器学习 | 机器学习100天(4) --- 逻辑回归

机器学习100天系列学习笔记基于机器学习100天(中文翻译版),机器学习100天(英文原版)

所有代码使用iPython Notebook实现

完整代码

实验综述

数据集

1.数据预处理

'''1. 导入相关库'''
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
%matplotlib inline

'''2. 导入数据集'''
data = pd.read_csv('Social_Network_Ads.csv')
print(data.head())
#分离特征矩阵X和标签向量Y
X = data.iloc[:,2:-1].values #只使用年龄和预估薪资两个特征
Y = data.iloc[:,-1].values

'''3. 检查缺失数据'''
#没有缺失数据

'''4. 解析分类数据'''
#没有分类数据 不需要数字化/转化one-hot编码

'''5. 避免虚拟变量陷阱'''
#没有虚拟变量

'''6. 分割数据集为训练集和测试集'''
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)

'''7. 特征缩放'''
from sklearn.preprocessing import StandardScaler
#实例化StandardScaler类的对象
sc = StandardScaler()
#用对象调用类内的特征缩放方法
X_train = sc.fit_transform(X_train)
X_test = sc.fit_transform(X_test)

2.逻辑回归模型

#导入逻辑回归类
from sklearn.linear_model import LogisticRegression
#实例化逻辑回归类的对象
classifier = LogisticRegression()
#用该对象调用类中的fit()方法 在训练集上训练逻辑回归模型
classifier = classifier.fit(X_train,Y_train) #或classifier.fit(X_train,Y_train) 

3.预测

使用训练好的模型在测试集上进行预测。

y_pred = classifier.predict(X_test)

4.评估预测

#生成混淆矩阵
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())
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()

#可视化测试集
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()

猜你喜欢

转载自blog.csdn.net/sdu_hao/article/details/86438076