根据误差反向传播计算准则,用python生成双月数据分类结果,并进行可视化展示
时间: 2023-06-16 11:03:51 浏览: 79
可以使用Scikit-learn库中的make_moons函数生成双月数据,并使用神经网络模型进行分类。以下是示例代码:
```python
from sklearn.datasets import make_moons
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import numpy as np
import matplotlib.pyplot as plt
# 生成双月数据
X, y = make_moons(n_samples=1000, noise=0.2, random_state=42)
# 数据预处理
scaler = StandardScaler()
X = scaler.fit_transform(X)
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# 定义神经网络模型
class NeuralNetwork:
def __init__(self):
self.weights1 = np.random.randn(2, 6)
self.bias1 = np.zeros((1, 6))
self.weights2 = np.random.randn(6, 1)
self.bias2 = np.zeros((1, 1))
def sigmoid(self, z):
return 1 / (1 + np.exp(-z))
def sigmoid_derivative(self, z):
return self.sigmoid(z) * (1 - self.sigmoid(z))
def forward(self, X):
self.z1 = np.dot(X, self.weights1) + self.bias1
self.a1 = self.sigmoid(self.z1)
self.z2 = np.dot(self.a1, self.weights2) + self.bias2
self.a2 = self.sigmoid(self.z2)
return self.a2
def backward(self, X, y, output):
self.error = output - y
self.delta2 = self.error * self.sigmoid_derivative(self.z2)
self.weights2 -= np.dot(self.a1.T, self.delta2)
self.bias2 -= np.sum(self.delta2, axis=0, keepdims=True)
self.delta1 = np.dot(self.delta2, self.weights2.T) * self.sigmoid_derivative(self.z1)
self.weights1 -= np.dot(X.T, self.delta1)
self.bias1 -= np.sum(self.delta1, axis=0)
def train(self, X, y):
output = self.forward(X)
self.backward(X, y, output)
# 训练模型
nn = NeuralNetwork()
for i in range(5000):
nn.train(X_train, y_train)
# 预测测试集
y_pred = np.round(nn.forward(X_test))
# 可视化结果
plt.scatter(X_test[:, 0], X_test[:, 1], c=y_pred.ravel(), cmap='viridis')
plt.show()
```
运行代码后,会生成一个可视化的结果,展示了神经网络模型对双月数据的分类效果。
阅读全文