generated from LufsX/Experiment-LogReg
This commit is contained in:
+29
-44
@@ -1,85 +1,70 @@
|
|||||||
import numpy as np
|
import numpy as np
|
||||||
from sklearn.linear_model import LogisticRegression
|
|
||||||
from sklearn.impute import SimpleImputer
|
|
||||||
|
|
||||||
"""
|
|
||||||
实验说明:
|
|
||||||
- 自行编写实现数据加载与预测病马死亡的对率回归算法。
|
|
||||||
|
|
||||||
注意事项:
|
|
||||||
- 在 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 = "202210423xxx" # 请填写学号
|
id = "202210423xxx" # 请填写学号
|
||||||
name = "test_name" # 请填写姓名
|
name = "test_name" # 请填写姓名
|
||||||
|
|
||||||
|
def sigmoid(z):
|
||||||
|
"""计算Sigmoid函数值"""
|
||||||
|
return 1 / (1 + np.exp(-z))
|
||||||
|
|
||||||
def train_logreg(X, y, max_iter=1000, C=1.0):
|
def train_logreg(X, y, learning_rate=0.01, iterations=1000):
|
||||||
"""
|
"""
|
||||||
对率回归训练函数,使用sklearn的LogisticRegression。
|
对率回归训练函数。
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
- X (numpy array): 特征数据。
|
- X (numpy array): 特征数据。
|
||||||
- y (numpy array): 标签数据。
|
- y (numpy array): 标签数据。
|
||||||
- max_iter (int): 最大迭代次数。
|
- learning_rate (float): 学习率,默认为0.01。
|
||||||
- C (float): 正则化强度。
|
- iterations (int): 梯度下降迭代次数,默认为1000。
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
- sklearn LogisticRegression: 训练好的模型。
|
- numpy array: 训练得到的权重。
|
||||||
"""
|
"""
|
||||||
# 使用sklearn的LogisticRegression模型
|
weights = np.zeros(X.shape[1])
|
||||||
model = LogisticRegression(max_iter=max_iter, C=C)
|
|
||||||
model.fit(X, y)
|
|
||||||
return model
|
|
||||||
|
|
||||||
|
for i in range(iterations):
|
||||||
|
predictions = sigmoid(np.dot(X, weights))
|
||||||
|
errors = y - predictions
|
||||||
|
weights += learning_rate * np.dot(X.T, errors)
|
||||||
|
|
||||||
def predict_logreg(inX, model):
|
return weights
|
||||||
|
|
||||||
|
def predict_logreg(inX, weights):
|
||||||
"""
|
"""
|
||||||
对率回归预测函数。
|
对率回归预测函数。
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
- inX (numpy array): 输入待分类的样本。
|
- inX (numpy array): 输入待分类的样本。
|
||||||
- model (LogisticRegression): 训练得到的LogisticRegression模型。
|
- weights (numpy array): 训练得到的权重。
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
- int: 预测的分类标签。
|
- int: 预测的分类标签。
|
||||||
"""
|
"""
|
||||||
return int(model.predict(inX.reshape(1, -1))[0])
|
probability = sigmoid(np.dot(inX, weights))
|
||||||
|
return 1 if probability >= 0.5 else 0
|
||||||
|
|
||||||
def load_data(filepath):
|
def load_data(filepath):
|
||||||
"""
|
"""
|
||||||
从文件中加载数据并填充缺失值。
|
从文件中加载数据,并填充缺失值。
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
- filepath (str): 数据文件路径。
|
- filepath (str): 数据文件路径。
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
- np.array: 填充缺失值后的特征数据。
|
- np.array: 特征数据。
|
||||||
- np.array: 标签数据。
|
- np.array: 标签数据。
|
||||||
"""
|
"""
|
||||||
# 加载数据
|
|
||||||
data = np.loadtxt(filepath, delimiter=",", dtype=float)
|
data = np.loadtxt(filepath, delimiter=",", dtype=float)
|
||||||
|
|
||||||
# 分割特征和标签
|
# 检查缺失值并使用列均值进行填充
|
||||||
X = data[:, :-1] # 特征
|
col_means = np.nanmean(data, axis=0)
|
||||||
y = data[:, -1] # 标签
|
indices = np.where(np.isnan(data))
|
||||||
|
data[indices] = np.take(col_means, indices[1])
|
||||||
# 填充缺失值,使用列的平均值
|
|
||||||
imputer = SimpleImputer(strategy="mean")
|
|
||||||
X = imputer.fit_transform(X)
|
|
||||||
|
|
||||||
|
X = data[:, :-1]
|
||||||
|
y = data[:, -1]
|
||||||
return X, y
|
return X, y
|
||||||
|
|
||||||
|
|
||||||
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")
|
||||||
@@ -88,8 +73,8 @@ if __name__ == "__main__":
|
|||||||
X_test, y_test = load_data("./data/horse-colic.test")
|
X_test, y_test = load_data("./data/horse-colic.test")
|
||||||
|
|
||||||
# 训练对率回归模型
|
# 训练对率回归模型
|
||||||
model = train_logreg(X_train, y_train, max_iter=1000, C=1.0)
|
weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=1000)
|
||||||
|
|
||||||
# 测试单个数据
|
# 测试单个数据
|
||||||
y_pred = predict_logreg(X_test[11], model)
|
y_pred = predict_logreg(X_test[11], weights)
|
||||||
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")
|
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")
|
||||||
|
|||||||
Reference in New Issue
Block a user