generated from LufsX/Experiment-LogReg
This commit is contained in:
+5
-21
@@ -36,14 +36,9 @@ def load_data(filepath):
|
|||||||
- np.array: 特征数据。
|
- np.array: 特征数据。
|
||||||
- np.array: 标签数据。
|
- np.array: 标签数据。
|
||||||
"""
|
"""
|
||||||
# 使用np.genfromtxt加载数据,它可以自动处理缺失值
|
|
||||||
data = np.genfromtxt(filepath, delimiter=',', skip_header=1, filling_values=np.nan)
|
data = np.genfromtxt(filepath, delimiter=',', skip_header=1, filling_values=np.nan)
|
||||||
|
|
||||||
# 分离特征和标签
|
# 分离特征和标签
|
||||||
# 确保data不是一维数组
|
|
||||||
if data.ndim == 1:
|
|
||||||
data = data.reshape(1, -1) # 将其转换为二维数组,如果它是一维的
|
|
||||||
|
|
||||||
X = data[:, :-1]
|
X = data[:, :-1]
|
||||||
y = data[:, -1].flatten() # 确保y是一维数组
|
y = data[:, -1].flatten() # 确保y是一维数组
|
||||||
|
|
||||||
@@ -84,11 +79,15 @@ def train_logreg(X, y, learning_rate=0.01, iterations=1000):
|
|||||||
# 初始化权重
|
# 初始化权重
|
||||||
weights = np.zeros(X.shape[1])
|
weights = np.zeros(X.shape[1])
|
||||||
|
|
||||||
|
# 检查y是否为空
|
||||||
|
if len(y) == 0:
|
||||||
|
raise ValueError("标签数组y为空")
|
||||||
|
|
||||||
for _ in range(iterations):
|
for _ in range(iterations):
|
||||||
# 计算预测值
|
# 计算预测值
|
||||||
predictions = sigmoid(np.dot(X, weights))
|
predictions = sigmoid(np.dot(X, weights))
|
||||||
# 计算梯度
|
# 计算梯度
|
||||||
gradient = np.dot(X.T, (predictions - y)) / len(y)
|
gradient = np.dot(X.T, (predictions - y)) / max(len(y), 1) # 防止除以零
|
||||||
# 更新权重
|
# 更新权重
|
||||||
weights -= learning_rate * gradient
|
weights -= learning_rate * gradient
|
||||||
|
|
||||||
@@ -108,18 +107,3 @@ def predict_logreg(inX, weights):
|
|||||||
inX = np.c_[1, inX] # 添加截距项
|
inX = np.c_[1, inX] # 添加截距项
|
||||||
prob = sigmoid(np.dot(inX, weights))
|
prob = sigmoid(np.dot(inX, weights))
|
||||||
return 1 if prob > 0.5 else 0
|
return 1 if prob > 0.5 else 0
|
||||||
|
|
||||||
# 移除以下测试代码,仅在本地测试时使用
|
|
||||||
# if __name__ == "__main__":
|
|
||||||
# # 加载训练集
|
|
||||||
# X_train, y_train = load_data("./data/horse-colic.data")
|
|
||||||
#
|
|
||||||
# # 加载测试集
|
|
||||||
# X_test, y_test = load_data("./data/horse-colic.test")
|
|
||||||
#
|
|
||||||
# # 训练对率回归模型
|
|
||||||
# weights = train_logreg(X_train, y_train)
|
|
||||||
#
|
|
||||||
# # 测试单个数据
|
|
||||||
# y_pred = predict_logreg(X_test[11], weights)
|
|
||||||
# print(f"预测结果: {y_pred}, 实际结果: {int(y_test[11])}")
|
|
||||||
Reference in New Issue
Block a user