import numpy as np
class LinearSVM:
def __init__(self, learning_rate=0.01, n_iters=1000, lambda_param=0.01):
self.lr = learning_rate
self.n_iters = n_iters
self.lambda_param = lambda_param
self.w = None
self.b = None
def fit(self, X, y):
n_samples, n_features = X.shape
y_ = np.where(y <= 0, -1, 1) # 将标签转换为-1和1
# 初始化参数
self.w = np.zeros(n_features)
self.b = 0
# 梯度下降
for _ in range(self.n_iters):
for idx, x_i in enumerate(X):
condition = y_[idx] * (np.dot(x_i, self.w) - self.b) >= 1
if condition:
continue
self.w -= self.lr * (2 * self.lambda_param * self.w - np.dot(x_i, y_[idx]))
self.b -= self.lr * y_[idx]
def predict(self, X):
linear_output = np.dot(X, self.w) - self.b
return np.sign(linear_output)
# 示例数据
X = np.array([[2, 3], [5, 8], [6, 1], [7, 2], [1, 1], [2, 1], [3, 2], [1, 0], [2, 0], [4, 1]])
y = np.array([0, 1, 1, 1, 0, 0, 0, -1, -1, -1])
# 实例化SVM模型
model = LinearSVM(learning_rate=0.01, n_iters=1000, lambda_param=0.01)
# 训练模型
model.fit(X, y)
# 预测
predictions = model.predict(X)
print(predictions)
![avatar](https://profile-avatar.csdnimg.cn/be4f8f17e79c4cd489df1e2a71de87ff_m0_72714916.jpg!1)
![avatar-vip](https://csdnimg.cn/release/downloadcmsfe/public/img/user-vip.1c89f3c5.png)
早七睡不醒
- 粉丝: 0
- 资源: 149
最新资源
- Vue3+ts+threejs实现360度VR全景
- 4451GH-HF-VB一款P-Channel沟道TO252的MOSFET晶体管参数介绍与应用说明
- 2024 埃森哲中国企业数字化转型指数-重塑生产力,增长新前沿
- 40N06-TO252-VB一款N-Channel沟道TO252的MOSFET晶体管参数介绍与应用说明
- 深入理解JavaScript中的异步编程:`async`和`await`的魔力
- 400N06N-VB一款N-Channel沟道TO252的MOSFET晶体管参数介绍与应用说明
- 1992-2022年各区县夜间灯光数据(excel+shp格式).zip
- 3N1-YM-VB一款N-Channel沟道SOT23-6的MOSFET晶体管参数介绍与应用说明
- 深入剖析C++代码可维护性分析:工具、策略与实
- 数据库原理实验报告 - 实验七 视图设计实验.doc
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈
![feedback](https://img-home.csdnimg.cn/images/20220527035711.png)
![feedback](https://img-home.csdnimg.cn/images/20220527035711.png)
![feedback-tip](https://img-home.csdnimg.cn/images/20220527035111.png)