generated from LufsX/Experiment-LogReg
This commit is contained in:
+23
-45
@@ -10,62 +10,43 @@ from sklearn.linear_model import LogisticRegression
|
||||
- 在 function.py 中实现对率回归算法。
|
||||
- 可以自行导入其他库,需要在 requirements.txt 添加依赖,若未在 requirements.txt 中添加使用到的依赖,则无法自动评测,成绩为零。
|
||||
- 自动评测脚本仅会加载 train_logreg、predict_logreg 和 load_data 函数,请勿修改函数名。
|
||||
|
||||
测评环境:
|
||||
- CPU: Intel Xeon(R) CPU E3-1231 v3 @ 3.40GHz
|
||||
- OS: Ubuntu 22.04.4 LTS
|
||||
- Python: 3.10.12
|
||||
- numpy: 2.1.1
|
||||
"""
|
||||
|
||||
"""
|
||||
请在这里填写学号和姓名,不填写即成绩无效。
|
||||
"""
|
||||
id = "202210423230"
|
||||
name = "尹家立"
|
||||
id = "202210423xxx"
|
||||
name = "test_name"
|
||||
|
||||
# Sigmoid function
|
||||
def sigmoid(inX):
|
||||
"""Sigmoid激活函数"""
|
||||
return 1.0 / (1 + np.exp(-inX))
|
||||
|
||||
def train_logreg(X, y, learning_rate=0.01, iterations=5000, solver='liblinear'):
|
||||
def train_logreg(X, y, max_iter=1000):
|
||||
"""
|
||||
对率回归训练函数。
|
||||
|
||||
Args:
|
||||
- X (numpy array): 特征数据。
|
||||
- y (numpy array): 标签数据。
|
||||
- learning_rate (float): 学习速率。
|
||||
- iterations (int): 最大迭代次数。
|
||||
- solver (str): 使用的求解器。默认值为'liblinear'。
|
||||
- max_iter (int): 最大迭代次数。
|
||||
|
||||
Returns:
|
||||
- numpy array: 训练得到的权重。
|
||||
- LogisticRegression: 训练好的模型。
|
||||
"""
|
||||
# 使用liblinear作为求解器进行对率回归训练
|
||||
model = LogisticRegression(solver=solver, max_iter=iterations)
|
||||
model.fit(X, y)
|
||||
|
||||
# 返回模型的系数作为权重
|
||||
return model.coef_.flatten()
|
||||
classifier = LogisticRegression(solver='liblinear', max_iter=max_iter)
|
||||
classifier.fit(X, y)
|
||||
return classifier
|
||||
|
||||
def predict_logreg(inX, weights):
|
||||
def predict_logreg(inX, model):
|
||||
"""
|
||||
对率回归预测函数。
|
||||
|
||||
Args:
|
||||
- inX (numpy array): 输入待分类的样本。
|
||||
- weights (numpy array): 训练得到的权重。
|
||||
- model (LogisticRegression): 训练好的逻辑回归模型。
|
||||
|
||||
Returns:
|
||||
- int: 预测的分类标签。
|
||||
"""
|
||||
prob = sigmoid(np.dot(inX, weights)) # 计算预测概率
|
||||
return 1 if prob > 0.5 else 0 # 返回二分类标签
|
||||
|
||||
import re
|
||||
|
||||
prediction = model.predict([inX])
|
||||
return int(prediction[0])
|
||||
|
||||
def load_data(filepath):
|
||||
"""
|
||||
@@ -81,9 +62,7 @@ def load_data(filepath):
|
||||
data = []
|
||||
with open(filepath, 'r') as file:
|
||||
for line in file:
|
||||
# 使用正则表达式按空白字符分隔
|
||||
currLine = re.split(r"\s+", line.strip())
|
||||
# 将数据转换为浮点数,如果是 "?" 则替换为 NaN
|
||||
currLine = line.strip().split('\t')
|
||||
lineData = [float(x) if x != '?' else np.nan for x in currLine]
|
||||
data.append(lineData)
|
||||
|
||||
@@ -91,25 +70,24 @@ def load_data(filepath):
|
||||
X = data[:, :-1]
|
||||
y = data[:, -1]
|
||||
|
||||
# 使用简单的列均值填补缺失值
|
||||
# 填充缺失值
|
||||
col_mean = np.nanmean(X, axis=0)
|
||||
inds = np.where(np.isnan(X))
|
||||
X[inds] = np.take(col_mean, inds[1])
|
||||
|
||||
return X, y.astype(int)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 以下代码可用于测试,可自行随意修改
|
||||
# 加载训练集
|
||||
X_train, y_train = load_data("./data/horse-colic.data")
|
||||
X_train, y_train = load_data("horseColicTraining.txt")
|
||||
|
||||
# 加载测试集
|
||||
X_test, y_test = load_data("./data/horse-colic.test")
|
||||
# 训练模型
|
||||
model = train_logreg(X_train, y_train, max_iter=1000)
|
||||
|
||||
# 训练对率回归模型
|
||||
weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=1000)
|
||||
# 加载测试集,获取单个数据进行预测
|
||||
X_test, y_test = load_data("horseColicTest.txt")
|
||||
test_sample = X_test[0] # 选取测试集的第一个样本
|
||||
|
||||
# 测试单个数据
|
||||
y_pred = predict_logreg(X_test[11], weights)
|
||||
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")
|
||||
# 预测单个样本
|
||||
y_pred = predict_logreg(test_sample, model)
|
||||
print(f"预测结果: {y_pred}, 实际结果: {y_test[0]}")
|
||||
|
||||
Reference in New Issue
Block a user