generated from LufsX/Experiment-LogReg
This commit is contained in:
+86
-106
@@ -1,116 +1,96 @@
|
|||||||
# function.py
|
# function.py
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import csv
|
from sklearn.preprocessing import StandardScaler
|
||||||
|
from sklearn.metrics import accuracy_score
|
||||||
|
"""
|
||||||
|
实验说明:
|
||||||
|
- 自行编写实现数据加载与预测病马死亡的对率回归算法。
|
||||||
|
|
||||||
"""
|
注意事项:
|
||||||
实验说明:
|
- 在 function.py 中实现对率回归算法。
|
||||||
- 自行编写实现数据加载与预测病马死亡的对率回归算法。
|
- 可以自行导入其他库,需要在 requirements.txt 添加依赖,若未在 requirements.txt 中添加使用到的依赖,则无法自动评测,成绩为零。
|
||||||
|
- 自动评测脚本仅会加载 train_logreg、predict_logreg 和 load_data 函数,请勿修改函数名。
|
||||||
|
|
||||||
注意事项:
|
测评环境:
|
||||||
- 在 function.py 中实现对率回归算法。
|
- CPU: Intel Xeon(R) CPU E3-1231 v3 @ 3.40GHz
|
||||||
- 可以自行导入其他库,需要在 requirements.txt 添加依赖,若未在 requirements.txt 中添加使用到的依赖,则无法自动评测,成绩为零。
|
- OS: Ubuntu 22.04.4 LTS
|
||||||
- 自动评测脚本仅会加载 train_logreg、predict_logreg 和 load_data 函数,请勿修改函数名。
|
- Python: 3.10.12
|
||||||
|
- numpy: 2.1.1
|
||||||
测评环境:
|
"""
|
||||||
- CPU: Intel Xeon(R) CPU E3-1231 v3 @ 3.40GHz
|
|
||||||
- OS: Ubuntu 22.04.4 LTS
|
|
||||||
- Python: 3.10.12
|
|
||||||
- numpy: 2.1.1
|
|
||||||
"""
|
|
||||||
|
|
||||||
"""
|
|
||||||
请在这里填写学号和姓名,不填写即成绩无效。
|
|
||||||
姓名请直接**填写中文**
|
|
||||||
例如: name = "张三"
|
|
||||||
"""
|
|
||||||
id = "20221042323"
|
|
||||||
name = "李顺潮"
|
|
||||||
|
|
||||||
|
|
||||||
# 这里写自己的代码实现
|
"""
|
||||||
def train_logreg(X, y, other_params=None):
|
请在这里填写学号和姓名,不填写即成绩无效
|
||||||
"""
|
"""
|
||||||
对率回归训练函数。
|
id = "202210423223"
|
||||||
|
name = "李顺潮"
|
||||||
|
|
||||||
Args:
|
|
||||||
- X (numpy array): 特征数据。
|
|
||||||
- y (numpy array): 标签数据。
|
|
||||||
- other_params (str): 其它参数,可选设置。若需设置其它参数,必须设置其默认值,否则将**无法通过**自动评测,**成绩为零**。
|
|
||||||
|
|
||||||
Returns:
|
# 这里写自己的代码实现
|
||||||
- numpy array: 训练得到的权重。
|
def train_logreg(X, y, learning_rate=0.01, iterations=1000, lambda_reg=0.1):
|
||||||
"""
|
|
||||||
m, n = X.shape
|
m, n = X.shape
|
||||||
weights = np.zeros(n) # 初始化权重
|
weights = np.zeros(n)
|
||||||
learning_rate = 0.01 # 学习率设置
|
bias = 0
|
||||||
num_iterations = 1000 # 迭代次数
|
|
||||||
|
for _ in range(iterations):
|
||||||
|
linear_output = np.dot(X, weights) + bias
|
||||||
|
y_predicted = 1 / (1 + np.exp(-linear_output))
|
||||||
|
|
||||||
|
# 计算梯度(包括正则化项)
|
||||||
|
dw = (1 / m) * np.dot(X.T, (y_predicted - y)) + (lambda_reg / m) * weights
|
||||||
|
db = (1 / m) * np.sum(y_predicted - y)
|
||||||
|
|
||||||
|
# 更新权重和偏置
|
||||||
|
weights -= learning_rate * dw
|
||||||
|
bias -= learning_rate * db
|
||||||
|
|
||||||
|
return weights, bias
|
||||||
|
|
||||||
# 对率回归的梯度下降
|
def predict_logreg(inX, weights, bias):
|
||||||
for _ in range(num_iterations):
|
linear_output = np.dot(inX, weights) + bias
|
||||||
linear_model = np.dot(X, weights)
|
y_predicted = 1 if linear_output >= 0 else 0 # 简化阈值判断,因为已经通过sigmoid函数输出
|
||||||
predictions = 1 / (1 + np.exp(-linear_model)) # Sigmoid函数
|
# 注意:这里为了与原始代码保持一致,使用了0.5作为阈值,但实际上由于sigmoid输出范围在(0,1),可以直接比较linear_output和0
|
||||||
errors = y - predictions
|
# return 1 if y_predicted >= 0.5 else 0 # 等价于上面的判断,但多余计算了sigmoid
|
||||||
weights += learning_rate * np.dot(X.T, errors) / m # 更新权重
|
return y_predicted
|
||||||
|
|
||||||
return weights
|
# 这里也写自己的代码实现
|
||||||
|
def load_data(filepath):
|
||||||
|
data = []
|
||||||
|
with open(filepath, 'r') as file:
|
||||||
|
for line in file:
|
||||||
|
parts = line.strip().split()
|
||||||
|
# 将缺失值'?'替换为np.nan,然后使用0填充(或选择其他适当的填充策略)
|
||||||
|
features = [float(part) if part != '?' else np.nan for part in parts[:-1]]
|
||||||
|
# 填充NaN值(这里选择0,但也可以考虑使用均值、中位数等)
|
||||||
|
features = np.nan_to_num(features, nan=0.0)
|
||||||
|
# 将标签从2转换为1(如果原始标签是1和2的话),这里假设标签已经是0和1
|
||||||
|
label = int(parts[-1]) # 假设标签已经是0和1,无需转换
|
||||||
|
data.append(features + [label])
|
||||||
|
|
||||||
|
data_array = np.array(data)
|
||||||
|
X = data_array[:, :-1]
|
||||||
|
y = data_array[:, -1]
|
||||||
|
|
||||||
|
# 特征缩放(标准化)
|
||||||
|
scaler = StandardScaler()
|
||||||
|
X_scaled = scaler.fit_transform(X)
|
||||||
|
|
||||||
|
return X_scaled, y
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
def predict_logreg(inX, weights):
|
# 加载训练集和测试集
|
||||||
"""
|
X_train, y_train = load_data("./data/horse-colic.data")
|
||||||
对率回归预测函数。
|
X_test, y_test = load_data("./data/horse-colic.test")
|
||||||
|
|
||||||
Args:
|
# 训练对率回归模型
|
||||||
- inX (numpy array): 输入待分类的样本。
|
weights, bias = train_logreg(X_train, y_train, learning_rate=0.01, iterations=1000, lambda_reg=0.1)
|
||||||
- weights (numpy array): 训练得到的权重。
|
|
||||||
|
# 测试模型并评估性能
|
||||||
Returns:
|
y_pred = [predict_logreg(x, weights, bias) for x in X_test]
|
||||||
- int: 预测的分类标签。
|
accuracy = accuracy_score(y_test, y_pred)
|
||||||
"""
|
print(f"模型准确率: {accuracy}")
|
||||||
linear_model = np.dot(inX, weights)
|
|
||||||
predictions = 1 / (1 + np.exp(-linear_model)) # Sigmoid函数
|
# 打印单个测试样本的预测结果和实际结果(示例)
|
||||||
return np.round(predictions).astype(int) # 返回0或1
|
# 注意:索引11可能需要根据实际测试集调整,这里仅作为示例
|
||||||
|
sample_index = 11 # 假设要测试的样本索引是11(注意:索引可能需要根据实际数据调整)
|
||||||
|
print(f"预测结果: {y_pred[sample_index]}, 实际结果: {y_test[sample_index]}")
|
||||||
# 这里也写自己的代码实现
|
|
||||||
def load_data(filepath):
|
|
||||||
"""
|
|
||||||
从文件中加载数据,处理缺失值并确保格式正确。
|
|
||||||
|
|
||||||
Args:
|
|
||||||
- filepath (str): 数据文件路径。
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
- np.array: 特征数据。
|
|
||||||
- np.array: 标签数据。
|
|
||||||
"""
|
|
||||||
features = []
|
|
||||||
labels = []
|
|
||||||
|
|
||||||
with open(filepath, 'r') as f:
|
|
||||||
reader = csv.reader(f)
|
|
||||||
for row in reader:
|
|
||||||
# 检查每一行是否包含预期数量的列,这里假设每行需要至少一个特征和一个标签
|
|
||||||
if len(row) > 1:
|
|
||||||
features.append([float(x) for x in row[:-1]]) # 将特征转换为浮点数
|
|
||||||
labels.append(row[-1]) # 取最后一列作为标签
|
|
||||||
|
|
||||||
# 转换成NumPy数组
|
|
||||||
X = np.array(features)
|
|
||||||
y = np.array(labels)
|
|
||||||
|
|
||||||
# 确保 y 只包含 0 和 1
|
|
||||||
y = np.where(y == '1', 1, 0)
|
|
||||||
|
|
||||||
# 过滤掉包含 NaN 的行
|
|
||||||
valid_indices = ~np.isnan(X).any(axis=1) & ~np.isnan(y.astype(float))
|
|
||||||
X = X[valid_indices]
|
|
||||||
y = y[valid_indices]
|
|
||||||
|
|
||||||
return X, y
|
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
|
||||||
# 以下代码可用于测试,可自行随意修改
|
|
||||||
# 加载训练集
|
|
||||||
X_train, y_train = load_data("./data/horse-colic.data")
|
|
||||||
print(f"预测结果: {y_pred[sample_index]}, 实际结果: {y_test[sample_index]}")
|
|
||||||
Reference in New Issue
Block a user