如何用代码实现神经网络分类
时间: 2023-07-16 08:15:45 浏览: 36
以下是一个简单的神经网络分类的示例代码:
```python
import numpy as np
# 生成随机训练数据
X = np.random.randn(100, 2)
y = np.logical_xor(X[:, 0] > 0, X[:, 1] > 0)
# 定义神经网络架构
input_size = 2
hidden_size = 5
output_size = 1
# 初始化权重
W1 = np.random.randn(input_size, hidden_size)
b1 = np.zeros((1, hidden_size))
W2 = np.random.randn(hidden_size, output_size)
b2 = np.zeros((1, output_size))
# 定义激活函数
def sigmoid(x):
return 1 / (1 + np.exp(-x))
# 训练神经网络
learning_rate = 0.1
for i in range(10000):
# 前向传播
hidden_layer = sigmoid(np.dot(X, W1) + b1)
output_layer = sigmoid(np.dot(hidden_layer, W2) + b2)
# 计算损失函数
loss = np.mean(-y*np.log(output_layer) - (1-y)*np.log(1-output_layer))
# 反向传播
d_output_layer = (output_layer - y) / output_layer / (1 - output_layer)
d_hidden_layer = np.dot(d_output_layer, W2.T) * hidden_layer * (1 - hidden_layer)
# 更新权重
W2 -= learning_rate * np.dot(hidden_layer.T, d_output_layer)
b2 -= learning_rate * np.sum(d_output_layer, axis=0, keepdims=True)
W1 -= learning_rate * np.dot(X.T, d_hidden_layer)
b1 -= learning_rate * np.sum(d_hidden_layer, axis=0, keepdims=True)
# 预测新数据
new_data = np.array([[0.5, 0.5], [-0.5, 0.5], [0.5, -0.5], [-0.5, -0.5]])
hidden_layer = sigmoid(np.dot(new_data, W1) + b1)
output_layer = sigmoid(np.dot(hidden_layer, W2) + b2)
predictions = np.round(output_layer)
print(predictions)
```
这个示例代码使用了一个两层的神经网络,其中输入层有两个神经元,隐藏层有五个神经元,输出层有一个神经元。该神经网络使用逻辑异或问题作为训练数据,并且使用 sigmoid 激活函数和交叉熵损失函数。在训练完成后,该神经网络可以对新数据进行分类预测。