用pytorch写一段代码:以西储大学CWRU轴承故障的振动信号数据库作为模型的训练集,故障类型标签包括:正常、内圈故障、外圈故障和滚动体故障四类。首先将一维故障信号转换为二维灰度图作为CNN模型的输...
时间: 2024-05-08 19:21:21 浏览: 76
以下是一段基本的代码,用于将CWRU轴承故障数据集转换为灰度图并使用CNN模型进行训练:
```python
import os
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
# 设置数据集路径和标签
data_dir = "/path/to/CWRU_dataset"
labels = {"Normal": 0, "Inner Race Fault": 1, "Outer Race Fault": 2, "Rolling Element Fault": 3}
# 自定义数据集类
class CWRUDataset(Dataset):
def __init__(self, data_dir, labels, transform=None):
self.data_dir = data_dir
self.labels = labels
self.transform = transform
self.file_list = []
self.label_list = []
for label, num in labels.items():
label_dir = os.path.join(data_dir, label)
for file_name in os.listdir(label_dir):
self.file_list.append(os.path.join(label_dir, file_name))
self.label_list.append(num)
def __len__(self):
return len(self.label_list)
def __getitem__(self, idx):
file_path = self.file_list[idx]
label = self.label_list[idx]
data = np.loadtxt(file_path, delimiter=",")
data = np.expand_dims(data, axis=0) # 将一维信号转换为二维灰度图
if self.transform:
data = self.transform(data)
return data, label
# 定义CNN模型
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.conv1 = nn.Conv2d(1, 16, 3, padding=1)
self.pool = nn.MaxPool2d(2, 2)
self.conv2 = nn.Conv2d(16, 32, 3, padding=1)
self.fc1 = nn.Linear(32 * 125 * 125, 128)
self.fc2 = nn.Linear(128, 4)
def forward(self, x):
x = self.pool(nn.functional.relu(self.conv1(x)))
x = self.pool(nn.functional.relu(self.conv2(x)))
x = x.view(-1, 32 * 125 * 125)
x = nn.functional.relu(self.fc1(x))
x = self.fc2(x)
return x
# 定义训练函数
def train(model, train_loader, optimizer, criterion, device):
model.train()
train_loss = 0.0
correct = 0
for inputs, labels in train_loader:
inputs, labels = inputs.to(device), labels.to(device)
optimizer.zero_grad()
outputs = model(inputs)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
train_loss += loss.item() * inputs.size(0)
preds = torch.argmax(outputs, axis=1)
correct += torch.sum(preds == labels)
train_loss /= len(train_loader.dataset)
accuracy = correct.double() / len(train_loader.dataset)
return train_loss, accuracy
# 定义验证函数
def validate(model, val_loader, criterion, device):
model.eval()
val_loss = 0.0
correct = 0
with torch.no_grad():
for inputs, labels in val_loader:
inputs, labels = inputs.to(device), labels.to(device)
outputs = model(inputs)
loss = criterion(outputs, labels)
val_loss += loss.item() * inputs.size(0)
preds = torch.argmax(outputs, axis=1)
correct += torch.sum(preds == labels)
val_loss /= len(val_loader.dataset)
accuracy = correct.double() / len(val_loader.dataset)
return val_loss, accuracy
# 定义训练数据预处理
train_transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(mean=[0.5], std=[0.5])
])
# 定义验证数据预处理
val_transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(mean=[0.5], std=[0.5])
])
# 创建训练集和验证集
train_set = CWRUDataset(data_dir, labels, transform=train_transform)
val_set = CWRUDataset(data_dir, labels, transform=val_transform)
# 创建训练集和验证集的DataLoader
train_loader = DataLoader(train_set, batch_size=32, shuffle=True)
val_loader = DataLoader(val_set, batch_size=32, shuffle=False)
# 定义设备
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# 创建模型实例,并将其移动到设备上
model = Net().to(device)
# 定义损失函数和优化器
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=0.001)
# 训练模型
num_epochs = 10
for epoch in range(num_epochs):
train_loss, train_acc = train(model, train_loader, optimizer, criterion, device)
val_loss, val_acc = validate(model, val_loader, criterion, device)
print(f"Epoch {epoch+1}/{num_epochs} - Train Loss: {train_loss:.4f} - Train Acc: {train_acc:.4f} - Val Loss: {val_loss:.4f} - Val Acc: {val_acc:.4f}")
```
请注意,上面的代码仅提供了一个基本的框架,并且需要根据你的实际情况进行修改和调整。例如,你可能需要更改CNN模型的结构,调整超参数,以及对数据进行更复杂的预处理等。
阅读全文