generated from LufsX/Experiment-LogReg
This commit is contained in:
+13
-13
@@ -35,7 +35,7 @@ def load_data(filepath):
|
|||||||
y = data[:, -1]
|
y = data[:, -1]
|
||||||
return X, y
|
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
|
n_samples, n_features = X.shape
|
||||||
weights = np.zeros(n_features + 1) # 增加一位用于偏置
|
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)
|
random_index = np.random.randint(n_samples)
|
||||||
X_i = X[random_index]
|
X_i = X[random_index]
|
||||||
y_i = y[random_index]
|
y_i = y[random_index]
|
||||||
|
|
||||||
linear_model = np.dot(X_i, weights)
|
linear_model = np.dot(X_i, weights)
|
||||||
prediction = 1 / (1 + np.exp(-linear_model)) # Sigmoid函数
|
dw = (linear_model - y_i) * X_i
|
||||||
error = prediction - y_i
|
weights -= learning_rate * dw
|
||||||
|
|
||||||
# 更新权重
|
|
||||||
weights -= learning_rate * error * X_i
|
|
||||||
|
|
||||||
return weights
|
return weights
|
||||||
|
|
||||||
@@ -59,16 +56,19 @@ def predict_logreg(inX, weights):
|
|||||||
"""使用线性模型预测结果."""
|
"""使用线性模型预测结果."""
|
||||||
inX = np.append(inX, 1) # 增加偏置项
|
inX = np.append(inX, 1) # 增加偏置项
|
||||||
linear_model = np.dot(inX, weights)
|
linear_model = np.dot(inX, weights)
|
||||||
prediction = 1 / (1 + np.exp(-linear_model))
|
return 1.0 if linear_model >= 0 else 2.0
|
||||||
return 1.0 if prediction >= 0.5 else 2.0 # 返回1.0或2.0
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
# 加载训练集
|
# 示例:加载数据并训练模型
|
||||||
X_train, y_train = load_data("./data/horse-colic.data")
|
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)
|
||||||
|
|
||||||
# 数据标准化
|
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")
|
||||||
scaler = StandardScaler()
|
|
||||||
X_train = scaler.fit_transform(X_train)
|
|
||||||
|
|
||||||
# 训练逻辑回归模型
|
# 训练逻辑回归模型
|
||||||
weights = train_logreg(X_train, y_train, learning_rate=0.001, iterations=5000)
|
weights = train_logreg(X_train, y_train, learning_rate=0.001, iterations=5000)
|
||||||
|
|||||||
Reference in New Issue
Block a user