generated from LufsX/Experiment-LogReg
This commit is contained in:
+13
-6
@@ -35,20 +35,26 @@ def load_data(filepath):
|
||||
y = data[:, -1]
|
||||
return X, y
|
||||
|
||||
def train_logreg(X, y, learning_rate=0.01, iterations=1000):
|
||||
"""训练逻辑回归模型,使用随机梯度下降."""
|
||||
def train_logreg(X, y, initial_learning_rate=0.1, iterations=1000, decay_rate=0.01):
|
||||
"""训练逻辑回归模型,使用随机梯度下降和学习率衰减."""
|
||||
n_samples, n_features = X.shape
|
||||
weights = np.zeros(n_features + 1) # 增加一位用于偏置
|
||||
X = np.c_[X, np.ones((n_samples, 1))] # 增加偏置项
|
||||
|
||||
for _ in range(iterations):
|
||||
for i in range(iterations):
|
||||
# 更新学习率
|
||||
learning_rate = initial_learning_rate / (1 + decay_rate * i)
|
||||
|
||||
random_index = np.random.randint(n_samples)
|
||||
X_i = X[random_index]
|
||||
y_i = y[random_index]
|
||||
|
||||
linear_model = np.dot(X_i, weights)
|
||||
dw = (linear_model - y_i) * X_i
|
||||
weights -= learning_rate * dw
|
||||
prediction = 1 / (1 + np.exp(-linear_model)) # Sigmoid函数
|
||||
error = prediction - y_i
|
||||
|
||||
# 更新权重
|
||||
weights -= learning_rate * error * X_i
|
||||
|
||||
return weights
|
||||
|
||||
@@ -56,7 +62,8 @@ def predict_logreg(inX, weights):
|
||||
"""使用线性模型预测结果."""
|
||||
inX = np.append(inX, 1) # 增加偏置项
|
||||
linear_model = np.dot(inX, weights)
|
||||
return 1.0 if linear_model >= 0 else 2.0
|
||||
prediction = 1 / (1 + np.exp(-linear_model))
|
||||
return 1.0 if prediction >= 0.5 else 2.0 # 返回1.0或2.0
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 加载训练集
|
||||
|
||||
Reference in New Issue
Block a user