generated from LufsX/Challenge-SVM
This commit is contained in:
+10
-11
@@ -3,31 +3,30 @@ import numpy as np
|
|||||||
id = "202210423201"
|
id = "202210423201"
|
||||||
name = "陈瑞琪祥"
|
name = "陈瑞琪祥"
|
||||||
|
|
||||||
def train_svm(X, y, other_params=""):
|
def train_svm(X, y, learning_rate=0.01, iterations=1000):
|
||||||
"""
|
"""
|
||||||
支持向量机训练函数。
|
支持向量机训练函数。
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
- X (numpy array): 特征数据。
|
- X (numpy array): 特征数据。
|
||||||
- y (numpy array): 标签数据。
|
- y (numpy array): 标签数据。
|
||||||
- other_params (str): 其它参数,可选设置。
|
- learning_rate (float): 学习率。
|
||||||
|
- iterations (int): 迭代次数。
|
||||||
|
|
||||||
Returns:
|
Returns:
|
||||||
- numpy array: 训练得到的权重。
|
- numpy array: 训练得到的权重。
|
||||||
"""
|
"""
|
||||||
# 初始化权重
|
# 初始化权重
|
||||||
weights = np.zeros(X.shape[1])
|
weights = np.zeros(X.shape[1] + 1) # 加1是为了偏置项
|
||||||
# 设置学习率和迭代次数
|
|
||||||
learning_rate = 0.01
|
|
||||||
iterations = 1000
|
|
||||||
|
|
||||||
# 简单的梯度下降优化
|
# 简单的梯度下降优化
|
||||||
for _ in range(iterations):
|
for _ in range(iterations):
|
||||||
for i in range(len(X)):
|
for i in range(len(X)):
|
||||||
if y[i] * (np.dot(X[i], weights)) < 1:
|
if y[i] * (np.dot(X[i], weights[:-1]) + weights[-1]) < 1:
|
||||||
weights += learning_rate * (y[i] * X[i])
|
weights[:-1] += learning_rate * (y[i] * X[i]) # 更新权重
|
||||||
|
weights[-1] += learning_rate * y[i] # 更新偏置项
|
||||||
else:
|
else:
|
||||||
weights -= learning_rate * (y[i] * X[i])
|
weights[:-1] -= learning_rate * (y[i] * X[i]) # 更新权重
|
||||||
|
weights[-1] -= learning_rate * y[i] # 更新偏置项
|
||||||
|
|
||||||
return weights
|
return weights
|
||||||
|
|
||||||
@@ -43,7 +42,7 @@ def predict_svm(inX, weights):
|
|||||||
- int: 预测的分类标签。
|
- int: 预测的分类标签。
|
||||||
"""
|
"""
|
||||||
# 预测标签
|
# 预测标签
|
||||||
prediction = np.sign(np.dot(inX, weights))
|
prediction = np.sign(np.dot(inX, weights[:-1]) + weights[-1]) # 加上偏置项
|
||||||
return 1 if prediction > 0 else -1
|
return 1 if prediction > 0 else -1
|
||||||
|
|
||||||
def load_data(filepath):
|
def load_data(filepath):
|
||||||
|
|||||||
Reference in New Issue
Block a user