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

This commit is contained in:
2024-11-14 16:57:56 +08:00
parent d23567f47a
commit 1b033a9e86
+21 -52
View File
@@ -28,59 +28,7 @@ name = "董秋"
# 这里写自己的代码实现
def train_svm(X, y, learning_rate=0.01, iterations=1000):
"""
支持向量机训练函数。
Args:
- X (numpy array): 特征数据。
- y (numpy array): 标签数据。
- other_params (str): 其它参数,可选设置。若需设置其它参数,必须设置其默认值,否则将**无法通过**自动评测,**成绩为零**。
Returns:
- numpy array: 训练得到的权重。
"""
n_samples, n_features = X.shape
n_classes = len(np.unique(y))
weights = np.zeros((n_classes, n_features))
for _ in range(iterations):
for idx, x_i in enumerate(X):
for c in range(n_classes):
y_i = 1 if y[idx] == c else -1
if y_i * (np.dot(weights[c], x_i)) < 1:
weights[c] += learning_rate * (y_i * x_i - (2 * 1/iterations) * weights[c])
else:
weights[c] -= learning_rate * (2 * 1/iterations) * weights[c]
return weights
def predict_svm(inX, weights):
"""
支持向量机预测函数。
Args:
- inX (numpy array): 输入待分类的样本。
- weights (numpy array): 训练得到的权重。
Returns:
- int: 预测的分类标签。
"""
scores = [np.dot(w, inX) for w in weights]
return np.argmax(scores)
# 这里也写自己的代码实现
def load_data(filepath):
"""
从文件中加载数据,若不自行正确实现,则无法通过评测,**不记录成绩**。
Args:
- directory (str): 数据文件路径。
Returns:
- np.array: 特征数据。
- np.array: 标签数据。
"""
data = []
labels = []
with open(filepath, 'r') as file:
@@ -101,6 +49,27 @@ def load_data(filepath):
return np.array(data), np.array(labels)
def train_svm(X, y, learning_rate=0.01, iterations=1000):
n_samples, n_features = X.shape
n_classes = len(np.unique(y))
weights = np.zeros((n_classes, n_features))
for _ in range(iterations):
for idx, x_i in enumerate(X):
for c in range(n_classes):
y_i = 1 if y[idx] == c else -1
if y_i * (np.dot(weights[c], x_i)) < 1:
weights[c] += learning_rate * (y_i * x_i - (2 * 1/iterations) * weights[c])
else:
weights[c] -= learning_rate * (2 * 1/iterations) * weights[c]
return weights
def predict_svm(inX, weights):
scores = [np.dot(w, inX) for w in weights]
return np.argmax(scores)
if __name__ == "__main__":
# 以下代码可用于测试,可自行随意修改