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

This commit is contained in:
2024-10-29 19:10:45 +08:00
parent fec9e467b6
commit a03737a8c1
+16 -15
View File
@@ -40,43 +40,43 @@ def train_logreg(X, y, learning_rate=0.01, iterations=1000):
- iterations (int): 迭代次数, 默认值为1000。 - iterations (int): 迭代次数, 默认值为1000。
Returns: Returns:
- numpy array: 训练得到的权重。 - numpy array: 训练得到的权重和偏置(合并为一个数组)。
- float: 训练得到的偏置。
""" """
n_samples, n_features = X.shape n_samples, n_features = X.shape
weights = np.zeros(n_features) weights = np.zeros(n_features + 1) # 增加一位用于偏置
bias = 0
# 增加一列1表示偏置
X = np.c_[X, np.ones((n_samples, 1))]
# 梯度下降法 # 梯度下降法
for i in range(iterations): for i in range(iterations):
linear_model = np.dot(X, weights) + bias linear_model = np.dot(X, weights)
y_pred = sigmoid(linear_model) y_pred = sigmoid(linear_model)
# 计算梯度 # 计算梯度
dw = (1 / n_samples) * np.dot(X.T, (y_pred - y)) dw = (1 / n_samples) * np.dot(X.T, (y_pred - y))
db = (1 / n_samples) * np.sum(y_pred - y)
# 更新权重和偏置 # 更新权重
weights -= learning_rate * dw weights -= learning_rate * dw
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: 预测的分类标签 (0 或 1)。 - int: 预测的分类标签 (0 或 1)。
""" """
linear_model = np.dot(inX, weights) + bias # 增加偏置项
inX = np.append(inX, 1)
linear_model = np.dot(inX, weights)
y_pred = sigmoid(linear_model) y_pred = sigmoid(linear_model)
return 1 if y_pred >= 0.5 else 0 return 1 if y_pred >= 0.5 else 0
@@ -115,10 +115,11 @@ 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.01, iterations=1000) weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=1000)
# 测试单个数据 # 测试单个数据
y_pred = predict_logreg(X_test[11], weights, bias) y_pred = predict_logreg(X_test[11], weights)
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}") print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")