generated from LufsX/Experiment-LogReg
This commit is contained in:
+16
-15
@@ -40,43 +40,43 @@ def train_logreg(X, y, learning_rate=0.01, iterations=1000):
|
||||
- iterations (int): 迭代次数, 默认值为1000。
|
||||
|
||||
Returns:
|
||||
- numpy array: 训练得到的权重。
|
||||
- float: 训练得到的偏置。
|
||||
- numpy array: 训练得到的权重和偏置(合并为一个数组)。
|
||||
"""
|
||||
n_samples, n_features = X.shape
|
||||
weights = np.zeros(n_features)
|
||||
bias = 0
|
||||
weights = np.zeros(n_features + 1) # 增加一位用于偏置
|
||||
|
||||
# 增加一列1表示偏置
|
||||
X = np.c_[X, np.ones((n_samples, 1))]
|
||||
|
||||
# 梯度下降法
|
||||
for i in range(iterations):
|
||||
linear_model = np.dot(X, weights) + bias
|
||||
linear_model = np.dot(X, weights)
|
||||
y_pred = sigmoid(linear_model)
|
||||
|
||||
# 计算梯度
|
||||
dw = (1 / n_samples) * np.dot(X.T, (y_pred - y))
|
||||
db = (1 / n_samples) * np.sum(y_pred - y)
|
||||
|
||||
# 更新权重和偏置
|
||||
# 更新权重
|
||||
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:
|
||||
- inX (numpy array): 输入待分类的样本。
|
||||
- weights (numpy array): 训练得到的权重。
|
||||
- bias (float): 训练得到的偏置。
|
||||
- weights (numpy array): 训练得到的权重和偏置。
|
||||
|
||||
Returns:
|
||||
- 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)
|
||||
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")
|
||||
|
||||
# 训练对率回归模型
|
||||
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]}")
|
||||
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user