基于sklearn的感知机python3

首先,本文还是选用python里面自带的digits数据集

from sklearn.datasets import load_digits
digits=load_digits()

大家都知道这个数据集是一些图片,我们对数据进行处理:

#数据标准化
from sklearn.preprocessing import StandardScaler
scaler=StandardScaler()
scaler.fit(digits.data)
x_scaled=scaler.transform(digits.data)

将数据和类别分别赋予x,y:

x=x_scaled
y=digits.target

划分训练集、测试集:

from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test=train_test_split(x,y)

调用sklearn,使用感知机预测:

from sklearn.neural_network import MLPClassifier
mlp=MLPClassifier(hidden_layer_sizes=(30,30,30),activation='logistic',max_iter=100)
mlp.fit(x_train,y_train)

进行预测,并观察效果:


from sklearn.metrics import classification_report
predicted=mlp.predict(x_test)
print(classification_report(y_test, predicted))
预测效果
下面我们进行调参,并观察参数改变对预测效果的影响:

from sklearn.pipeline import Pipeline
from sklearn.model_selection import GridSearchCV
if __name__ == '__main__':
    pipeline = Pipeline([
        ('mlp',MLPClassifier(hidden_layer_sizes=(30,30,30),max_iter=100))
    ])
    parameters = {
        'mlp__activation': ('identity','logistic','tanh','relu'),
         'mlp__solver': ('lbfgs','sgd','adam')
    }
    grid_search = GridSearchCV(pipeline, parameters,verbose=1,n_jobs=-1)
    grid_search.fit(x_train, y_train)
    print('最佳效果:%0.3f' % grid_search.best_score_)
    print('最优参数:')
    best_parameters = grid_search.best_estimator_.get_params()
    for param_name in sorted(parameters.keys()):
        print('\t%s: %r' % (param_name, best_parameters[param_name]))

    predictions = grid_search.predict(x_test)
    print(classification_report(y_test, predictions))

参数结果
可以看到预测效果有显著提升!

### 感知机算法的Python实现 感知机是一种线性分类模型,属于监督学习算法。它通过寻找一条直线(二维空间)或将超平面(高维空间)来划分数据集中的不同类别。以下是基于Python的一个简单感知机算法实现: #### 单层感知机的核心逻辑 单层感知机的目标是最小化错误分类样本的数量。其更新规则如下:当某个样本被误分类时,调整权重向量 \( w \) 和偏置项 \( b \),使得该样本更接近于正确分类。 核心公式为: \[ f(x) = sign(w \cdot x + b) \] 其中 \( w \) 是权重向量,\( b \) 是偏置项,\( x \) 是输入特征向量,而 \( sign(\cdot) \) 函数用于返回正负标签。 --- #### Python代码实现 以下是一个简单的感知机算法实现,支持二分类任务: ```python import numpy as np class Perceptron: def __init__(self, learning_rate=0.1, max_epochs=100): self.learning_rate = learning_rate # 学习率 self.max_epochs = max_epochs # 最大迭代次数 self.weights = None # 权重向量 self.bias = None # 偏置项 def fit(self, X, y): n_samples, n_features = X.shape # 初始化参数 self.weights = np.zeros(n_features) self.bias = 0 # 将y转换为{-1, 1} y_ = np.where(y <= 0, -1, 1) for epoch in range(self.max_epochs): # 迭代训练 misclassified_count = 0 for idx, x_i in enumerate(X): condition = y_[idx] * (np.dot(x_i, self.weights) + self.bias) if condition <= 0: # 如果条件不满足,则更新权重和偏置 update_value = self.learning_rate * y_[idx] self.weights += update_value * x_i self.bias += update_value misclassified_count += 1 if misclassified_count == 0: # 若无误分类样本则提前终止 break def predict(self, X): linear_output = np.dot(X, self.weights) + self.bias predictions = np.sign(linear_output) return predictions.astype(int) # 测试代码 if __name__ == "__main__": from sklearn.model_selection import train_test_split from sklearn.datasets import make_classification # 创建一个简单的二分类数据集 X, y = make_classification( n_samples=100, n_features=2, n_redundant=0, n_informative=1, n_clusters_per_class=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.01, max_epochs=100) perceptron.fit(X_train, y_train) predictions = perceptron.predict(X_test) accuracy = np.mean(predictions == y_test) print(f"Accuracy: {accuracy:.2f}") ``` 上述代码实现了基本的感知机算法,并测试了一个简单的二分类问题。注意,在实际应用中可能需要对数据进行预处理(如标准化),并考虑更多复杂的场景。 --- #### 关键点说明 1. **初始化**:权重向量和偏置项均初始化为零。 2. **更新规则**:如果当前样本被误分类,则按照梯度下降的方向更新权重和偏置[^1]。 3. **停止条件**:当达到最大迭代次数或所有样本都被正确分类时结束训练。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

gxls2024

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

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

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

打赏作者

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

抵扣说明:

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

余额充值