Files
Experiment_2/function.py
T
DREMN2112 1a97f717ab
Gitea Actions Experiment Test / Experiment-Actions (push) Successful in 14s
更新 function.py
2024-11-07 17:23:25 +08:00

51 lines
1.5 KiB
Python

import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
# 填写学号和姓名
id = "202210218225"
name = "周水源"
def train_logreg(X, y, random_state=42):
model = LogisticRegression(solver='liblinear', random_state=random_state)
model.fit(X, y)
return model
def predict_logreg(inX, model):
return int(model.predict([inX])[0])
def load_data(filepath):
data = np.genfromtxt(filepath, delimiter=' ', missing_values='?', filling_values=0)
labels = data[:, -1].astype(int)
data = data[:, :-1]
labels = np.where((labels == 2) | (labels == 3), 0, labels)
if data.shape[1] >= 3:
data = np.delete(data, 2, axis=1)
scaler = StandardScaler()
data = scaler.fit_transform(data)
return data, labels
# 测试代码
if __name__ == "__main__":
# 指定数据文件路径
filepath = "./data/horse-colic.data"
# 加载数据
X, y = load_data(filepath)
print("数据加载成功。")
# 训练模型
model = train_logreg(X, y)
print("模型训练完成。")
# 随机选择一个样本进行预测测试
sample = X[0]
actual_label = y[0]
predicted_label = predict_logreg(sample, model)
print(f"预测结果: {predicted_label}, 实际结果: {actual_label}")
# 计算测试集上的准确率
correct_predictions = sum(predict_logreg(X[i], model) == y[i] for i in range(len(y)))
accuracy = correct_predictions / len(y)
print(f"测试集准确率: {accuracy:.2f}")