Files
Experiment-LogReg/function.py
T
luderby 9148b0c06e
Gitea Actions Experiment Test / Experiment-Actions (push) Successful in 19s
更新 function.py
2024-11-05 18:55:42 +08:00

106 lines
3.0 KiB
Python

import numpy as np
import pandas as pd
id = "202210423223"
name = "李顺潮"
def load_data(filepath):
"""
从文件中加载数据,处理缺失值和数据类型。
Args:
filepath (str): 数据文件路径。
Returns:
tuple: 特征数据 (np.array) 和标签数据 (np.array)。 返回None如果加载失败。
"""
try:
# 使用正则表达式作为分隔符,更灵活地处理多个空格
data = pd.read_csv(filepath, header=None, delim_whitespace=True)
# 替换问号为 NaN
data.replace('?', np.nan, inplace=True)
# 填充数值型缺失值,这里使用中位数填充
numeric_cols = data.select_dtypes(include=np.number).columns
for col in numeric_cols:
data[col].fillna(data[col].median(), inplace=True)
# 删除包含非数值型缺失值的列 (如果存在)
data.dropna(inplace=True)
# 假设最后一列是标签,其余是特征
X = data.iloc[:, :-1].values.astype(float)
y = data.iloc[:, -1].values.astype(float)
return X, y
except pd.errors.ParserError as e:
print(f"数据加载错误: {e}")
return None
except Exception as e:
print(f"发生未知错误: {e}")
return None
def sigmoid(z):
"""
Sigmoid 函数,用于对率回归的激活函数。
Args:
- z (numpy array): 输入值。
Returns:
- numpy array: Sigmoid 函数输出。
"""
return 1 / (1 + np.exp(-z))
def train_logreg(X, y, other_params=None):
"""
对率回归训练函数。
Args:
- X (numpy array): 特征数据。
- y (numpy array): 标签数据。
- other_params (str): 其它参数,可选设置。若需设置其它参数,必须设置其默认值,否则将**无法通过**自动评测,**成绩为零**。
Returns:
- numpy array: 训练得到的权重。
"""
m, n = X.shape
weights = np.zeros(n) # 初始化权重
learning_rate = 0.01
num_iterations = 1000
for _ in range(num_iterations):
z = np.dot(X, weights)
predictions = sigmoid(z)
# 计算梯度
gradient = np.dot(X.T, (predictions.astype(float) - y.astype(float))) / m
# 更新权重
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)
probability = sigmoid(z)
return 1 if probability >= 0.5 else 0
if __name__ == "__main__":
# 加载训练集
X_train, y_train = load_data("./data/horse-colic.data")
# 训练模型
weights = train_logreg(X_train, y_train)
# 测试预测
sample_index = 0 # 选择一个样本进行测试
y_pred = predict_logreg(X_train[sample_index], weights)
print(f"预测结果: {y_pred}, 实际结果: {y_train[sample_index]}")