test
Gitea Actions Test / Challenge-Actions (push) Has been cancelled

This commit is contained in:
2024-11-13 17:25:37 +08:00
parent 3ce2510e4f
commit 8aa87599fd
3 changed files with 56 additions and 9 deletions
+2
View File
@@ -1,3 +1,5 @@
__pycache__ __pycache__
main.py main.py
病马数据集* 病马数据集*
horse-colic.data
horse-colic.test
+53 -9
View File
@@ -1,5 +1,6 @@
# function.py # function.py
import numpy as np import numpy as np
from sklearn.preprocessing import StandardScaler
""" """
挑战说明: 挑战说明:
@@ -23,12 +24,12 @@ import numpy as np
姓名请直接**填写中文** 姓名请直接**填写中文**
例如: name = "张三" 例如: name = "张三"
""" """
id = "202210423xxx" id = "202210423229"
name = "test_name" name = "向兴宇"
# 这里写自己的代码实现 # 这里写自己的代码实现
def train_svm(X, y, other_params="你自己设置一些其它参数"): def train_svm(X, y, C=0.20, max_iter=1000, learning_rate=0.01):
""" """
支持向量机训练函数。 支持向量机训练函数。
@@ -40,9 +41,20 @@ def train_svm(X, y, other_params="你自己设置一些其它参数"):
Returns: Returns:
- numpy array: 训练得到的权重。 - numpy array: 训练得到的权重。
""" """
m, n = X.shape
w = np.zeros(n)
b = 0
for i in range(max_iter):
for j in range(m):
if y[j] * (np.dot(X[j], w) + b) < 1:
w = w - learning_rate * (2 * w - C * y[j] * X[j])
b = b + learning_rate * C * y[j]
else:
w = w - learning_rate * 2 * w
return (w, b)
def predict_svm(inX, weights): def predict_svm(inX, weight):
""" """
支持向量机预测函数。 支持向量机预测函数。
@@ -53,6 +65,8 @@ def predict_svm(inX, weights):
Returns: Returns:
- int: 预测的分类标签。 - int: 预测的分类标签。
""" """
result = np.dot(inX, weight[0]) + weight[1]
return 1 if result > 0 else -1
# 这里也写自己的代码实现 # 这里也写自己的代码实现
@@ -67,6 +81,22 @@ def load_data(filepath):
- np.array: 特征数据。 - np.array: 特征数据。
- np.array: 标签数据。 - np.array: 标签数据。
""" """
# 使用 np.genfromtxt 加载数据,处理缺失值 '?' 为 -1
data = np.genfromtxt(filepath, delimiter=" ", missing_values="?", filling_values=0)
# 分离特征标签
labels = data[:, 22].astype(int)
# 删除无用特征
data = np.delete(data, [2] + list(range(22, 28)), axis=1)
# 合并死亡
labels = np.where((labels == 2) | (labels == 3), 0, labels)
# 数据标准化
scaler = StandardScaler()
data = scaler.fit_transform(data)
return data, labels
if __name__ == "__main__": if __name__ == "__main__":
@@ -77,9 +107,23 @@ if __name__ == "__main__":
# 加载测试集 # 加载测试集
X_test, y_test = load_data("./data/horse-colic.test") X_test, y_test = load_data("./data/horse-colic.test")
# 训练支持向量机模型 before_acc = 0.0
weights = train_svm(X_train, y_train, learning_rate=0.01, iterations=1000) for x in range(1, 2):
# 训练对率回归模型
np.random.seed(x)
weights = train_svm(X_train, y_train)
# 测试单个数据 # 评估模型准确率
y_pred = predict_svm(X_test[11], weights) correct = 0
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}") for i in range(X_test.shape[0]):
pred = predict_svm(X_test[i], weights)
if pred == y_test[i]:
correct += 1
# else:
# print(f"{i+1}: P: {pred} A: {y_test[i]}")
# 准确率
acc = correct / X_test.shape[0]
if acc >= before_acc:
before_acc = acc
print(f"seed: {x} 准确率:{acc}")
+1
View File
@@ -1,2 +1,3 @@
numpy==2.1.1 numpy==2.1.1
requests==2.32.3 requests==2.32.3
scikit-learn