2.基于感知机的二分类问题

本文通过Python和matplotlib库生成两类数据点,并利用随机梯度下降法训练一个简单的线性分类器来区分这两类数据。文章详细展示了数据生成、可视化、模型训练及最终分类边界绘制的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import numpy as np
import matplotlib.pyplot as plt
np.random.seed(0)
Num = 100
x_1 = np.random.normal(6,1,size=(Num))
x_2 = np.random.normal(3,1,size=(Num))
y  = np.ones(Num)*-1
c_0 = np.array([x_1,x_2,y])    # -1分类
x_1 = np.random.normal(3,1,size=(Num))
x_2 = np.random.normal(6,1,size=(Num))
y  = np.ones(Num)
c_1 = np.array([x_1,x_2,y])    # 1分类
c_0 = c_0.T
c_1 = c_1.T
plt.scatter(c_1[:,0],c_1[:,1])
plt.scatter(c_0[:,0],c_0[:,1],marker='+')
<matplotlib.collections.PathCollection at 0x24b24683988>

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-W7G4pY4f-1588587740917)(output_5_1.png)]

# 建立数据集,分训练集和测试集
All_data = np.concatenate((c_1,c_0))
print(All_data.shape)
np.random.shuffle(All_data)
train_data_X = All_data[:150,:2]  # [)
train_data_y = All_data[:150,-1].reshape(150,1)
test_data_X = All_data[150:,:2]
test_data_y = All_data[150:,-1].reshape(50,1)
print(train_data_X.shape,train_data_y.shape,test_data_X.shape,test_data_y.shape)
(200, 3)
(150, 2) (150, 1) (50, 2) (50, 1)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QXJiyX2O-1588587740921)(attachment:7e9b90ac-01e7-4694-a16b-9a7094372ac5.png)]

W = np.zeros((2,1))
T = 100#最大迭代次数
k = 0
train_data = np.concatenate((train_data_X,train_data_y),axis=1)
train_data.shape
#train_data[0][-1]
(150, 3)
# 训练模型
for t in range(T):
    np.random.shuffle(train_data)
    for i in range(len(train_data)):
        # 选择第i个样本
        pred = np.dot(W.T,(train_data[i][-1]*train_data[i][:2]).reshape(2,1))[0,0]
        if pred <= 0:
            W = W + (train_data[i][-1]*train_data[i][:2]).reshape(2,1)
W
array([[-43.38640304],
       [ 47.145247  ]])
plt.scatter(c_1[:,0],c_1[:,1])
plt.scatter(c_0[:,0],c_0[:,1],marker='+')
x = np.arange(10)
y = -(W[0]*x)/W[1]
plt.plot(x,y)
[<matplotlib.lines.Line2D at 0x24b2474c208>]

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-rNxykPGB-1588587740925)(output_11_1.png)]


### 感知机算法用于二分类问题的完整代码实现 以下是基于感知机算法(Perceptron Algorithm)解决二分类问题的一个完整的 Python 实现。此代码实现了权重更新逻辑以及训练过程,并提供了预测功能。 ```python import numpy as np class Perceptron: def __init__(self, learning_rate=0.01, max_iterations=1000): self.learning_rate = learning_rate # 学习率 self.max_iterations = max_iterations # 最大迭代次数 def fit(self, X, y): """ 训练模型,调整权重向量 w 和偏置 b。 参数: X (numpy.ndarray): 输入特征矩阵,形状为 [n_samples, n_features]。 y (numpy.ndarray): 输出标签数组,形状为 [n_samples],取值为 {1, -1}。 """ n_samples, n_features = X.shape # 初始化权重和偏置 self.w = np.zeros(n_features) # 权重初始化为零 self.b = 0 # 偏置初始化为零 for _ in range(self.max_iterations): misclassified_count = 0 for i in range(n_samples): xi, yi = X[i], y[i] # 预测当前样本的类别 prediction = np.dot(xi, self.w) + self.b # 如果预测错误,则更新权重和偏置 if yi * prediction <= 0: update_term = self.learning_rate * yi self.w += update_term * xi # 更新权重 self.b += update_term # 更新偏置 misclassified_count += 1 # 如果没有误分类点,则提前终止训练 if misclassified_count == 0: break def predict(self, X): """ 对输入数据进行预测。 参数: X (numpy.ndarray): 测试集特征矩阵,形状为 [n_test_samples, n_features]。 返回: numpy.ndarray: 预测结果,形状为 [n_test_samples],取值为 {1, -1}。 """ return np.sign(np.dot(X, self.w) + self.b) # 示例用法 if __name__ == "__main__": from sklearn.datasets import make_classification from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score # 创建一个简单的线性可分数据集 X, y = make_classification( n_samples=100, n_features=2, n_informative=2, n_redundant=0, n_clusters_per_class=1, flip_y=0, random_state=42 ) # 将标签转换为 {-1, 1} y[y == 0] = -1 # 划分训练集和测试集 X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) # 初始化并训练感知机模型 perceptron = Perceptron(learning_rate=0.1, max_iterations=1000) perceptron.fit(X_train, y_train) # 进行预测 predictions = perceptron.predict(X_test) # 打印准确率 print(f"Accuracy: {accuracy_score(y_test, predictions)}") ``` #### 关键说明 上述代码展示了如何通过感知机算法完成二分类任务。核心部分包括: - **权重更新规则**:当某个样本被误分类时,按照特定的学习率调整权重和偏置[^2]。 - **停止条件**:如果在某次遍历中没有任何样本被误分类,则认为模型已收敛,可以提前结束训练。 - **预测函数**:利用 `np.sign` 函数判断最终输出属于正类还是负类[^1]。 此外,在实际应用中可能需要对原始数据进行预处理,例如标准化或归一化操作,以便提高模型性能[^4]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

该用户没有用户名

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值