写一段python代码:写一段深度神经网络的示例
时间: 2023-07-22 08:27:57 浏览: 148
一个神经网络的例子
好的,以下是一个基于PyTorch框架的深度神经网络示例,包含两个隐藏层和一个输出层:
```python
import torch
import torch.nn as nn
import torch.optim as optim
# 定义深度神经网络模型
class DeepNeuralNetwork(nn.Module):
def __init__(self, input_dim, hidden_dim1, hidden_dim2, output_dim):
super(DeepNeuralNetwork, self).__init__()
self.fc1 = nn.Linear(input_dim, hidden_dim1)
self.fc2 = nn.Linear(hidden_dim1, hidden_dim2)
self.fc3 = nn.Linear(hidden_dim2, output_dim)
def forward(self, x):
x = torch.relu(self.fc1(x))
x = torch.relu(self.fc2(x))
x = self.fc3(x)
return x
# 定义训练数据和标签
x_train = torch.tensor([[0,0], [0,1], [1,0], [1,1]], dtype=torch.float32)
y_train = torch.tensor([[0], [1], [1], [0]], dtype=torch.float32)
# 定义模型参数
input_dim = 2
hidden_dim1 = 4
hidden_dim2 = 2
output_dim = 1
# 构建模型
dnn = DeepNeuralNetwork(input_dim, hidden_dim1, hidden_dim2, output_dim)
# 定义损失函数和优化器
criterion = nn.MSELoss()
optimizer = optim.Adam(dnn.parameters(), lr=0.01)
# 训练模型
for epoch in range(10000):
optimizer.zero_grad()
outputs = dnn(x_train)
loss = criterion(outputs, y_train)
loss.backward()
optimizer.step()
if epoch % 1000 == 0:
print('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, 10000, loss.item()))
# 测试模型
with torch.no_grad():
x_test = torch.tensor([[0,0], [0,1], [1,0], [1,1]], dtype=torch.float32)
y_test = torch.tensor([[0], [1], [1], [0]], dtype=torch.float32)
outputs = dnn(x_test)
predicted = torch.round(outputs)
accuracy = (predicted == y_test).sum() / y_test.size(0)
print('Accuracy of the model: {:.2f}%'.format(accuracy.item() * 100))
```
该模型使用了ReLU激活函数和均方误差损失函数,使用Adam优化器进行参数更新。训练完成后,使用测试数据计算模型准确率。
阅读全文