generated from LufsX/Experiment-LogReg
99 lines
2.7 KiB
Python
99 lines
2.7 KiB
Python
import numpy as np
|
|
import pandas as pd
|
|
|
|
id = "202210423223"
|
|
name = "李顺潮"
|
|
|
|
def load_data(filepath):
|
|
"""从文件中加载数据,处理不规则的字段数量和缺失值"""
|
|
data = []
|
|
with open(filepath, 'r') as f:
|
|
for line in f:
|
|
fields = line.strip().split()
|
|
# 处理不规则的字段数量,这里选择忽略多余的字段
|
|
if len(fields) > 28:
|
|
fields = fields[:28]
|
|
# 替换 '?' 为 NaN
|
|
fields = [np.nan if x == '?' else x for x in fields]
|
|
data.append(fields)
|
|
|
|
# 使用 pandas 创建 DataFrame
|
|
df = pd.DataFrame(data)
|
|
# 删除包含 NaN 的行
|
|
df.dropna(inplace=True)
|
|
# 转换为数值类型
|
|
df = df.astype(float)
|
|
|
|
X = df.iloc[:, :-1].values
|
|
y = df.iloc[:, -1].values
|
|
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]}") |