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

This commit is contained in:
2024-11-05 15:11:17 +08:00
parent fba273d85b
commit 9000e29c5e
+11 -18
View File
@@ -28,16 +28,9 @@ name = "Tanjunfeng"
# 这里写自己的代码实现 # 这里写自己的代码实现
import numpy as np
def sigmoid(z): def sigmoid(z):
"""
Compute the sigmoid of z.
Args:
- z (numpy array): Input array.
Returns:
- numpy array: Sigmoid of input.
"""
return 1 / (1 + np.exp(-z)) return 1 / (1 + np.exp(-z))
def train_logreg(X, y, learning_rate=0.01, iterations=1000): def train_logreg(X, y, learning_rate=0.01, iterations=1000):
@@ -51,7 +44,7 @@ def train_logreg(X, y, learning_rate=0.01, iterations=1000):
- iterations (int): 迭代次数,默认为 1000。 - iterations (int): 迭代次数,默认为 1000。
Returns: Returns:
- Tuple[numpy array, float]: 训练得到的权重和偏置。 - numpy array: 训练得到的权重。
""" """
m, n = X.shape m, n = X.shape
weights = np.zeros(n) weights = np.zeros(n)
@@ -65,23 +58,23 @@ def train_logreg(X, y, learning_rate=0.01, iterations=1000):
weights -= learning_rate * dw weights -= learning_rate * dw
bias -= learning_rate * db bias -= learning_rate * db
return weights, bias return weights
def predict_logreg(inX, weights, bias): def predict_logreg(inX, weights):
""" """
对率回归预测函数。 对率回归预测函数。
Args: Args:
- inX (numpy array): 输入待分类的样本。 - inX (numpy array): 输入待分类的样本。
- weights (numpy array): 训练得到的权重。 - weights (numpy array): 训练得到的权重。
- bias (float): 训练得到的偏置。
Returns: Returns:
- int: 预测的分类标签。 - int: 预测的分类标签。
""" """
z = np.dot(inX, weights) + bias z = np.dot(inX, weights)
h = sigmoid(z) h = sigmoid(z)
return 1 if h >= 0.5 else 0 # 调整分类阈值
return 1 if h > 0.6 else 0
def load_data(filepath): def load_data(filepath):
""" """
@@ -119,14 +112,14 @@ if __name__ == "__main__":
X_test, y_test = load_data("./data/horse-colic.test") X_test, y_test = load_data("./data/horse-colic.test")
# 训练对率回归模型 # 训练对率回归模型
weights, bias = train_logreg(X_train, y_train, learning_rate=0.001, iterations=5000) weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=5000)
# 测试单个数据 # 测试单个数据
correct_count = 0 correct_count = 0
total_count = len(y_test) total_count = len(y_test)
for i in range(total_count): for i in range(total_count):
y_pred = predict_logreg(X_test[i], weights, bias) y_pred = predict_logreg(X_test[i], weights)
if y_pred == y_test[i]: if y_pred == y_test[i]:
correct_count += 1 correct_count += 1
accuracy = correct_count / total_count accuracy = correct_count / total_count
print(f"测试准确率: {accuracy:.2f}") print(f"准确率: {accuracy}")