devalab / CIGIN

AAAI 2020: Chemically Interpretable Graph Interaction Network for Prediction of Pharmacokinetic Properties of Drug-like Molecules
MIT License
35 stars 19 forks source link

AttributeError: 'numpy.ndarray' object has no attribute 'device' #9

Open zyrlia1018 opened 3 years ago

zyrlia1018 commented 3 years ago

Using backend: pytorch 0%| | 0/1 [00:00<?, ?it/s] Traceback (most recent call last): File "main.py", line 105, in main() File "main.py", line 101, in main train(max_epochs, model, optimizer, scheduler, train_loader, valid_loader, project_name) File "F:\zouyr\pythonProject\CIGIN-master\CIGIN_V2\train.py", line 40, in train for samples in tq_loader: File "D:\ANACONDA\envs\onionnet\lib\site-packages\tqdm\std.py", line 1178, in iter for obj in iterable: File "D:\ANACONDA\envs\onionnet\lib\site-packages\torch\utils\data\dataloader.py", line 517, in next data = self._next_data() File "D:\ANACONDA\envs\onionnet\lib\site-packages\torch\utils\data\dataloader.py", line 557, in _next_data data = self._dataset_fetcher.fetch(index) # may raise StopIteration File "D:\ANACONDA\envs\onionnet\lib\site-packages\torch\utils\data_utils\fetch.py", line 44, in fetch data = [self.dataset[idx] for idx in possibly_batched_index] File "D:\ANACONDA\envs\onionnet\lib\site-packages\torch\utils\data_utils\fetch.py", line 44, in data = [self.dataset[idx] for idx in possibly_batched_index] File "main.py", line 74, in getitem solute_graph = get_graph_from_smile(solute) File "F:\zouyr\pythonProject\CIGIN-master\CIGIN_V2\molecular_graph.py", line 95, in get_graph_from_smile G.ndata['x'] = np.array(node_features) File "D:\ANACONDA\envs\onionnet\lib\site-packages\dgl\view.py", line 81, in setitem self._graph._set_n_repr(self._ntid, self._nodes, {key : val}) File "D:\ANACONDA\envs\onionnet\lib\site-packages\dgl\heterograph.py", line 3994, in _set_n_repr if F.context(val) != self.device: File "D:\ANACONDA\envs\onionnet\lib\site-packages\dgl\backend\pytorch\tensor.py", line 76, in context return input.device AttributeError: 'numpy.ndarray' object has no attribute 'device'

harrypotty18 commented 2 years ago

I have the same problem, did you solve it?

harrypotty18 commented 2 years ago

I have fixed it!

  1. G.ndata['x'] = np.array(node_features) should be: G.ndata['x'] = torch.from_numpy(np.array(node_features)) G.edata['w'] = torch.from_numpy(np.array(edge_features))

  2. solute_len_matrix = get_len_matrix(solute_graphs.batch_num_nodes), and solvent_len_matrix = get_len_matrix(solvent_graphs.batch_num_nodes should be like this: solute_len_matrix = get_len_matrix(solute_graphs.batch_num_nodes().numpy()) solvent_len_matrix = get_len_matrix(solvent_graphs.batch_num_nodes().numpy()) (File unity.py, line 58,59 in collate function)

colour307 commented 2 years ago

hi,bro! I have a question, when the model has been trained and save in "bese_model.tar", how to load and use the mode?

zyrlia1018 commented 2 years ago

hi,bro! I have a question, when the model has been trained and save in "bese_model.tar", how to load and use the mode? This project doesn't have an application file like eval.py, so you can write your own from train.py.

colour307 commented 2 years ago

hi,bro! I have a question, when the model has been trained and save in "bese_model.tar", how to load and use the mode? This project doesn't have an application file like eval.py, so you can write your own from train.py.

ok,i get it. I have already load the model. but I have another question. I use my dataset to predict the properties of energetic materials.the code is follow: import dgl import matplotlib.pyplot as plt from torch.utils.data import DataLoader, Dataset from GNNmodel import GNNModel from GNNmolecular_graph import get_graph_from_smile from rdkit import Chem

model = GNNModel() model.load_state_dict(torch.load("runs/run-gnn/models/best_model.tar"))

model=(torch.load("runs/run-gnn/models/best_model.tar"))

print(model)

use_cuda = torch.cuda.is_available() device = torch.device("cuda" if use_cuda else "cpu")

def get_len_matrix(len_list): len_list = np.array(len_list) max_nodes = np.sum(len_list) curr_sum = 0 len_matrix = [] for l in len_list: curr = np.zeros(max_nodes) curr[curr_sum:curr_sum + l] = 1 len_matrix.append(curr) curr_sum += l return np.array(len_matrix)

def collate(samples): density_graphs, labels = map(list, zip(*samples)) density_graphs = dgl.batch(density_graphs) density_len_matrix = get_len_matrix(density_graphs.batch_num_nodes().numpy()) return density_graphs, density_len_matrix, labels

class Dataclass(Dataset): def init(self, dataset): self.dataset = dataset

def __len__(self):
    return len(self.dataset)

def __getitem__(self, idx):

    density = self.dataset.iloc[idx]['SMILES']
    mol = Chem.MolFromSmiles(density)
    mol = Chem.AddHs(mol)
    density = Chem.MolToSmiles(mol)
    density_graph = get_graph_from_smile(density)

    delta_density = self.dataset.iloc[idx]['Delta_Density']
    return [density_graph, [delta_density]]

Data_df = pd.read_csv('data/Nitro aromatic 1.csv', encoding='ANSI', skipinitialspace=True) test_df = Data_df.sample(frac=0.8) test_dataset = Dataclass(test_df) test_loader = DataLoader(test_dataset, collate_fn=collate, batch_size=128, shuffle=True)

test_batch = next(iter(test_loader)) model.to(device) with torch.no_grad(): test_batch.to(device)

and the AttributeError: 'tuple' object has no attribute 'to', how to resolve the error? Thank you very much