Files
experient9_2/function.py
T
wujunjie 7c2b5175d6
Gitea Actions Experiment Test / Experiment-Actions (push) Successful in 11s
更新 function.py
2024-10-29 09:00:06 +08:00

89 lines
2.9 KiB
Python

# function.py
import numpy as np
"""
实验说明:
- 自行编写实现数据加载与预测病马死亡的对率回归算法。
注意事项:
- 在 function.py 中实现对率回归算法。
- 可以自行导入其他库,需要在 requirements.txt 添加依赖,若未在 requirements.txt 中添加使用到的依赖,则无法自动评测,成绩为零。
- 自动评测脚本仅会加载 train_logreg、predict_logreg 和 load_data 函数,请勿修改函数名。
测评环境:
- CPU: Intel Xeon(R) CPU E3-1231 v3 @ 3.40GHz
- OS: Ubuntu 22.04.4 LTS
- Python: 3.10.12
- numpy: 2.1.1
"""
"""
请在这里填写学号和姓名,不填写即成绩无效。
"""
id = "202210423217"
name = "吴俊煯"
# 这里写自己的代码实现
def train_logreg(X, y, learning_rate=0.1, iterations=100):
m, n = X.shape
weights = np.zeros(n)
bias = 0
for _ in range(iterations):
for idx, x_i in enumerate(X):
linear_output = np.dot(x_i, weights) + bias
y_predicted = 1 / (1 + np.exp(-linear_output))
# 计算误差
error = y[idx] - y_predicted
# 更新权重和偏置
weights += learning_rate * error * x_i
bias += learning_rate * error
return weights
def predict_logreg(inX, weights):
linear_output = np.dot(inX, weights)
y_predicted = 1 / (1 + np.exp(-linear_output))
# 将输出转换为分类标签
return 1 if y_predicted >= 0.5 else 0
# 这里也写自己的代码实现
def load_data(filepath):
data = []
with open(filepath, 'r') as file:
for line in file:
# 分割行,并去除任何可能的空白字符
parts = [part.strip() for part in line.split()]
# 将缺失值'?'替换为0(或者你可以选择其他适当的处理方式)
features = [float(part) if part != '?' else 1 for part in parts[:-1]]
# 将标签从2转换为1(如果原始标签是1和2的话)
label = int(parts[-1]) - 1 # 假设原始标签是1和2,转换为0和1
data.append(features + [label])
# 将数据转换为numpy数组
data_array = np.array(data)
# 分离特征和标签
X = data_array[:, :-1] # 所有行,除了最后一列
y = data_array[:, -1] # 所有行的最后一列
return X, y
if __name__ == "__main__":
# 加载训练集
X_train, y_train = load_data("./data/horse-colic.data")
# 加载测试集
X_test, y_test = load_data("./data/horse-colic.test")
# 训练对率回归模型
weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=1000)
# 测试单个数据
y_pred = predict_logreg(X_test[11], weights)
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")