代码拉取完成,页面将自动刷新
# 导入所需的库
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score
# 读取数据集
url = "https://raw.githubusercontent.com/MicrosoftDocs/mslearn-introduction-to-machine-learning/main/Data/ml-basics/penguins.csv"
df = pd.read_csv(url)
# 打印前五行数据
print(df.head())
# 显示包含缺失值的行
print("\nRows with missing values:")
print(df[df.isnull().any(axis=1)])
# 删除含有缺失值的行
df_clean = df.dropna()
# 用条形图可视化企鹅种类的分布
sns.countplot(x='Species', data=df_clean)
plt.title('Distribution of Penguin Species')
plt.show()
# 用箱线图可视化 FlipperLength, CulmenLength 和 CulmenDepth 的分布
plt.figure(figsize=(15,5))
plt.subplot(1, 3, 1)
sns.boxplot(x='Species', y='FlipperLength', data=df_clean)
plt.title('Flipper Length Distribution by Species')
plt.subplot(1, 3, 2)
sns.boxplot(x='Species', y='CulmenLength', data=df_clean)
plt.title('Culmen Length Distribution by Species')
plt.subplot(1, 3, 3)
sns.boxplot(x='Species', y='CulmenDepth', data=df_clean)
plt.title('Culmen Depth Distribution by Species')
plt.tight_layout()
plt.show()
# 准备训练模型:将数据分为特征和标签
X = df_clean[['CulmenLength', 'CulmenDepth', 'FlipperLength']] # 特征
y = df_clean['Species'] # 标签
# 将数据划分为训练集和测试集,30%的数据用于测试
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
# 创建多分类的逻辑回归模型并训练
model = LogisticRegression(multi_class='multinomial', solver='lbfgs', max_iter=200)
model.fit(X_train, y_train)
# 预测测试集的标签
y_pred = model.predict(X_test)
# 计算模型的准确率
accuracy = accuracy_score(y_test, y_pred)
print(f"Model accuracy: {accuracy * 100:.2f}%")
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。