Python机器学习

多项逻辑回归

多项逻辑回归详细操作教程
逻辑回归的另一种有用形式是多项逻辑回归,其中目标或因变量可以具有3种或多种可能的 无序 类型,即没有定量意义的类型。

Python的实现

现在,我们将在Python中实现上述多项式逻辑回归的概念。为此,我们使用来自sklearn的名为 digit 的数据集。
首先,我们需要按如下所示导入必要的库-
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-27
import sklearn
from sklearn import datasets
from sklearn import linear_model
from sklearn import metrics
from sklearn.model_selection import train_test_split
接下来,我们需要加载数字数据集-
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-27
digits = datasets.load_digits()
现在,如下定义特征矩阵(X)和响应向量(y)-
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-27
X = digits.data
y = digits.target
借助下一行代码,我们可以将X和y分为训练和测试集-
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-27
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.4, random_state = 1)
现在创建如下的逻辑回归对象-
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-27
digreg = linear_model.LogisticRegression()
现在,我们需要使用如下训练集来训练模型-
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-27
digreg.fit(X_train, y_train)
接下来,对测试集进行如下预测-
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-27
y_pred = digreg.predict(X_test)
接下来按如下所示打印模型的精度-
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-27
print("Accuracy of Logistic Regression model is:",
metrics.accuracy_score(y_test, y_pred)*100)

输出

# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-27
Accuracy of Logistic Regression model is: 95.6884561891516
从上面的输出中,我们可以看到我们模型的准确性约为96%。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4