diff --git a/function.py b/function.py index cf46fa8..45f6edf 100644 --- a/function.py +++ b/function.py @@ -35,7 +35,7 @@ def load_data(filepath): y = data[:, -1] return X, y -def train_logreg(X, y, learning_rate=0.1, iterations=1000): +def train_logreg(X, y, learning_rate=0.01, iterations=1000): """训练逻辑回归模型,使用随机梯度下降.""" n_samples, n_features = X.shape weights = np.zeros(n_features + 1) # 增加一位用于偏置 @@ -45,13 +45,10 @@ def train_logreg(X, y, learning_rate=0.1, iterations=1000): random_index = np.random.randint(n_samples) X_i = X[random_index] y_i = y[random_index] - + linear_model = np.dot(X_i, weights) - prediction = 1 / (1 + np.exp(-linear_model)) # Sigmoid函数 - error = prediction - y_i - - # 更新权重 - weights -= learning_rate * error * X_i + dw = (linear_model - y_i) * X_i + weights -= learning_rate * dw return weights @@ -59,16 +56,19 @@ def predict_logreg(inX, weights): """使用线性模型预测结果.""" inX = np.append(inX, 1) # 增加偏置项 linear_model = np.dot(inX, weights) - prediction = 1 / (1 + np.exp(-linear_model)) - return 1.0 if prediction >= 0.5 else 2.0 # 返回1.0或2.0 + return 1.0 if linear_model >= 0 else 2.0 if __name__ == "__main__": - # 加载训练集 + # 示例:加载数据并训练模型 X_train, y_train = load_data("./data/horse-colic.data") + weights = train_logreg(X_train, y_train, learning_rate=0.001, iterations=5000) + + # 测试单个数据 + X_test, y_test = load_data("./data/horse-colic.test") + y_pred = predict_logreg(X_test[11], weights) - # 数据标准化 - scaler = StandardScaler() - X_train = scaler.fit_transform(X_train) + print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}") + # 训练逻辑回归模型 weights = train_logreg(X_train, y_train, learning_rate=0.001, iterations=5000)