利用linear_model.LogisticRegression()对scikit-learn中的自带数据集iris,再利用train_test_split将样本的test_size作为测试集进行分类与预测,最后输出score(X_test, y_test)
时间: 2024-10-29 11:19:49 浏览: 11
scikit_learn-1.0.2-cp37-cp37m-win_amd64.zip
首先,我们需要导入所需的库并加载Iris数据集。在scikit-learn中,`LogisticRegression`用于二元逻辑回归任务,而`train_test_split`则用于拆分数据集为训练集和测试集。
```python
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
# 加载Iris数据集
iris = datasets.load_iris()
X = iris.data # 特征
y = iris.target # 类别标签
# 划分训练集和测试集,test_size表示保留比例,默认0.25
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)
# 创建Logistic Regression模型
logreg = LogisticRegression()
# 训练模型
logreg.fit(X_train, y_train)
# 预测测试集
y_pred = logreg.predict(X_test)
# 计算准确率得分
score = accuracy_score(y_test, y_pred)
print("模型在测试集上的准确率为:", score)
阅读全文