首页 > 其他分享 >机器学习 实验二

机器学习 实验二

时间:2024-12-31 12:20:47浏览次数:1  
标签:iris 机器 train 学习 print score 实验 test model

from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split, cross_validate
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import make_scorer, accuracy_score, precision_score, recall_score, f1_score, classification_report

# (1) 从 scikit-learn 库中加载 iris 数据集,使用留出法留出 1/3 的样本作为测试集(注意同分布取样)
# 加载数据集
iris = load_iris()
X, y = iris.data, iris.target

# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=1/3, random_state=42, stratify=y)

# (2) 使用训练集训练对数几率回归(逻辑回归)分类算法
# 创建逻辑回归模型实例
model = LogisticRegression(solver='lbfgs', max_iter=200)

# 训练模型
model.fit(X_train, y_train)

# (3) 使用五折交叉验证对模型性能(准确度、精度、召回率和 F1 值)进行评估和选择
# 定义多个评分器
scoring = {
    'accuracy': make_scorer(accuracy_score),
    'precision': make_scorer(precision_score, average='weighted'),
    'recall': make_scorer(recall_score, average='weighted'),
    'f1': make_scorer(f1_score, average='weighted')
}

# 使用交叉验证评估模型
scores = cross_validate(model, X_train, y_train, cv=5, scoring=scoring)

# 输出各项指标的平均值
print("五折交叉验证结果:")
for key in scores:
    if key.startswith('test_'):
        print(f"{key[5:]}: {scores[key].mean():.4f}")  # 去掉前缀 'test_' 来显示指标名称

# (4) 使用测试集,测试模型的性能,对测试结果进行分析,完成实验报告中实验二的部分
# 预测测试集标签
y_pred = model.predict(X_test)

# 打印分类报告
report = classification_report(y_test, y_pred, target_names=iris.target_names, output_dict=True)
print("\n测试集上的分类报告:")
for label, metrics in report.items():
    if isinstance(metrics, dict):
        print(f"类别 {label}:")
        for metric, value in metrics.items():
            print(f"  {metric}: {value:.4f}")
    else:
        print(f"{label}: {value:.4f}")

# 打印混淆矩阵
from sklearn.metrics import confusion_matrix
conf_matrix = confusion_matrix(y_test, y_pred)
print("\n混淆矩阵:")
print(conf_matrix)

  

标签:iris,机器,train,学习,print,score,实验,test,model
From: https://www.cnblogs.com/youxiandechilun/p/18643697

相关文章

  • 机器学习 实验一
    #导入必要的库importpandasaspdfromsklearn.datasetsimportload_irisfromsklearn.model_selectionimportcross_val_score,KFold,cross_val_predictfromsklearn.linear_modelimportLogisticRegressionfromsklearn.metricsimportclassification_report#(......
  • 机器学习 实验三
    #导入必要的库importmatplotlib.pyplotaspltfromsklearn.datasetsimportload_irisfromsklearn.model_selectionimporttrain_test_split,cross_val_score,cross_validatefromsklearn.treeimportDecisionTreeClassifierfromsklearn.metricsimportaccuracy_s......
  • 机器学习 实验五
    #导入必要的库fromsklearn.datasetsimportload_irisfromsklearn.model_selectionimporttrain_test_split,cross_val_scorefromsklearn.neural_networkimportMLPClassifierfromsklearn.metricsimportaccuracy_score,precision_score,recall_score,f1_scorei......
  • 机器学习 实验四
    importnumpyasnpfromsklearn.datasetsimportload_irisfromsklearn.model_selectionimporttrain_test_split,cross_val_score,KFoldfromsklearn.treeimportDecisionTreeClassifierfromsklearn.metricsimportaccuracy_score,precision_score,recall_scor......
  • 机器学习 实验七
    #导入必要的库fromsklearnimportdatasetsfromsklearn.model_selectionimporttrain_test_splitfromsklearn.clusterimportKMeansfromsklearn.metricsimportsilhouette_score,accuracy_score,adjusted_rand_scoreimportnumpyasnp#(1)加载数据集并划分数据......
  • 机器学习 实验六
    #导入必要的库fromsklearnimportdatasetsfromsklearn.model_selectionimporttrain_test_split,cross_validatefromsklearn.naive_bayesimportGaussianNBfromsklearn.metricsimportaccuracy_score,precision_score,recall_score,f1_scoreimportnumpyasnp......
  • 机器学习 实验八
    #导入必要的库fromsklearnimportdatasetsfromsklearn.model_selectionimporttrain_test_split,cross_validatefromsklearn.ensembleimportRandomForestClassifierfromsklearn.metricsimportaccuracy_score,precision_score,recall_score,f1_scoreimportnu......
  • 飞书lark机器人 自动化发版
    飞书lark机器人自动化发版#1介绍开发飞书机器人接收消息并调用构建接口,实现自动化发版发送指令->机器人接收指令->调用jenkins-job远程构建与部署jenkins配置,勾选job配置的触发远程构建并设置身份验证令牌#测试触发远程构建curl-ks-uuser:user_token-......
  • 学习 lambda
    JavaLambda表达式|菜鸟教程(runoob.com)根据菜鸟教程学习Lambda表达式概述定义:Lambda表达式是Java8引入的一个特性,它允许开发者以更加简洁和紧凑的方式编写匿名类的替代品。它们通常用于实现函数式接口(即只有一个抽象方法的接口)。语法:(parameters)->expressio......
  • 学习 stream 流
    Java8引入了StreamAPI,这是一个处理集合数据的强大工具,它允许你以声明式的方式对数据进行各种操作,如过滤、映射、排序、归约等。Stream不存储数据,而是像管道一样传输和转换数据元素。你可以将Stream看作是高级迭代器,它提供了一种更抽象的方式来遍历和操作数据集。Stream的......