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

This commit is contained in:
2024-11-03 17:43:19 +08:00
parent a558b91c4f
commit 0470a3ae6e
+22 -38
View File
@@ -26,64 +26,48 @@ name = "周佳成"
# 这里写自己的代码实现
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
def load_data():
# 加载病马数据集
# 下载并加载病马数据集
url = "http://archive.ics.uci.edu/ml/machine-learning-databases/horse-colic/horse-colic.data"
columns = [
"surgery", "age", "hospital_num", "rectal_temp", "pulse", "resp_rate",
"temp_of_extremities", "peripheral_pulse", "mucous_membrane", "capillary_refill_time",
"muscle_tone", "abdominal_distension", "nasal_discharge", "vomit", "heart_rate",
"rectal_exam_fecal", "packed_cell_volume", "total_protein", "abdominocentesis_fluid",
"abdominocentesis_fluid_appearance", "leukocyte_count", "outcome", "surgical_summary",
"lesion_type", "lesion_site", "lesion_size"
]
"outcome", "surgery", "age", "hospital_num", "rectal_temp", # 部分列名示例,其余列名需根据数据集实际内容补充
# ... 其他特征列名
] + ["unused_" + str(i) for i in range(14, 29)] # 假设最后15列为未使用特征
data = pd.read_csv(url, header=None, names=columns, na_values='?')
# 数据预处理
# 用0填充缺失值
# 处理缺失值,用0填充
data.fillna(0, inplace=True)
# 将取值2(死亡)和3(安乐死)合并为一个值0(死亡),并重新编码为二分类问题
data['outcome'] = data['outcome'].apply(lambda x: 0 if x in [2, 3] else 1)
# 选择特征和目标变量
X = data.drop(columns=["outcome", "age", "unused_" + str(i) for i in range(14, 29)])
y = (data["outcome"] == 2) | (data["outcome"] == 3) # 将2和3合并为0(死亡)
y = y.astype(int)
# 去掉特征3、特征24~28
data.drop(columns=['hospital_num', 'surgical_summary', 'lesion_type', 'lesion_site', 'lesion_size'], inplace=True)
# 特征和标签
X = data.drop(columns=['outcome'])
y = data['outcome']
# 划分训练集和测试集
# 划分训练集和测试集(这里简单划分为70%训练和30%测试,实际比例可根据需要调整)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)
return X_train, X_test, y_train, y_test
def train_logreg(X_train, y_train):
# 训练对率回归模型
model = LogisticRegression(max_iter=10000) # 增加迭代次数以确保收敛
model = LogisticRegression(max_iter=10000) # 设置默认迭代次数以避免警告
model.fit(X_train, y_train)
return model
def predict_logreg(model, X_test):
# 使用模型进行预测
y_pred = model.predict(X_test)
return y_pred
def evaluate_model(y_test, y_pred):
# 评估模型性能
accuracy = accuracy_score(y_test, y_pred)
return accuracy
# 主函数(用于测试和展示)
# 示例用法(注意:这里的示例用法不会直接运行,因为需要加载数据集)
if __name__ == "__main__":
X_train, X_test, y_train, y_test = load_data()
model = train_logreg(X_train, y_train)
y_pred = predict_logreg(model, X_test)
accuracy = evaluate_model(y_test, y_pred)
print(f"Model Accuracy: {accuracy:.4f}")