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

This commit is contained in:
2024-10-31 23:33:36 +08:00
parent f49e7c7cd5
commit 3242f3f163
+7 -23
View File
@@ -36,14 +36,9 @@ def load_data(filepath):
- np.array: 特征数据。
- np.array: 标签数据。
"""
# 使用np.genfromtxt加载数据,它可以自动处理缺失值
data = np.genfromtxt(filepath, delimiter=',', skip_header=1, filling_values=np.nan)
# 分离特征和标签
# 确保data不是一维数组
if data.ndim == 1:
data = data.reshape(1, -1) # 将其转换为二维数组,如果它是一维的
X = data[:, :-1]
y = data[:, -1].flatten() # 确保y是一维数组
@@ -53,7 +48,7 @@ def load_data(filepath):
y = y[mask]
return X, y
def sigmoid(z):
"""
Sigmoid函数。
@@ -84,11 +79,15 @@ def train_logreg(X, y, learning_rate=0.01, iterations=1000):
# 初始化权重
weights = np.zeros(X.shape[1])
# 检查y是否为空
if len(y) == 0:
raise ValueError("标签数组y为空")
for _ in range(iterations):
# 计算预测值
predictions = sigmoid(np.dot(X, weights))
# 计算梯度
gradient = np.dot(X.T, (predictions - y)) / len(y)
gradient = np.dot(X.T, (predictions - y)) / max(len(y), 1) # 防止除以零
# 更新权重
weights -= learning_rate * gradient
@@ -107,19 +106,4 @@ def predict_logreg(inX, weights):
"""
inX = np.c_[1, inX] # 添加截距项
prob = sigmoid(np.dot(inX, weights))
return 1 if prob > 0.5 else 0
# 移除以下测试代码,仅在本地测试时使用
# 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}, 实际结果: {int(y_test[11])}")
return 1 if prob > 0.5 else 0