{ "title": "基于图像颜色特征的图卷积网络模型训练", "description": "本文介绍了使用图像颜色特征作为输入,构建图卷积网络 (GCN) 模型进行训练和评估的步骤。代码包含数据集加载、模型构建、训练和测试等部分,并展示了如何利用图像颜色特征提升模型性能。", "keywords": "图卷积网络, GCN, 图像颜色特征, 模型训练, 图神经网络, 深度学习", "content": "import torch import numpy as np import pandas as pd import torch_geometric import torch.nn.functional as F from torch_geometric.data import Data from torch_geometric.nn import GCNConv, GATConv, GraphSAGE from torch_geometric.nn import MessagePassing from torch_geometric.utils import add_self_loops, degree import torch_geometric.transforms as T from torch.utils.data import Dataset, DataLoader

自定义数据集类My_dataset:

class My_dataset(Dataset): def init(self, path_feature, path_label): self.path_feature = path_feature self.path_label = path_label self.data_feature = []

    for i in range(1, 43):
        for j in range(37):
            image_path = r"C:\Users\jh\Desktop\data\input\images\{}_{}.png".format(i, j)
            img = Image.open(image_path)
            img = img.resize((40, 40))  # Resize the image to 40x40
            img = np.array(img)  # Convert the image to a numpy array
            img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)  # Convert the image to BGR format
            img = img.flatten()  # Flatten the image
            self.data_feature.append(img)

    self.data_feature = np.array(self.data_feature)
    self.data_label = np.loadtxt(self.path_label, dtype=float, comments='#', delimiter=' ')
    self.length = len(self.data_feature)

#  __getitem__方法用于获取指定索引的数据样本:
def __getitem__(self, idx):
    feature, label = self.data_feature[idx], self.data_label[idx]
    feature = feature.reshape(-1, 2)
    feature = feature.astype(np.float32)
    label = label.astype(np.float32)
    feature = torch.tensor(feature)
    label = torch.tensor(label)
    return feature, label

def __len__(self):
    return self.length

定义 edge_index, train_mask, and test_mask tensors

df = pd.read_csv(r'C:\Users\jh\Desktop\data\input\edges_L.csv') source_nodes = df.iloc[:, 0].tolist() #分别提取df的第一列和第二列,并将它们转换为Python列表格式。这样就得到了源节点和目标节点列表 target_nodes = df.iloc[:, 1].tolist() adj_matrix = [source_nodes, target_nodes] edge_index = torch.tensor(adj_matrix, dtype=torch.long)

#边索引 train_mask = torch.tensor([1] * 30 + [0] * 7, dtype=torch.bool) test_mask = torch.tensor([0] * 30 + [1] * 7, dtype=torch.bool)

建立GCN模型:

class GCN(torch.nn.Module): #四层卷积 def init(self): super().init() self.conv1 = GCNConv(1600, 8) # Update the input dimension to match the image color feature size self.conv2 = GCNConv(8, 32) self.conv3 = GCNConv(32, 8) self.conv4 = GCNConv(8, 2)

def forward(self, x, edge_index):
    #前向传播
    x = self.conv1(x, edge_index)
    x = F.relu(x)
    #使用ReLU激活函数对节点特征进行非线性变换
    x = self.conv2(x, edge_index)
    x = F.relu(x)
    x = self.conv3(x, edge_index)
    x = F.relu(x)
    x = self.conv4(x, edge_index)
    #         x = F.relu(x)
    return F.log_softmax(x, dim=1)  #使用log_softmax函数对节点特征进行分类

定义图像和标签文件的路径以及数据集

path_feature = r"C:\Users\jh\Desktop\data\input\labels" path_label = r"C:\Users\jh\Desktop\data\input\labels" dataset = My_dataset(path_feature, path_label)

使用DataLoader加载数据集

dataloader = DataLoader(dataset, batch_size=1, shuffle=False)

初始化 device, model, data

torch.manual_seed(10) # 设置随机种子 device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') model = GCN().to(device) # optimizer = torch.optim.SGD(model.parameters(), lr=0.1, momentum=0.9, weight_decay=5e-4) # 定义优化器和学习率调度器 optimizer = torch.optim.Adam(model.parameters(), lr=0.01, weight_decay=5e-4) scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.5, patience=10, verbose=True) # factor:学习率调整的因子,patience:如果在patience个epoch中,模型性能没有改善,则进行学习率调整。verbose=True打印学习率调整的详细信息 # 模型训练: model.train() for epoch in range(2000): epoch_loss = 0.0 #初始化每个epoch的损失为0 for i, (features, labels) in enumerate(dataloader): labels = labels.to(torch.float32) # 转换标签为float型并压缩特征和标签张量 features = torch.squeeze(features, dim=0) labels = torch.squeeze(labels, dim=0) # 创建一个Data对象,其中包含特征、边索引、标签以及训练掩码和测试掩码 data = Data(x=features, edge_index=edge_index, y=labels, train_mask=train_mask, test_mask=test_mask) data = data.to(device) out = model(data.x, data.edge_index) optimizer.zero_grad() #将优化器的梯度归零,以便进行下一次反向传播 # loss = F.cross_entropy(out[data.train_mask], data.y[data.train_mask].long()) loss = F.nll_loss(out[data.train_mask], data.y[data.train_mask].long()) # 使用负对数似然损失函数计算损失 loss.backward() #根据损失计算梯度 optimizer.step() #根据梯度更新模型的参数 epoch_loss += loss.item() #将当前批次的损失添加到epoch损失中 epoch_loss /= len(dataloader) #计算每个epoch的平均损失 scheduler.step(epoch_loss) #根据epoch损失调整学习率 print(f"Epoch: {epoch+1}, Loss: {epoch_loss}") #测试: model.eval() pred = model(data.x, data.edge_index).argmax(dim=1) correct = (pred[data.test_mask] == data.y[data.test_mask]).sum() acc = int(correct) / int(data.test_mask.sum()) print(f'Accuracy: {acc:.4f}')


原文地址: https://www.cveoy.top/t/topic/pcH0 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录