美文网首页机器学习
逻辑回归实现-Python

逻辑回归实现-Python

作者: 灵妍 | 来源:发表于2018-03-01 20:07 被阅读86次
1、数据预处理

这里的案例是根据用户的年龄和收入预测该用户是否会购买该产品。
步骤如下:
导入标准库-导入数据集-确定因变量和自变量-划分训练集和测试集-将自变量标准化
注意:由于因变量是分类数据,不需要标准化。
代码:

# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

# Importing the dataset
dataset = pd.read_csv('Social_Network_Ads.csv')
X = dataset.iloc[:, 2:4].values
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_X = StandardScaler()
X_train = sc_X.fit_transform(X_train)
X_test = sc_X.transform(X_test)
2、拟合逻辑回归模型

步骤如下:
导入线性模型中的逻辑回归类-创建逻辑回归对象-利用训练集拟合逻辑回归对象
代码:

#fitting logistic regression to the Training set
from sklearn.linear_model import LogisticRegression
classifier=LogisticRegression(random_state=0)
classifier.fit(X_train,y_train)
3、预测因变量

利用拟合好的逻辑回归模型中的predict()函数预测测试集。
代码:

#predicting the test set results
y_pred=classifier.predict(X_test)
4、得到测试集的预测结果与真实结果的对比(混淆矩阵)
混淆矩阵结果.png

代码:

#make the confusion matrix
from sklearn.metrics import confusion_matrix
cm=confusion_matrix(y_test,y_pred)
5、可视化模型

得到的模性可视化后的分界线是一条直线,直线两边的区域分别代表购买以及不购买,不同颜色的散点代表训练集或测试集的购买情况,横坐标代表年龄,纵坐标代表收入。
模型的绘制主要指通过像素点描色,具体步骤如下:
得到平面上的点坐标-得到点坐标的预测结果-绘制模型-绘制散点图


模型-测试集.png 模型-训练集.png
#visualing the train set results
# Visualising the Training set results
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(('orange', 'blue'))(i), label = j)
plt.title('Logistic Regression (Training set)')
plt.xlabel('Age')
plt.ylabel('Estimated Salary')
plt.legend()
plt.show()

# Visualising the Test set results
from matplotlib.colors import ListedColormap
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(('orange', 'blue'))(i), label = j)
plt.title('Logistic Regression (Test set)')
plt.xlabel('Age')
plt.ylabel('Estimated Salary')
plt.legend()
plt.show()

相关文章

  • 案例

    Python实现逻辑回归(Logistic Regression in Python)http://www.pow...

  • 机器学习之逻辑回归

    逻辑回归 场景简介:使用逻辑回归实现对鸢尾花的分类预测。基于python基本库的实现 模型说明 逻辑回归是一个分类...

  • python实现逻辑回归

    逻辑回归是一种常见的分类算法,通常用来处理二分类问题。逻辑回归名字中带有回归两个字,却用于处理分类问题,是因为逻辑...

  • 逻辑回归实现-Python

    1、数据预处理 这里的案例是根据用户的年龄和收入预测该用户是否会购买该产品。步骤如下:导入标准库-导入数据集-确定...

  • python实现逻辑回归

    定义逻辑回归算法:logRegression.py 调用算法:use_logRegression.py 附部分数据...

  • 逻辑回归python实现

    参考文章:https://blog.csdn.net/bitcarmanlee/article/details/5...

  • 2018-10-20

    Python与数据挖掘(二)——逻辑回归 2、算法实现 import pandas as pdfrom sklea...

  • 2018-10-19

    Python与数据挖掘(二)——逻辑回归 逻辑回归一般用来实现分类 一、算法原理 1、预测函数 2、将预测函数的输...

  • python完整实现逻辑回归

    数据我们将建立一个逻辑回归模型来预测一个学生是否被大学录取。假设你是一个大学系的管理员,你想根据两次考试的结果来决...

  • 逻辑回归以及python实现

    https://mp.weixin.qq.com/s/3knhQddJW8uZsEEiJxRM9Q

网友评论

    本文标题:逻辑回归实现-Python

    本文链接:https://www.haomeiwen.com/subject/irenxftx.html