generated from LufsX/Experiment-LogReg
116 lines
4.0 KiB
Python
116 lines
4.0 KiB
Python
# function.py
|
|
import numpy as np
|
|
import pandas as pd
|
|
from sklearn.impute import SimpleImputer
|
|
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 = "202210423112"
|
|
name = "严锡好"
|
|
|
|
|
|
# 这里写自己的代码实现
|
|
# sigmoid函数,用于逻辑回归模型中将线性输出转换为概率
|
|
def sigmoid(x):
|
|
return 1 / (1 + np.exp(-x))
|
|
|
|
# train_logreg函数,用于训练逻辑回归模型
|
|
def train_logreg(X, y, learning_rate=0.01, iterations=1000, regularization=0.01):
|
|
m, n = X.shape # 获取样本数量和特征数量
|
|
weights = np.zeros(n) # 初始化权重为0
|
|
for _ in range(iterations): # 迭代指定次数
|
|
linear_model = np.dot(X, weights) # 计算线性模型的输出
|
|
y_predicted = sigmoid(linear_model) # 将线性输出转换为概率
|
|
gradient = np.dot(X.T, (y_predicted - y)) / m + regularization * weights # 计算梯度
|
|
weights -= learning_rate * gradient # 更新权重
|
|
return weights # 返回训练好的权重
|
|
|
|
# predict_logreg函数,用于使用训练好的权重进行预测
|
|
def predict_logreg(inX, weights):
|
|
linear_output = np.dot(inX, weights) # 计算线性输出
|
|
probability = sigmoid(linear_output) # 将线性输出转换为概率
|
|
return 1 if probability > 0.5 else 0 # 返回预测结果,大于0.5为1,否则为0
|
|
|
|
# preprocess_data函数,用于预处理数据
|
|
def preprocess_data(X, y):
|
|
# 合并目标变量的类别,将2和3都转换为0
|
|
y[y == 2] = 0
|
|
y[y == 3] = 0
|
|
|
|
# 删除特征3和特征24~28
|
|
X = np.delete(X, [3], axis=1)
|
|
X = X[:, :23]
|
|
|
|
return X, y # 返回预处理后的数据
|
|
|
|
# load_data函数,用于加载数据
|
|
def load_data(filepath):
|
|
# 使用Pandas读取数据,可以更好地处理缺失值和字符串
|
|
try:
|
|
data = pd.read_csv(filepath, header=None, sep=r'\s+', on_bad_lines='skip')
|
|
except pd.errors.ParserError as e:
|
|
print(f"Error parsing file: {e}")
|
|
return None, None
|
|
|
|
# 将'?'替换为np.nan
|
|
data.replace('?', np.nan, inplace=True)
|
|
|
|
# 使用SimpleImputer填充缺失值
|
|
imputer = SimpleImputer(missing_values=np.nan, strategy='constant', fill_value=0)
|
|
data.iloc[:, :-1] = imputer.fit_transform(data.iloc[:, :-1])
|
|
|
|
# 将所有列转换为数值类型
|
|
for col in data.columns[:-1]:
|
|
data[col] = pd.to_numeric(data[col], errors='coerce')
|
|
|
|
X = data.iloc[:, :-1].values # 特征数据
|
|
y = data.iloc[:, -1].values.astype(int) # 目标变量
|
|
|
|
# 预处理数据
|
|
X, y = preprocess_data(X, y)
|
|
|
|
return X, y # 返回加载和预处理后的数据
|
|
|
|
# main函数,程序的入口点
|
|
def main():
|
|
# 假设data文件夹和function.py在同一目录下
|
|
X_train, y_train = load_data("./data/horse-colic.data")
|
|
X_test, y_test = load_data("./data/horse-colic.test")
|
|
|
|
if X_train is not None and X_test is not None:
|
|
# 特征缩放
|
|
scaler = StandardScaler()
|
|
X_train = scaler.fit_transform(X_train)
|
|
X_test = scaler.transform(X_test)
|
|
|
|
# 训练模型
|
|
weights = train_logreg(X_train, y_train, learning_rate=0.01, iterations=1000, regularization=0.1)
|
|
|
|
# 预测测试集
|
|
y_pred = [predict_logreg(x, weights) for x in X_test]
|
|
|
|
# 计算准确率
|
|
accuracy = np.mean(y_pred == y_test)
|
|
print(f"准确率: {accuracy}")
|
|
|
|
if __name__ == "__main__":
|
|
main() # 调用main函数,运行程序 |