generated from LufsX/Experiment-LogReg
This commit is contained in:
+37
-90
@@ -1,104 +1,51 @@
|
|||||||
import os
|
|
||||||
import numpy as np
|
import numpy as np
|
||||||
|
from sklearn.linear_model import LogisticRegression
|
||||||
"""
|
from sklearn.preprocessing import StandardScaler
|
||||||
实验说明:
|
|
||||||
- 自行编写实现数据加载与预测病马死亡的对率回归算法。
|
|
||||||
|
|
||||||
注意事项:
|
|
||||||
- 在 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 = "202210218225"
|
id = "202210218225"
|
||||||
name = "周水源"
|
name = "周水源"
|
||||||
|
|
||||||
|
def train_logreg(X, y, random_state=42):
|
||||||
|
model = LogisticRegression(solver='liblinear', random_state=random_state)
|
||||||
|
model.fit(X, y)
|
||||||
|
return model
|
||||||
|
|
||||||
# 这里写自己的代码实现
|
def predict_logreg(inX, model):
|
||||||
import numpy as np
|
return int(model.predict([inX])[0])
|
||||||
from sklearn.metrics import accuracy_score
|
|
||||||
|
|
||||||
# 定义sigmoid函数
|
def load_data(filepath):
|
||||||
def sigmoid(z):
|
data = np.genfromtxt(filepath, delimiter=' ', missing_values='?', filling_values=0)
|
||||||
return 1 / (1 + np.exp(-z))
|
labels = data[:, -1].astype(int)
|
||||||
|
data = data[:, :-1]
|
||||||
|
labels = np.where((labels == 2) | (labels == 3), 0, labels)
|
||||||
|
if data.shape[1] >= 3:
|
||||||
|
data = np.delete(data, 2, axis=1)
|
||||||
|
scaler = StandardScaler()
|
||||||
|
data = scaler.fit_transform(data)
|
||||||
|
return data, labels
|
||||||
|
|
||||||
# 训练逻辑回归模型
|
# 测试代码
|
||||||
def train_logreg(X, y, learning_rate, iterations=1000):
|
if __name__ == "__main__":
|
||||||
m, n = X.shape
|
# 指定数据文件路径
|
||||||
weights = np.zeros(n)
|
filepath = "./data/horse-colic.data"
|
||||||
bias = 0
|
|
||||||
for _ in range(iterations):
|
|
||||||
z = np.dot(X, weights) + bias
|
|
||||||
h = sigmoid(z)
|
|
||||||
dw = (1/m) * np.dot(X.T, (h - y))
|
|
||||||
db = (1/m) * np.sum(h - y)
|
|
||||||
weights -= learning_rate * dw
|
|
||||||
bias -= learning_rate * db
|
|
||||||
return weights, bias
|
|
||||||
|
|
||||||
# 使用逻辑回归模型进行预测
|
|
||||||
def predict_logreg(inX, weights, bias):
|
|
||||||
z = np.dot(inX, weights) + bias
|
|
||||||
h = sigmoid(z)
|
|
||||||
return 1 if h >= 0.5 else 0
|
|
||||||
|
|
||||||
# 加载数据
|
# 加载数据
|
||||||
def load_data(filepath):
|
X, y = load_data(filepath)
|
||||||
data = []
|
print("数据加载成功。")
|
||||||
with open(filepath, 'r') as file:
|
|
||||||
for line in file:
|
|
||||||
cleaned_line = line.strip().replace('?', '0')
|
|
||||||
values = [float(x) for x in cleaned_line.split()]
|
|
||||||
if values[22] in [2, 3]:
|
|
||||||
values[22] = 0
|
|
||||||
new_values = values[:2] + values[3:23]
|
|
||||||
data.append(new_values)
|
|
||||||
data = np.array(data)
|
|
||||||
X = data[:, :-1]
|
|
||||||
y = data[:, -1]
|
|
||||||
return X, y
|
|
||||||
|
|
||||||
# 寻找最佳学习率
|
# 训练模型
|
||||||
def find_best_learning_rate(X, y, learning_rates, iterations=1000):
|
model = train_logreg(X, y)
|
||||||
best_accuracy = 0
|
print("模型训练完成。")
|
||||||
best_learning_rate = None
|
|
||||||
best_weights = None
|
|
||||||
best_bias = None
|
|
||||||
for rate in learning_rates:
|
|
||||||
weights, bias = train_logreg(X, y, rate, iterations)
|
|
||||||
y_pred = np.array([predict_logreg(x, weights, bias) for x in X])
|
|
||||||
accuracy = accuracy_score(y, y_pred)
|
|
||||||
if accuracy > best_accuracy:
|
|
||||||
best_accuracy = accuracy
|
|
||||||
best_learning_rate = rate
|
|
||||||
best_weights = weights
|
|
||||||
best_bias = bias
|
|
||||||
return best_learning_rate, best_accuracy, best_weights, best_bias
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
# 随机选择一个样本进行预测测试
|
||||||
X_train, y_train = load_data("./data/horse-colic.data")
|
sample = X[0]
|
||||||
X_test, y_test = load_data("./data/horse-colic.test")
|
actual_label = y[0]
|
||||||
|
predicted_label = predict_logreg(sample, model)
|
||||||
|
print(f"预测结果: {predicted_label}, 实际结果: {actual_label}")
|
||||||
|
|
||||||
# 定义要尝试的学习率列表
|
# 计算测试集上的准确率
|
||||||
learning_rates = np.linspace(0.001, 0.1, 50)
|
correct_predictions = sum(predict_logreg(X[i], model) == y[i] for i in range(len(y)))
|
||||||
|
accuracy = correct_predictions / len(y)
|
||||||
# 寻找最佳学习率
|
print(f"测试集准确率: {accuracy:.2f}")
|
||||||
best_learning_rate, best_accuracy, best_weights, best_bias = find_best_learning_rate(X_train, y_train, learning_rates)
|
|
||||||
|
|
||||||
print(f"最佳学习率: {best_learning_rate}")
|
|
||||||
print(f"最佳准确率: {best_accuracy}")
|
|
||||||
|
|
||||||
# 使用最佳权重和偏置进行预测
|
|
||||||
y_pred = predict_logreg(X_test[11], best_weights, best_bias)
|
|
||||||
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")
|
|
||||||
Reference in New Issue
Block a user