g = dgl.DGLGraph() g.add_nodes(drug_features.shape[0] + protein_features.shape[0])是什么意思
时间: 2023-06-19 07:04:32 浏览: 164
这段代码使用了 DGL(Deep Graph Library)库创建了一个空的有向图(DGLGraph)。其中,`drug_features.shape[0]` 表示药物特征的数量,`protein_features.shape[0]` 表示蛋白质特征的数量。`g.add_nodes(drug_features.shape[0] + protein_features.shape[0])` 表示向这个空图中添加了药物特征和蛋白质特征的节点,节点编号从 0 到 `drug_features.shape[0] + protein_features.shape[0] - 1`。这个过程相当于在图中添加了所有的节点。
相关问题
import dgl import numpy as np import torch import torch.nn as nn import dgl.function as fn # 生成10个节点和15条边的图 g = dgl.rand_graph(10, 15) # 为每个节点随机生成一个特征向量 feat = np.random.rand(10, 5) # 为每条边随机生成一个特征向量 e_feat = np.random.rand(15, 3) # 将特征向量添加到图中 g.ndata['feat'] = torch.from_numpy(feat) g.edata['e_feat'] =torch.from_numpy(e_feat) # 随机给每个节点分配一个标签 labels = np.random.randint(0, 3, size=(10,)) g.ndata['label'] = torch.from_numpy(labels) class GraphSAGE(nn.Module): def __init__(self, in_feats, h_feats, num_classes): super(GraphSAGE, self).__init__() self.conv1 = dgl.nn.SAGEConv(in_feats, h_feats, 'mean') self.conv2 = dgl.nn.SAGEConv(h_feats, num_classes, 'mean') def forward(self, g, in_feat): h = self.conv1(g, in_feat) h = torch.relu(h) h = self.conv2(g, h) g.ndata['h'] = h hg = dgl.mean_nodes(g, 'h') return hg # 定义超参数 in_feats = 5 h_feats = 10 num_classes = 3 lr = 0.01 num_epochs = 20 # 创建模型和优化器 model = GraphSAGE(in_feats, h_feats, num_classes) optimizer = torch.optim.Adam(model.parameters(), lr=lr) # 训练模型 for epoch in range(num_epochs): logits = model(g, g.ndata['feat']) labels = g.ndata['label'] loss = nn.CrossEntropyLoss()(logits, labels) optimizer.zero_grad() loss.backward() optimizer.step() print('Epoch %d | Loss: %.4f' % (epoch, loss.item())) # 预测 model.eval() with torch.no_grad(): logits = model(g, g.ndata['feat']) pred = logits.argmax(1) print('Predicted labels:', pred) 报错:RuntimeError: expected scalar type Double but found Float
这个错误是因为在创建特征向量时使用了numpy中的float64类型,而在将特征向量添加到图中时使用了torch中的float32类型。你可以在生成特征向量时将其转换为float32类型,如下所示:
```python
feat = np.random.rand(10, 5).astype(np.float32)
e_feat = np.random.rand(15, 3).astype(np.float32)
```
这样,在将特征向量添加到图中时,就可以直接使用它们了。
程序提示AttributeError: 'ImageThread' object has no attribute '_dgl',优化程序 def __init__(self, pipeline, color_label, depth_label, interval, color_photo_dir, depth_photo_dir): super().__init__() self.pipeline = pipeline self.color_label = color_label self.depth_label = depth_label self.is_running = True self.interval = interval self.color_photo_dir = color_photo_dir self.depth_photo_dir = depth_photo_dir self.saved_color_photos = 0 self.saved_depth_photos = 0 def save_photo(self, color_image, depth_image): # 保存彩色图和深度图 filename = datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S-{}.bmp".format(self.saved_color_photos)) color_image.save(os.path.join(self.color_photo_dir, filename), "BMP") depth_image.save(os.path.join(self.depth_photo_dir, filename), "BMP") # print(self.color_photo_dir) # 更新已保存照片数量标签 self.saved_color_photos += 1 self.saved_depth_photos += 1 self.saved_color_photos_signal.emit(self.saved_color_photos) self.saved_depth_photos_signal.emit(self.saved_depth_photos) def run(self): ROT = 3 while self.is_running: # 从相机获取彩色图和深度图 frames = self.pipeline.wait_for_frames() color_frame = frames.get_color_frame() depth_frame = frames.get_depth_frame() depth_image = np.asanyarray(depth_frame.get_data()) color_image = np.asanyarray(color_frame.get_data()) # 转换成 Qt 图像格式 depth_colormap = cv2.applyColorMap(cv2.convertScaleAbs(depth_image, alpha=0.03), cv2.COLORMAP_JET) # 将深度图像转换为伪彩色图像 color_image = QImage(color_image, color_image.shape[1], color_image.shape[0], color_image.shape[1] * 3, QImage.Format_RGB888) depth_colormap = QImage(depth_colormap, depth_colormap.shape[1], depth_colormap.shape[0], depth_colormap.shape[1] * 3, QImage.Format_RGB888) # 显示图像 self.color_label.setPixmap(QPixmap.fromImage(color_image)) self.depth_label.setPixmap(QPixmap.fromImage(depth_colormap)) v = self._dgl.qpin(ROT) if len(v) > 0: self._count += sum(v) if self._count > self._inspect_step: self.save_photo(color_image, depth_colormap) self._count -= self._inspect_step
根据提示信息,'_dgl' 属性在 'ImageThread' 对象中不存在。你需要在类的构造函数中初始化 '_dgl' 属性。
你可以在类的构造函数中添加以下代码:
```python
self._dgl = YourDGLClass()
```
其中,'YourDGLClass' 是你要使用的类所代表的名称。如果你没有定义这个类,你需要先定义这个类并实现相关方法。
此外,在上述代码中,还有一个 '_count' 属性也没有在类的构造函数中初始化。你需要为 '_count' 属性赋予一个初始值,例如:
```python
self._count = 0
```
这样,在执行到 'if self._count > self._inspect_step:' 这行代码时,'_count' 属性就不会出现 'not defined' 的情况了。
阅读全文