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

This commit is contained in:
2024-11-14 16:56:38 +08:00
parent 55718a87d8
commit a4bb608bd4
+38 -8
View File
@@ -23,12 +23,12 @@ import numpy as np
姓名请直接**填写中文**
例如: name = "张三"
"""
id = "202210423xxx"
name = "test_name"
id = "202210423222"
name = "邓龙树"
# 这里写自己的代码实现
def train_svm(X, y, other_params="你自己设置一些其它参数"):
def train_svm(X, y, learning_rate=0.001, iterations=1000):
"""
支持向量机训练函数。
@@ -40,6 +40,20 @@ def train_svm(X, y, other_params="你自己设置一些其它参数"):
Returns:
- numpy array: 训练得到的权重。
"""
n_samples, n_features = X.shape
# 初始化权重向量
weights = np.zeros(n_features)
eta = 0.001 # 学习率
epochs = 1000 # 迭代次数
for _ in range(epochs):
for idx, x_i in enumerate(X):
condition = y[idx] * (np.dot(x_i, weights))
if condition < 1:
weights = weights + eta * ( (y[idx] * x_i) - (2 / (n_samples * epochs)) * weights)
else:
weights = weights + eta * (- (2 / (n_samples * epochs)) * weights)
return weights
def predict_svm(inX, weights):
@@ -53,9 +67,10 @@ def predict_svm(inX, weights):
Returns:
- int: 预测的分类标签。
"""
prediction = np.sign(np.dot(inX, weights))
return prediction if prediction!= 0 else -1
# 这里也写自己的代码实现
def load_data(filepath):
"""
从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。
@@ -67,10 +82,22 @@ def load_data(filepath):
- np.array: 特征数据。
- np.array: 标签数据。
"""
data = []
labels = []
with open(filepath, 'r') as file:
lines = file.readlines()
for line in lines:
line = line.strip().split()
if '?' not in line: # 只处理不包含缺失值的行
features = [float(x) for x in line[:-1]]
label = float(line[-1])
if label == 0:
label = -1 # 将类别0转换为 -1 ,符合SVM二分类的约定
data.append(features)
labels.append(label)
return np.array(data), np.array(labels)
if __name__ == "__main__":
# 以下代码可用于测试,可自行随意修改
# 加载训练集
X_train, y_train = load_data("./data/horse-colic.data")
@@ -78,8 +105,11 @@ if __name__ == "__main__":
X_test, y_test = load_data("./data/horse-colic.test")
# 训练支持向量机模型
weights = train_svm(X_train, y_train, learning_rate=0.01, iterations=1000)
weights = train_svm(X_train, y_train, learning_rate=0.001, iterations=1000)
# 测试单个数据
y_pred = predict_svm(X_test[11], weights)
for i in range(len(X_test)):
y_pred = predict_svm(X_test[i], weights)
print(f"预测结果: {y_pred}, 实际结果: {y_test[i]}")
print(f"预测结果: {y_pred}, 实际结果: {y_test[11]}")