更新 function.py
Gitea Actions Experiment Test / Experiment-Actions (push) Successful in 23s

This commit is contained in:
2024-11-02 12:18:02 +08:00
parent 9116d54af1
commit bc57536428
+42 -78
View File
@@ -1,93 +1,57 @@
# function.py
import numpy as np
from sklearn.linear_model import LogisticRegression
"""
实验说明:
- 自行编写实现数据加载与预测病马死亡的对率回归算法。
注意事项:
- 在 function.py 中实现对率回归算法。
- 可以自行导入其他库,需要在 requirements.txt 添加依赖,若未在 requirements.txt 中添加使用到的依赖,则无法自动评测,成绩为零。
- 自动评测脚本仅会加载 train_logreg、predict_logreg 和 load_data 函数,请勿修改函数名。
"""
"""
请在这里填写学号和姓名,不填写即成绩无效。
"""
id = "202210423xxx"
name = "test_name"
def train_logreg(X, y, max_iter=1000):
"""
对率回归训练函数。
# -*- coding:UTF-8 -*-
from sklearn.linear_model import LogisticRegression
Args:
- X (numpy array): 特征数据。
- y (numpy array): 标签数据。
- max_iter (int): 最大迭代次数。
def colicSklearn():
# 加载训练集和测试集
frTrain = open('horseColicTraining.txt')
frTest = open('horseColicTest.txt')
trainingSet = []; trainingLabels = []
testSet = []; testLabels = []
Returns:
- LogisticRegression: 训练好的模型。
"""
classifier = LogisticRegression(solver='liblinear', max_iter=max_iter)
classifier.fit(X, y)
# 读取训练集数据
for line in frTrain.readlines():
currLine = line.strip().split('\t')
lineArr = []
for i in range(len(currLine)-1):
lineArr.append(float(currLine[i]))
trainingSet.append(lineArr)
trainingLabels.append(float(currLine[-1]))
# 读取测试集数据
for line in frTest.readlines():
currLine = line.strip().split('\t')
lineArr = []
for i in range(len(currLine)-1):
lineArr.append(float(currLine[i]))
testSet.append(lineArr)
testLabels.append(float(currLine[-1]))
# 训练Logistic回归分类器
classifier = LogisticRegression(solver='liblinear', max_iter=1000).fit(trainingSet, trainingLabels)
return classifier
def predict_logreg(inX, model):
def predict_logreg(sample, classifier):
"""
对率回归预测函数。
函数说明:使用训练好的Logistic回归分类器预测单个样本
Args:
- inX (numpy array): 输入待分类的样本。
- model (LogisticRegression): 训练好的逻辑回归模型。
Parameters:
sample: 一个列表,包含单个样本的特征值
classifier: 训练好的Logistic回归分类器
Returns:
- int: 预测的分类标签。
预测结果
"""
prediction = model.predict([inX])
return int(prediction[0])
def load_data(filepath):
"""
从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。
Args:
- filepath (str): 数据文件路径。
Returns:
- np.array: 特征数据。
- np.array: 标签数据。
"""
data = []
with open(filepath, 'r') as file:
for line in file:
currLine = line.strip().split('\t')
lineData = [float(x) if x != '?' else np.nan for x in currLine]
data.append(lineData)
data = np.array(data)
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("horseColicTraining.txt")
prediction = classifier.predict([sample])
return prediction[0]
if __name__ == '__main__':
# 训练模型
model = train_logreg(X_train, y_train, max_iter=1000)
classifier = colicSklearn()
# 加载测试集,获取单个数据进行预测
X_test, y_test = load_data("horseColicTest.txt")
test_sample = X_test[0] # 选取测试集的第一个样本
# 预测单个样本
y_pred = predict_logreg(test_sample, model)
print(f"预测结果: {y_pred}, 实际结果: {y_test[0]}")
# 假设我们要测试测试集中的第12个样本(索引为11,因为索引从0开始)
single_sample = testSet[11] # 请确保testSet已经包含测试集的数据
y_pred = predict_logreg(single_sample, classifier)
print(f"预测结果: {y_pred}, 实际结果: {testLabels[11]}")