generated from LufsX/Experiment-LogReg
This commit is contained in:
+54
-66
@@ -26,69 +26,57 @@ name = "周佳成"
|
||||
|
||||
|
||||
# 这里写自己的代码实现
|
||||
import pandas as pd
|
||||
import requests
|
||||
|
||||
# 下载病马数据
|
||||
def download_horse_colic_data(url, filename):
|
||||
response = requests.get(url)
|
||||
with open(filename, 'wb') as f:
|
||||
f.write(response.content)
|
||||
|
||||
# 处理并加载数据
|
||||
def load_and_preprocess_horse_colic_data(train_filename, test_filename):
|
||||
# 定义列名
|
||||
column_names = [
|
||||
'surgery', 'age', 'hospital_number', 'rectal_temperature',
|
||||
'pulse', 'respiratory_rate', 'temperature_of_extremities',
|
||||
'peripheral_pulse', 'mucous_membrane', 'capillary_refill_time',
|
||||
'pain', 'surgical_lesion', 'type_of_lesion', 'surgical_lesion_location',
|
||||
'outcome' # 假设'outcome'是目标变量,1=lived, 2=died, 3=euthanized
|
||||
]
|
||||
|
||||
# 读取训练数据
|
||||
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)
|
||||
|
||||
# 处理缺失值:用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)
|
||||
|
||||
# 处理目标变量'outcome'的缺失值
|
||||
train_data['outcome'].fillna(0, inplace=True) # 可以选择适合的填充方法
|
||||
test_data['outcome'].fillna(0, inplace=True)
|
||||
|
||||
# 将目标变量'outcome'转换为数值型
|
||||
train_data['outcome'] = train_data['outcome'].astype(int)
|
||||
test_data['outcome'] = test_data['outcome'].astype(int)
|
||||
|
||||
return train_data, test_data
|
||||
|
||||
# 主函数
|
||||
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())
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
import pandas as pd
|
||||
import numpy as np
|
||||
from sklearn.model_selection import train_test_split
|
||||
from sklearn.linear_model import LogisticRegression
|
||||
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_number", "rectal_temp", "pulse", "respiratory_rate",
|
||||
"temp_of_extremities", "peripheral_pulse", "mucous_membrane_color",
|
||||
"capillary_refill_time", "pain", "peristalsis", "abdominal_distention",
|
||||
"nasal_discharge", "vomit", "heart_rate", "rectal_exam_fecal", "packed_cell_volume",
|
||||
"total_protein", "abdominal_fluid_type", "abdominal_fluid_color", "outcome"
|
||||
] + ["unused_" + str(i) for i in range(1, 9)] # 忽略最后8个无用特征
|
||||
|
||||
data = pd.read_csv(url, header=None, names=columns, na_values="?")
|
||||
|
||||
# 处理缺失值,用0填充
|
||||
data.fillna(0, inplace=True)
|
||||
|
||||
# 转换目标变量,将2(死亡)和3(安乐死)合并为0(死亡),1(存活)保持不变
|
||||
data["outcome"] = data["outcome"].apply(lambda x: 0 if x in [2, 3] else 1)
|
||||
|
||||
# 去掉特征3(hospital_number)和特征24~28(unused_1 到 unused_8)
|
||||
data.drop(columns=["hospital_number"] + ["unused_" + str(i) for i in range(1, 9)], inplace=True)
|
||||
|
||||
# 特征和标签
|
||||
X = data.drop(columns=["outcome"])
|
||||
y = data["outcome"]
|
||||
|
||||
# 划分训练集和测试集(这里简单按7:3划分,实际应用中应与原数据集划分保持一致)
|
||||
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.fit(X_train, y_train)
|
||||
return model
|
||||
|
||||
def predict_logreg(model, X_test):
|
||||
# 使用模型进行预测
|
||||
y_pred = model.predict(X_test)
|
||||
return y_pred
|
||||
|
||||
# 示例调用(注:这些调用在自动评测时不会执行,仅供测试使用)
|
||||
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)
|
||||
print(f"Accuracy: {accuracy_score(y_test, y_pred)}")
|
||||
|
||||
Reference in New Issue
Block a user