以下是为您提供的一段可能的代码示例,希望对您有所帮助: ```python import numpy as np import matplotlib.pyplot as plt from sklearn import datasets from sklearn.linear_model import Perceptron # 加载鸢尾花数据集 iris = datasets.load_iris() X = iris.data[:, :2] # 只取前两个特征 y = iris.target # 自定义感知机函数 class CustomPerceptron: def __init__(self, learning_rate=0.1, n_iterations=100): self.learning_rate = learning_rate self.n_iterations = n_iterations 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 for _ in range(self.n_iterations): for i in range(n_samples): linear_output = np.dot(X[i], self.weights) + self.bias prediction = np.sign(linear_output) if prediction!= y[i]: self.weights += self.learning_rate * y[i] * X[i] self.bias += self.learning_rate * y[i] def predict(self, X): linear_output = np.dot(X, self.weights) + self.bias return np.sign(linear_output) # 创建自定义感知机对象并训练 custom_perceptron = CustomPerceptron() custom_perceptron.fit(X, y) # 使用 sklearn 的感知机 sklearn_perceptron = Perceptron() sklearn_perceptron.fit(X, y) # 绘制图像 plt.figure(figsize=(10, 5)) plt.scatter(X[y == 0][:, 0], X[y == 0][:, 1], color='red', label='Class 0') plt.scatter(X[y == 1][:, 0], X[y == 1][:, 1], color='blue', label='Class 1') # 绘制自定义感知机的决策边界 x1_min, x1_max = X[:, 0].min() - 1, X[:, 0].max() + 1 x2_min, x2_max = X[:, 1].min() - 1, X[:, 1].max() + 1 xx1, xx2 = np.meshgrid(np.arange(x1_min, x1_max, 0.01), np.arange(x2_min, x2_max, 0.01)) Z = custom_perceptron.predict(np.c_[xx1.ravel(), xx2.ravel()]) Z = Z.reshape(xx1.shape) plt.contour(xx1, xx2, Z, levels=[0], colors='green', linestyles='dashed') # 绘制 sklearn 感知机的决策边界 Z_sklearn = sklearn_perceptron.predict(np.c_[xx1.ravel(), xx2.ravel()]) Z_sklearn = Z_sklearn.reshape(xx1.shape) plt.contour(xx1, xx2, Z_sklearn, levels=[0], colors='black', linestyles='dashed') plt.xlabel('Feature 1') plt.ylabel('Feature 2') plt.title('Comparison of Custom and sklearn Perceptron on Iris Dataset') plt.legend() plt.show() ``` 额外需要注意的逻辑点: 1. 数据的预处理和特征选择可能会影响模型效果。 2. 调整学习率和迭代次数以优化模型性能。 3. 对于复杂的数据集,感知机可能表现不佳,考虑使用更复杂的模型。 [2024-12-10 22:30:51 | AI写代码神器 | 821点数解答]