Files
Experiment-LogReg/function.py
T
dong f11d075a99
Gitea Actions Experiment Test / Experiment-Actions (push) Successful in 30s
更新 function.py
2024-10-31 23:33:16 +08:00

110 lines
2.9 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
"""
实验说明:
- 自行编写实现数据加载与预测病马死亡的对率回归算法。
"""
id = "202210423130"
name = "董秋"
def train_logreg(X, y, learning_rate=0.01, iterations=1000, lambda_reg=0.01):
"""
对率回归训练函数。
Args:
- X (numpy array): 特征数据。
- y (numpy array): 标签数据。
Returns:
- numpy array: 训练得到的权重。
"""
m, n = X.shape
weights = np.zeros(n)
for _ in range(iterations):
z = np.dot(X, weights)
predictions = 1 / (1 + np.exp(-z))
gradient = np.dot(X.T, (predictions - y)) / m
# L2正则化
gradient += (lambda_reg / m) * weights
weights -= learning_rate * gradient
return weights
def predict_logreg(inX, weights):
"""
对率回归预测函数。
Args:
- inX (numpy array): 输入待分类的样本。
- weights (numpy array): 训练得到的权重。
Returns:
- int: 预测的分类标签。
"""
z = np.dot(inX, weights)
prediction_prob = 1 / (1 + np.exp(-z))
return 1 if prediction_prob >= 0.5 else 0
def load_data(filepath):
data = []
labels = []
with open(filepath, 'r') as f:
for line in f:
values = line.strip().replace('?', '0').split()
try:
values = [float(v) for v in values]
# 合并特征23的取值
if values[22] == 2 or values[22] == 3: # 特征23(索引22)
labels.append(0) # 死亡
elif values[22] == 1:
labels.append(1) # 生存
else:
continue # 无效标签,丢弃
# 用0填充缺失值
values = [0 if np.isnan(v) else v for v in values]
# 去掉特征3(索引2)和特征24~28(索引23-27)
data.append(values[:2] + values[3:23]) # 保留特征1, 2 和特征4-23
except ValueError:
continue
return np.array(data), np.array(labels)
def preprocess_data(X):
# 特征标准化
scaler = StandardScaler()
return scaler.fit_transform(X)
if __name__ == "__main__":
# 以下代码可用于测试,可自行随意修改
# 加载训练集
X_train, y_train = load_data("./data/horse-colic.data")
X_train = preprocess_data(X_train)
# 加载测试集
X_test, y_test = load_data("./data/horse-colic.test")
X_test = preprocess_data(X_test)
# 训练对率回归模型
weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=1000, lambda_reg=0.01)
# 测试单个数据
y_pred = predict_logreg(X_test[11], weights)
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")