更新 function.py
Gitea Actions Experiment Test / Experiment-Actions (push) Successful in 11s

This commit is contained in:
2024-11-03 00:10:31 +08:00
parent 0bdb5ddebd
commit 15426c6300
+9 -49
View File
@@ -1,10 +1,5 @@
import numpy as np
"""
实验说明:
- 自行编写实现数据加载与预测病马死亡的对率回归算法。
"""
id = "202210423218"
name = "唐一鸣"
@@ -12,17 +7,6 @@ def sigmoid(z):
return 1 / (1 + np.exp(-z))
def train_logreg(X, y, other_params=""):
"""
对率回归训练函数。
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
@@ -31,52 +15,32 @@ def train_logreg(X, y, other_params=""):
for _ in range(num_iterations):
linear_model = np.dot(X, weights)
y_predicted = sigmoid(linear_model)
# Gradient descent
gradient = np.dot(X.T, (y_predicted - y)) / m
weights -= learning_rate * gradient
return weights
def predict_logreg(inX, weights):
"""
对率回归预测函数。
Args:
- inX (numpy array): 输入待分类的样本。
- weights (numpy array): 训练得到的权重。
Returns:
- int: 预测的分类标签。
"""
prob = sigmoid(np.dot(inX, weights))
return 1 if prob >= 0.5 else 0
def load_data(filepath):
"""
从文件中加载数据,处理缺失值。
Args:
- filepath (str): 数据文件路径。
Returns:
- np.array: 特征数据。
- np.array: 标签数据。
"""
with open(filepath, 'r') as f:
lines = f.readlines()
data = []
for line in lines:
# 替换缺失值 '?' 为 np.nan
row = line.strip().split()
row = [float(x) if x != '?' else np.nan for x in row]
data.append(row)
data = np.array(data)
# 处理缺失值:用均值替代缺失值
data = np.where(np.isnan(data), np.nanmean(data, axis=0), data)
# 用均值替代缺失值
for i in range(data.shape[1] - 1): # 只处理特征列
if np.any(np.isnan(data[:, i])):
mean_value = np.nanmean(data[:, i])
data[:, i] = np.where(np.isnan(data[:, i]), mean_value, data[:, i])
# 特征为前n-1列,标签为最后一列
X = data[:, :-1]
@@ -84,19 +48,15 @@ def load_data(filepath):
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)
# 测试单个数据
y_pred = predict_logreg(X_test[11], weights)
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")
test_index = 11 # 选择要测试的索引
y_pred = predict_logreg(X_test[test_index], weights)
print(f"预测结果: {y_pred}, 实际结果: {y_test[test_index]}")