更新 function.py
Gitea Actions Experiment Test / Experiment-Actions (push) Successful in 12s

This commit is contained in:
2024-11-03 15:41:27 +08:00
parent 1e3fab5bfe
commit 7e2a459455
+56 -29
View File
@@ -21,45 +21,72 @@ import numpy as np
"""
请在这里填写学号和姓名,不填写即成绩无效。
"""
id = "202210423xxx"
name = "test_name"
id = "202210423102"
name = "周佳成"
# 这里写自己的代码实现
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error, r2_score
import requests
# 数据加载
data_path = 'data/your_dataset.csv' # 替换为实际数据集路径
data = pd.read_csv(data_path)
# 下载病马数据集
def download_horse_colic_data(url, filename):
response = requests.get(url)
with open(filename, 'wb') as f:
f.write(response.content)
# 数据预处理
# 检查缺失值
print(data.isnull().sum())
# 处理并加载数据
def load_and_preprocess_horse_colic_data(train_filename, test_filename):
# 定义列名
column_names = [
'surgery', 'age', 'hospital_number', 'rectal_temperature',
# ... 其他列名可以根据需要添加
'outcome' # 假设'outcome'是目标变量,1=lived, 2=died, 3=euthanized
]
# 填补缺失值(可以选择不同策略)
data.fillna(data.mean(), inplace=True)
# 读取训练数据
train_data = pd.read_csv(train_filename, delim_whitespace=True, header=None, names=column_names)
# 读取测试数据
test_data = pd.read_csv(test_filename, delim_whitespace=True, header=None, names=column_names)
# 特征选择
features = ['age', 'health_condition', 'treatment_effectiveness']
X = data[features]
y = data['mortality_rate']
# 处理缺失值:用0填充(这里假设除了'outcome'之外的所有特征都可能有缺失值)
for column in train_data.columns[:-1]: # 排除目标变量列
train_data[column].fillna(0, inplace=True)
for column in test_data.columns[:-1]: # 排除目标变量列
test_data[column].fillna(0, inplace=True)
# 数据集划分
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 处理目标变量'outcome'的缺失值
train_data['outcome'].fillna(0, inplace=True) # 可以选择适合的填充方法
test_data['outcome'].fillna(0, inplace=True)
# 模型构建
model = LinearRegression()
model.fit(X_train, y_train)
# 将目标变量'outcome'转换为数值型
train_data['outcome'] = train_data['outcome'].astype(int)
test_data['outcome'] = test_data['outcome'].astype(int)
# 预测
y_pred = model.predict(X_test)
return train_data, test_data
# 模型评估
mse = mean_squared_error(y_test, y_pred)
r2 = r2_score(y_test, y_pred)
# 主函数
def main():
# 数据集URL
train_url = 'http://archive.ics.uci.edu/ml/machine-learning-databases/horse-colic/horse-colic.data'
test_url = 'http://archive.ics.uci.edu/ml/machine-learning-databases/horse-colic/horse-colic-test.data'
# 保存数据集的文件名
train_filename = 'horse_colic_train.data'
test_filename = 'horse_colic_test.data'
# 下载数据集
download_horse_colic_data(train_url, train_filename)
download_horse_colic_data(test_url, test_filename)
# 加载并预处理数据
train_data, test_data = load_and_preprocess_horse_colic_data(train_filename, test_filename)
# 打印前几行数据以验证
print("训练数据预览:")
print(train_data.head())
print("测试数据预览:")
print(test_data.head())
print(f'Mean Squared Error: {mse}')
print(f'R^2 Score: {r2}')
if __name__ == "__main__":
main()