generated from LufsX/Challenge-SVM
This commit is contained in:
+31
-4
@@ -23,8 +23,8 @@ import numpy as np
|
|||||||
姓名请直接**填写中文**
|
姓名请直接**填写中文**
|
||||||
例如: name = "张三"
|
例如: name = "张三"
|
||||||
"""
|
"""
|
||||||
id = "202210423xxx"
|
id = "202210423130"
|
||||||
name = "test_name"
|
name = "董秋"
|
||||||
|
|
||||||
|
|
||||||
# 这里写自己的代码实现
|
# 这里写自己的代码实现
|
||||||
@@ -40,7 +40,22 @@ def train_svm(X, y, other_params="你自己设置一些其它参数"):
|
|||||||
Returns:
|
Returns:
|
||||||
- numpy array: 训练得到的权重。
|
- numpy array: 训练得到的权重。
|
||||||
"""
|
"""
|
||||||
|
n_samples, n_features = X.shape
|
||||||
|
weights = np.zeros(n_features) # 初始化权重
|
||||||
|
bias = 0 # 初始化偏置
|
||||||
|
|
||||||
|
for _ in range(iterations):
|
||||||
|
for idx, x_i in enumerate(X):
|
||||||
|
condition = y[idx] * (np.dot(x_i, weights) + bias) >= 1
|
||||||
|
if condition:
|
||||||
|
# 更新公式,不需要正则化项
|
||||||
|
weights -= learning_rate * (2 * lambda_param * weights)
|
||||||
|
else:
|
||||||
|
# 更新公式,包括误分类损失
|
||||||
|
weights -= learning_rate * (2 * lambda_param * weights - np.dot(x_i, y[idx]))
|
||||||
|
bias -= learning_rate * y[idx]
|
||||||
|
|
||||||
|
return np.append(weights, bias) # 将偏置合并到权重中
|
||||||
|
|
||||||
def predict_svm(inX, weights):
|
def predict_svm(inX, weights):
|
||||||
"""
|
"""
|
||||||
@@ -53,7 +68,10 @@ def predict_svm(inX, weights):
|
|||||||
Returns:
|
Returns:
|
||||||
- int: 预测的分类标签。
|
- int: 预测的分类标签。
|
||||||
"""
|
"""
|
||||||
|
w = weights[:-1] # 分离权重和偏置
|
||||||
|
b = weights[-1]
|
||||||
|
linear_output = np.dot(inX, w) + b
|
||||||
|
return 1 if linear_output >= 0 else -1
|
||||||
|
|
||||||
# 这里也写自己的代码实现
|
# 这里也写自己的代码实现
|
||||||
def load_data(filepath):
|
def load_data(filepath):
|
||||||
@@ -67,7 +85,16 @@ def load_data(filepath):
|
|||||||
- np.array: 特征数据。
|
- np.array: 特征数据。
|
||||||
- np.array: 标签数据。
|
- np.array: 标签数据。
|
||||||
"""
|
"""
|
||||||
|
data = []
|
||||||
|
with open(filepath, 'r') as file:
|
||||||
|
for line in file:
|
||||||
|
if "?" not in line: # 去除包含缺失值的数据行
|
||||||
|
data.append([float(x) for x in line.strip().split()])
|
||||||
|
data = np.array(data)
|
||||||
|
X = data[:, :-1] # 所有列,除最后一列
|
||||||
|
y = data[:, -1] # 最后一列
|
||||||
|
y = np.where(y == 1, 1, -1) # 将标签转换为 +1 和 -1
|
||||||
|
return X, y
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
# 以下代码可用于测试,可自行随意修改
|
# 以下代码可用于测试,可自行随意修改
|
||||||
|
|||||||
Reference in New Issue
Block a user