Files
experient9_2/function.py
T
wujunjie 3ceac3241d
Gitea Actions Experiment Test / Experiment-Actions (push) Successful in 11s
更新 function.py
2024-10-29 08:39:05 +08:00

108 lines
3.7 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.
# 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.01, iterations=1000, regularization=0.0):
m, n = X.shape
weights = np.zeros(n)
bias = 0
m = len(X) # 重新赋值m,以确保它表示样本数量(在添加正则化时可能需要)
for _ in range(iterations):
linear_output = np.dot(X, weights) + bias # 向量化操作
y_predicted = 1 / (1 + np.exp(-linear_output))
error = y - y_predicted
# 计算梯度(不包括正则化项)
gradient = np.dot(X.T, error) / m
# 加上正则化项的梯度(注意这里是对weights的每个元素都加上-regularization*weight[i])
gradient += -regularization * weights
# 更新权重
weights += learning_rate * gradient
bias += learning_rate * np.sum(error) / m
return weights, bias
def predict_logreg(inX, weights, bias):
# 确保 inX 是一维数组
if inX.ndim == 2 and inX.shape[1] == 1:
inX = inX.flatten()
elif inX.ndim > 1:
raise ValueError("Input data should be one-dimensional or a column vector.")
# 计算线性输出
linear_output = np.dot(inX, weights) + bias
# 应用sigmoid函数(如果需要的话)
# sigmoid_output = 1 / (1 + np.exp(-linear_output))
# 这里可以返回线性输出或sigmoid输出,取决于您的需求
return linear_output
# 这里也写自己的代码实现
def load_data(filepath):
data = []
with open(filepath, 'r') as file:
for line in file:
parts = [part.strip() for part in line.split()]
features = [float(part) if part != '?' else 0 for part in parts[:-1]]
label = int(parts[-1]) - 1 # 假设标签是{1, 2},转换为{0, 1}
data.append(features + [label])
data_array = np.array(data)
X = data_array[:, :-1]
y = data_array[:, -1]
return X, y
def evaluate_model(X, y, weights, bias):
predictions = [predict_logreg(x, weights, bias) for x in X]
accuracy = np.mean(predictions == y)
return accuracy
if __name__ == "__main__":
X_train, y_train = load_data("./data/horse-colic.data")
X_test, y_test = load_data("./data/horse-colic.test")
# 数据标准化(可选,但通常有助于模型性能)
X_train_mean = np.mean(X_train, axis=0)
X_train_std = np.std(X_train, axis=0)
X_train = (X_train - X_train_mean) / X_train_std
X_test = (X_test - X_train_mean) / X_train_std # 使用训练集的标准差来标准化测试集
# 训练逻辑回归模型
weights, bias = train_logreg(X_train, y_train, learning_rate=0.01, iterations=1000, regularization=0.1)
# 评估模型性能
accuracy = evaluate_model(X_test, y_test, weights, bias)
print(f"测试集准确率: {accuracy:.2f}")
# 测试单个数据(可选)
y_pred = predict_logreg(X_test[11], weights, bias)
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")