基于企鹅数据集的决策树实战

基于企鹅数据集的决策树实战

实践要求:导入基础的函数库包括:numpy(Python进行科学计算的基础软件包),pandas(pandas是一种快速,强大,灵活且易于使用的开源数据分析和处理工具),matplotlib和seaborn绘图。

数据集下载地址:
https://tianchi-media.oss-cn-beijing.aliyuncs.com/DSW/6tree/penguins_raw.csv

实践步骤:

Step1:库函数导入
import numpy as np
import pandas as pd
import matplotlib as plt
import seaborn as sns
Step2:数据读取/载入
data = pd.read_csv(open(r'D:\算法作业\penguins_raw.csv'))
Step3:数据信息简单查看
>>>print(data.info())

微信图片_20211118131753.png

data = data.fillna(-1)# 将缺失值补全
## 利用value_counts函数查看每个类别数量
print(pd.Series(data['Species']).value_counts())

微信图片_20211118131914.png

Step4:可视化描述

仅从数据集中选择了几个特征

data = data[['Species','Culmen Length (mm)','Culmen Depth (mm)',
            'Flipper Length (mm)','Body Mass (g)']]
sns.pairplot(data=data, diag_kind='hist', hue= 'Species')
plt.show()

1.png

#   将分类变量转化成数字变量,方便后续计算
def translate(x):
    if x == data['Species'].unique()[0]:
        return 0
    if x == data['Species'].unique()[1]:
        return 1
    if x == data['Species'].unique()[2]:
        return 2


data['Species'] = data['Species'].apply(translate)

for col in data.columns:
    if col != 'Species':
        sns.boxplot(x='Species', y=col, saturation=0.5, palette='pastel', data=data)
        plt.title(col)
        plt.show()

c_1.png
c_2.png
c_3.png
c_4.png

Step5:利用决策树模型在二分类上进行训练和预测
data_target_part = data[data['Species'].isin([0,1])][['Species']]
data_features_part = data[data['Species'].isin([0,1])][['Culmen Length (mm)','Culmen Depth (mm)','Flipper Length (mm)','Body Mass (g)']]
from sklearn.model_selection import train_test_split
from sklearn import metrics


# 为了正确评估模型性能,将数据划分为训练集和测试集,并在训练集上训练模型,在测试集上验证模型性能。
x_train, x_test, y_train, y_test = train_test_split(data_features_part,data_target_part,test_size=0.2,random_state=2020)
# 导入决策树模型
from sklearn.tree import DecisionTreeClassifier
from sklearn import tree
## 定义 决策树模型
clf = DecisionTreeClassifier(criterion='entropy')# 信息熵,根据信息增益来划分
# 在训练集上训练clf模型
clf.fit(x_train, y_train)

## 在训练集和测试集上分别利用训练好的模型进行预测
train_predict = clf.predict(x_train)
test_predict = clf.predict(x_test)

## 利用accuracy(准确度)【预测正确的样本数目占总预测样本数目的比例】评估模型效果
print('准确度:', metrics.accuracy_score(y_train, train_predict))
print('准确度:', metrics.accuracy_score(y_test, test_predict))
## 查看混淆矩阵
confusion_matrix_result = metrics.confusion_matrix(test_predict, y_test)
print('混淆矩阵结果:\n', confusion_matrix_result)

plt.figure(figsize=(8, 6))  # 指定figure的宽和高,单位为英寸
sns.heatmap(confusion_matrix_result, annot=True, cmap='Blues')
plt.xlabel('Predictedlabels')
plt.ylabel('Truelabels')
plt.show()

准确度: 0.9954545454545455
准确度: 1.0

2f.png

Step6:利用决策树模型在三分类(多分类)上进行训练和预测
## 测试集大小为20%, 80%/20%分
x_train, x_test, y_train, y_test = train_test_split(data[['Culmen Length (mm)', 'Culmen Depth (mm)',
                                                          'Flipper Length (mm)', 'Body Mass (g)']], data[['Species']],
                                                    test_size=0.2, random_state=2020)
## 定义 决策树模型
clf = DecisionTreeClassifier(criterion='entropy')
# 在训练集上训练决策树模型
clf.fit(x_train, y_train)

## 在训练集和测试集上分别利用训练好的模型进行预测
train_predict = clf.predict(x_train)
test_predict = clf.predict(x_test)

## 利用accuracy(准确度)【预测正确的样本数目占总预测样本数目的比例】评估模型效果
print('准确度:', metrics.accuracy_score(y_train, train_predict))
print('准确度:', metrics.accuracy_score(y_test, test_predict))
## 查看混淆矩阵
confusion_matrix_result = metrics.confusion_matrix(test_predict, y_test)
print('混淆矩阵结果:\n', confusion_matrix_result)

准确度: 0.9963636363636363
逻辑回归准确度: 0.9710144927536232
3f.png

  • 7
    点赞
  • 43
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
抱歉,我不清楚您具体需要哪方面的深度学习代码。帕尔默企鹅数据集主要用于分类问题,可以使用多种深度学习模型进行训练和测试,如卷积神经网络(CNN)、循环神经网络(RNN)和转移学习等。以下是一个使用 CNN 模型的 Python 代码示例,用于对帕尔默企鹅数据集进行分类: ```python import tensorflow as tf from tensorflow.keras import layers, models, optimizers from sklearn.model_selection import train_test_split import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt # 加载数据集 penguins = sns.load_dataset("penguins") # 数据预处理 penguins.dropna(inplace=True) penguins.drop(columns=["island", "sex"], inplace=True) penguins["species"] = pd.Categorical(penguins["species"]).codes # 划分训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(penguins.drop(columns=["species"]), penguins["species"], test_size=0.2, random_state=42) # 构建 CNN 模型 model = models.Sequential([ layers.Conv2D(32, (3, 3), activation='relu', input_shape=(X_train.shape[1], X_train.shape[2], 1)), layers.MaxPooling2D((2, 2)), layers.Flatten(), layers.Dense(64, activation='relu'), layers.Dense(3, activation='softmax') ]) # 编译模型 model.compile(optimizer=optimizers.Adam(learning_rate=0.001), loss='sparse_categorical_crossentropy', metrics=['accuracy']) # 训练模型 history = model.fit(X_train.values.reshape(-1, X_train.shape[1], X_train.shape[2], 1), y_train.values, epochs=50, validation_data=(X_test.values.reshape(-1, X_test.shape[1], X_test.shape[2], 1), y_test.values)) # 可视化训练过程 plt.plot(history.history['accuracy'], label='accuracy') plt.plot(history.history['val_accuracy'], label = 'val_accuracy') plt.xlabel('Epoch') plt.ylabel('Accuracy') plt.legend() plt.show() # 评估模型 test_loss, test_acc = model.evaluate(X_test.values.reshape(-1, X_test.shape[1], X_test.shape[2], 1), y_test.values, verbose=2) print("Test accuracy:", test_acc) ``` 在这个示例中,我们使用卷积神经网络(CNN)模型对帕尔默企鹅数据集进行分类。首先加载数据集并进行预处理,然后将数据集分为训练集和测试集。接着构建并编译 CNN 模型,训练模型并评估模型性能。最后,我们可视化训练过程并输出测试准确率。需要注意的是,这只是一个简单的示例,您可以根据具体情况进行修改和优化。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值