W3School TIY Editor

  • W3School 在线教程
  • 改变方向
  • 暗黑模式
​x
 
from sklearn import datasets
from sklearn.linear_model import LogisticRegression
​
# 加载鸢尾花数据集:
iris = datasets.load_iris()
​
# 准备特征数据和目标标签:
X = iris['data']  # 特征矩阵
y = iris['target']  # 类别标签
​
# 创建逻辑回归模型(增加最大迭代次数确保收敛):
logit = LogisticRegression(max_iter=10000)
​
# 定义要测试的正则化强度参数 C 的候选值:
C = [0.25, 0.5, 0.75, 1, 1.25, 1.5, 1.75, 2]
​
scores = []  # 存储不同 C 值对应的模型准确率
​
for choice in C:
    # 设置当前 C 值并训练模型
    logit.set_params(C=choice)
    logit.fit(X, y)
    # 记录模型在训练集上的准确率
    scores.append(logit.score(X, y))
    
# 输出不同 C 值对应的准确率:
print(scores)