机器学习——python训练CNN模型实战(傻瓜式教学,小学生都可以学会)代码开源

机器学习实战目录

第一章 python训练线性模型实战

第二章 python训练决策树模型实战

第三章 python训练神经网络模型实战

第四章 python训练支持向量机模型实战

第五章 python训练贝叶斯分类器模型实战

第六章 python训练集成学习模型实战

第七章 python训练聚类模型实战

第八章 python训练KNN模型实战

第九章 python训练CNN模型实战

第十章 python训练RNN模型实战

......(会一直更新)

第九章 python训练CNN模型实战

目录

机器学习实战目录

第九章 python训练CNN模型实战

1. 下载数据集

2. 定义 CNN 模型

3. 训练模型

4. 测试模型

完整代码如下:

参考资料:


训练CNN模型的步骤如下:

1. 下载数据集

可以在各种网站上下载图像数据集,例如 CIFAR10 和 ImageNet。以使用的 CIFAR10 数据集为例,具体步骤如下:

- 安装 torchvision 库:使用以下命令安装 torchvision 库。

``` python

!pip install torchvision

```

如果你使用的是 conda,可以使用以下命令来安装 torchvision 库。

``` python

!conda install torchvision -c pytorch

```

- 加载数据集:使用以下代码来加载 CIFAR10 数据集。

``` python

import torch

import torchvision.datasets as datasets



# 加载数据集

train_data = datasets.CIFAR10(root='./data', train=True, download=True)

test_data = datasets.CIFAR10(root='./data', train=False, download=True)



# 将数据转换为 PyTorch 的张量格式

train_data = torch.utils.data.DataLoader(train_data, batch_size=64, shuffle=True)

test_data = torch.utils.data.DataLoader(test_data, batch_size=64, shuffle=True)

```

2. 定义 CNN 模型

在本例中,我们定义了一个包含三个卷积层和两个全连接层的 CNN 模型,以处理 3 通道的 32x32 图像。


``` python

import torch.nn as nn



class Net(nn.Module):

    def __init__(self):

        super(Net, self).__init__()

        

        # 定义卷积层

        self.conv1 = nn.Conv2d(3, 16, kernel_size=3, stride=1, padding=1)

        self.conv2 = nn.Conv2d(16, 32, kernel_size=3, stride=1, padding=1)

        self.conv3 = nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=1)

        

        # 定义全连接层

        self.fc1 = nn.Linear(64 * 4 * 4, 500)

        self.fc2 = nn.Linear(500, 10)

        

    def forward(self, x):

        

        # 卷积层

        x = self.conv1(x)

        x = nn.functional.relu(x)

        x = nn.functional.max_pool2d(x, 2)

        

        x = self.conv2(x)

        x = nn.functional.relu(x)

        x = nn.functional.max_pool2d(x, 2)

        

        x = self.conv3(x)

        x = nn.functional.relu(x)

        x = nn.functional.max_pool2d(x, 2)

        

        # 全连接层

        x = x.view(-1, 64 * 4 * 4)

        x = self.fc1(x)

        x = nn.functional.relu(x)

        x = self.fc2(x)

        

        return x



# 创建模型实例

model = Net()

```

3. 训练模型

训练 CNN 模型的代码如下所示:


``` python

import torch.optim as optim



# 定义优化器和损失函数

criterion = nn.CrossEntropyLoss()

optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9)



# 训练模型

for epoch in range(10):  # 训练 10 次

    running_loss = 0.0

    for i, data in enumerate(train_data, 0):

        # 获取输入

        inputs, labels = data

        

        # 梯度清零

        optimizer.zero_grad()

        

        # 前向传播,反向传播,优化器更新参数

        outputs = model(inputs)

        loss = criterion(outputs, labels)

        loss.backward()

        optimizer.step()

        

        # 输出统计信息

        running_loss += loss.item()

        if i % 100 == 99:

            print('[%d, %5d] loss: %.3f' %

                  (epoch + 1, i + 1, running_loss / 100))

            running_loss = 0.0

print('Finished Training')

```

4. 测试模型

对测试集进行推理并计算准确率。


``` python

correct = 0

total = 0

with torch.no_grad():

    for data in test_data:

        images, labels = data

        outputs = model(images)

        _, predicted = torch.max(outputs.data, 1)

        total += labels.size(0)

        correct += (predicted == labels).sum().item()



print('Accuracy of the network on the 10000 test images: %d %%' % (

    100 * correct / total))

```

完整代码如下:


``` python

import torch

import torch.nn as nn

import torch.optim as optim

import torchvision.datasets as datasets



# 加载数据集

train_data = datasets.CIFAR10(root='./data', train=True, download=True)

test_data = datasets.CIFAR10(root='./data', train=False, download=True)



# 将数据转换为 PyTorch 的张量格式

train_data = torch.utils.data.DataLoader(train_data, batch_size=64, shuffle=True)

test_data = torch.utils.data.DataLoader(test_data, batch_size=64, shuffle=True)



# 定义 CNN 模型

class Net(nn.Module):

    def __init__(self):

        super(Net, self).__init__()

        

        # 定义卷积层

        self.conv1 = nn.Conv2d(3, 16, kernel_size=3, stride=1, padding=1)

        self.conv2 = nn.Conv2d(16, 32, kernel_size=3, stride=1, padding=1)

        self.conv3 = nn.Conv2d(32, 64, kernel_size=3, stride=1, padding=1)

        

        # 定义全连接层

        self.fc1 = nn.Linear(64 * 4 * 4, 500)

        self.fc2 = nn.Linear(500, 10)

        

    def forward(self, x):

        

        # 卷积层

        x = self.conv1(x)

        x = nn.functional.relu(x)

        x = nn.functional.max_pool2d(x, 2)

        

        x = self.conv2(x)

        x = nn.functional.relu(x)

        x = nn.functional.max_pool2d(x, 2)

        

        x = self.conv3(x)

        x = nn.functional.relu(x)

        x = nn.functional.max_pool2d(x, 2)

        

        # 全连接层

        x = x.view(-1, 64 * 4 * 4)

        x = self.fc1(x)

        x = nn.functional.relu(x)

        x = self.fc2(x)

        

        return x



# 创建模型实例

model = Net()



# 定义优化器和损失函数

criterion = nn.CrossEntropyLoss()

optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9)



# 训练模型

for epoch in range(10):  # 训练 10 次

    running_loss = 0.0

    for i, data in enumerate(train_data, 0):

        # 获取输入

        inputs, labels = data

        

        # 梯度清零

        optimizer.zero_grad()

        

        # 前向传播,反向传播,优化器更新参数

        outputs = model(inputs)

        loss = criterion(outputs, labels)

        loss.backward()

        optimizer.step()

        

        # 输出统计信息

        running_loss += loss.item()

        if i % 100 == 99:

            print('[%d, %5d] loss: %.3f' %

                  (epoch + 1, i + 1, running_loss / 100))

            running_loss = 0.0

print('Finished Training')



# 测试模型

correct = 0

total = 0

with torch.no_grad():

    for data in test_data:

        images, labels = data

        outputs = model(images)

        _, predicted = torch.max(outputs.data, 1)

        total += labels.size(0)

        correct += (predicted == labels).sum().item()



print('Accuracy of the network on the 10000 test images: %d %%' % (

    100 * correct / total))

```

参考资料:

[[1](https://www.python.org/)]

[[2](https://zhuanlan.zhihu.com/p/344562609)]

大家觉得有帮助的话还请大家给个收藏关注鼓励一下,有什么问题评论区留言,看到会恢复哒~

你可能感兴趣的:(机器学习,python,cnn)