pythonstudy Day24

复习日

@疏锦行



c 复制代码
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.ensemble import RandomForestClassifier

# 1. 读入数据(注意路径:Kaggle Notebook 里直接就是 /kaggle/input/...)
train = pd.read_csv("/kaggle/input/titanic/train.csv")
test = pd.read_csv("/kaggle/input/titanic/test.csv")

# 2. 简单特征工程
# 选择一些比较有用的特征
features = ["Pclass", "Sex", "Age", "SibSp", "Parch", "Fare", "Embarked"]

train = train[features + ["Survived"]]
test_features = test[features]

# 处理缺失值
# Age 和 Fare 用中位数填充,Embarked 用众数填充
for df in [train, test_features]:
    df["Age"].fillna(df["Age"].median(), inplace=True)
    df["Fare"].fillna(df["Fare"].median(), inplace=True)
    df["Embarked"].fillna(df["Embarked"].mode()[0], inplace=True)

# 把 Sex 和 Embarked 变成数字(one-hot 编码)
train = pd.get_dummies(train, columns=["Sex", "Embarked"])
test_features = pd.get_dummies(test_features, columns=["Sex", "Embarked"])

# 对齐列(避免测试集缺某些 dummy 列)
test_features = test_features.reindex(columns=train.drop("Survived", axis=1).columns, fill_value=0)

X = train.drop("Survived", axis=1)
y = train["Survived"]

# 3. 划分一部分训练集做本地验证(可选)
X_train, X_valid, y_train, y_valid = train_test_split(X, y, test_size=0.2, random_state=42)

# 4. 训练模型(随机森林只是示例,其他模型也可以)
model = RandomForestClassifier(
    n_estimators=200,
    max_depth=5,
    random_state=42
)
model.fit(X_train, y_train)

# 在验证集上看一下效果(仅自我检查)
y_pred_valid = model.predict(X_valid)
print("Validation accuracy:", accuracy_score(y_valid, y_pred_valid))

# 5. 用全部训练数据重新训练,然后在测试集上预测
model.fit(X, y)
test_pred = model.predict(test_features)

# 6. 生成提交文件
submission = pd.DataFrame({
    "PassengerId": test["PassengerId"],
    "Survived": test_pred
})

submission.to_csv("submission.csv", index=False)
print("submission.csv 已保存")
相关推荐
DisonTangor1 天前
DeepSeek-OCR 2: 视觉因果流
人工智能·开源·aigc·ocr·deepseek
薛定谔的猫19821 天前
二十一、基于 Hugging Face Transformers 实现中文情感分析情感分析
人工智能·自然语言处理·大模型 训练 调优
发哥来了1 天前
《AI视频生成技术原理剖析及金管道·图生视频的应用实践》
人工智能
数智联AI团队1 天前
AI搜索引领开源大模型新浪潮,技术创新重塑信息检索未来格局
人工智能·开源
不懒不懒1 天前
【线性 VS 逻辑回归:一篇讲透两种核心回归模型】
人工智能·机器学习
冰西瓜6001 天前
从项目入手机器学习——(四)特征工程(简单特征探索)
人工智能·机器学习
Ryan老房1 天前
未来已来-AI标注工具的下一个10年
人工智能·yolo·目标检测·ai
丝斯20111 天前
AI学习笔记整理(66)——多模态大模型MOE-LLAVA
人工智能·笔记·学习
小鸡吃米…1 天前
机器学习中的代价函数
人工智能·python·机器学习
chatexcel1 天前
元空AI+Clawdbot:7×24 AI办公智能体新形态详解(长期上下文/自动化任务/工具粘合)
运维·人工智能·自动化