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

This commit is contained in:
2024-11-14 17:16:49 +08:00
parent 65926187ab
commit 65d16c1d6e
+35 -2
View File
@@ -28,9 +28,42 @@ name = "章程鸿"
# 这里写自己的代码实现
import numpy as np
from sklearn.svm import SVC
from sklearn.preprocessing import StandardScaler
import numpy as np
def load_data(filepath):
"""
从文件中加载数据,并进行必要的预处理,处理缺失值。
Args:
- filepath (str): 数据文件路径。
Returns:
- X (numpy array): 特征数据。
- y (numpy array): 标签数据。
"""
# 加载数据,假设分隔符是空格或者制表符
data = np.genfromtxt(filepath, delimiter=' ', dtype=str)
# 处理缺失值,将 '?' 替换为 np.nan
data[data == '?'] = np.nan
# 将非数值字段转为浮动类型
data = data.astype(np.float64)
# 选择特征和标签
X = data[:, :-1] # 特征数据(假设最后一列是目标变量)
y = data[:, 23] # 特征23作为目标变量
# 转换目标变量为 1 (lived), 2 (died), 3 (euthanized)
y = np.where(y == 2, 0, y) # 2 -> 0 (died -> death)
y = np.where(y == 3, 0, y) # 3 -> 0 (euthanized -> death)
# 将缺失值填充为 0(或其他合适的值)
X = np.nan_to_num(X, nan=0)
return X, y
def train_svm(X, y):
"""
@@ -42,6 +75,7 @@ def train_svm(X, y):
Returns:
- model (SVC): 训练得到的 SVM 模型。
- scaler (StandardScaler): 用于后续预测的数据标准化器。
"""
# 数据标准化
scaler = StandardScaler()
@@ -89,4 +123,3 @@ if __name__ == "__main__":
accuracy = correct / len(X_test) * 100
print(f"测试集准确率: {accuracy}%")