dmlc--dgl
44089c8b4d
* Merge * [Graph][CUDA] Graph on GPU and many refactoring (#1791) * change edge_ids behavior and C++ impl * fix unittests; remove utils.Index in edge_id * pass mx and th tests * pass tf test * add aten::Scatter_ * Add nonzero; impl CSRGetDataAndIndices/CSRSliceMatrix * CSRGetData and CSRGetDataAndIndices passed tests * CSRSliceMatrix basic tests * fix bug in empty slice * CUDA CSRHasDuplicate * has_node; has_edge_between * predecessors, successors * deprecate send/recv; fix send_and_recv * deprecate send/recv; fix send_and_recv * in_edges; out_edges; all_edges; apply_edges * in deg/out deg * subgraph/edge_subgraph * adj * in_subgraph/out_subgraph * sample neighbors * set/get_n/e_repr * wip: working on refactoring all idtypes * pass ndata/edata tests on gpu * fix * stash * workaround nonzero issue * stash * nx conversion * test_hetero_basics except update routines * test_update_routines * test_hetero_basics for pytorch * more fixes * WIP: flatten graph * wip: flatten * test_flatten * test_to_device * fix bug in to_homo * fix bug in CSRSliceMatrix * pass subgraph test * fix send_and_recv * fix filter * test_heterograph * passed all pytorch tests * fix mx unittest * fix pytorch test_nn * fix all unittests for PyTorch * passed all mxnet tests * lint * fix tf nn test * pass all tf tests * lint * lint * change deprecation * try fix compile * lint * update METIDS * fix utest * fix * fix utests * try debug * revert * small fix * fix utests * upd * upd * upd * fix * upd * upd * upd * upd * upd * trigger * +1s * [kernel] Use heterograph index instead of unitgraph index (#1813) * upd * upd * upd * fix * upd * upd * upd * upd * upd * trigger * +1s * [Graph] Mutation for Heterograph (#1818) * mutation add_nodes and add_edges * Add support for remove_edges, remove_nodes, add_selfloop, remove_selfloop * Fix Co-authored-by: Ubuntu <ubuntu@ip-172-31-51-214.ec2.internal> * upd * upd * upd * fix * [Transfom] Mutable transform (#1833) * add nodesy * All three * Fix * lint * Add some test case * Fix * Fix * Fix * Fix * Fix * Fix * fix * triger * Fix * fix Co-authored-by: Ubuntu <ubuntu@ip-172-31-51-214.ec2.internal> * [Graph] Migrate Batch & Readout module to heterograph (#1836) * dgl.batch * unbatch * fix to device * reduce readout; segment reduce * change batch_num_nodes|edges to function * reduce readout/ softmax * broadcast * topk * fix * fix tf and mx * fix some ci * fix batch but unbatch differently * new checkk * upd * upd * upd * idtype behavior; code reorg * idtype behavior; code reorg * wip: test_basics * pass test_basics * WIP: from nx/ to nx * missing files * upd * pass test_basics:test_nx_conversion * Fix test * Fix inplace update * WIP: fixing tests * upd * pass test_transform cpu * pass gpu test_transform * pass test_batched_graph * GPU graph auto cast to int32 * missing file * stash * WIP: rgcn-hetero * Fix two datasety * upd * weird * Fix capsuley * fuck you * fuck matthias * Fix dgmg * fix bug in block degrees; pass rgcn-hetero * rgcn * gat and diffpool fix also fix ppi and tu dataset * Tree LSTM * pointcloud * rrn; wip: sgc * resolve conflicts * upd * sgc and reddit dataset * upd * Fix deepwalk, gindt and gcn * fix datasets and sign * optimization * optimization * upd * upd * Fix GIN * fix bug in add_nodes add_edges; tagcn * adaptive sampling and gcmc * upd * upd * fix geometric * fix * metapath2vec * fix agnn * fix pickling problem of block * fix utests * miss file * linegraph * upd * upd * upd * graphsage * stgcn_wave * fix hgt * on unittests * Fix transformer * Fix HAN * passed pytorch unittests * lint * fix * Fix cluster gcn * cluster-gcn is ready * on fixing block related codes * 2nd order derivative * Revert "2nd order derivative" This reverts commit 523bf6c249bee61b51b1ad1babf42aad4167f206. * passed torch utests again * fix all mxnet unittests * delete some useless tests * pass all tf cpu tests * disable * disable distributed unittest * fix * fix * lint * fix * fix * fix script * fix tutorial * fix apply edges bug * fix 2 basics * fix tutorial Co-authored-by: yzh119 <expye@outlook.com> Co-authored-by: xiang song(charlie.song) <classicxsong@gmail.com> Co-authored-by: Ubuntu <ubuntu@ip-172-31-51-214.ec2.internal> Co-authored-by: Ubuntu <ubuntu@ip-172-31-7-42.us-west-2.compute.internal> Co-authored-by: Ubuntu <ubuntu@ip-172-31-1-5.us-west-2.compute.internal> Co-authored-by: Ubuntu <ubuntu@ip-172-31-68-185.ec2.internal>
153 行
5.1 KiB
Python
153 行
5.1 KiB
Python
import torch
|
|
torch.backends.cudnn.enabled = False
|
|
import torch.nn as nn
|
|
import torch.nn.functional as F
|
|
import torch.optim as optim
|
|
from torch.utils.data import DataLoader
|
|
import dgl
|
|
from dgl.data.utils import download, get_download_dir
|
|
|
|
from functools import partial
|
|
import tqdm
|
|
import urllib
|
|
import os
|
|
import argparse
|
|
|
|
# from dataset import ModelNet
|
|
import provider
|
|
from ModelNetDataLoader import ModelNetDataLoader
|
|
from pointnet_cls import PointNetCls
|
|
from pointnet2 import PointNet2SSGCls, PointNet2MSGCls
|
|
|
|
parser = argparse.ArgumentParser()
|
|
parser.add_argument('--model', type=str, default='pointnet')
|
|
parser.add_argument('--dataset-path', type=str, default='')
|
|
parser.add_argument('--load-model-path', type=str, default='')
|
|
parser.add_argument('--save-model-path', type=str, default='')
|
|
parser.add_argument('--num-epochs', type=int, default=200)
|
|
parser.add_argument('--num-workers', type=int, default=8)
|
|
parser.add_argument('--batch-size', type=int, default=32)
|
|
args = parser.parse_args()
|
|
|
|
num_workers = args.num_workers
|
|
batch_size = args.batch_size
|
|
|
|
data_filename = 'modelnet40_normal_resampled.zip'
|
|
download_path = os.path.join(get_download_dir(), data_filename)
|
|
local_path = args.dataset_path or os.path.join(get_download_dir(), 'modelnet40_normal_resampled')
|
|
|
|
if not os.path.exists(local_path):
|
|
download('https://shapenet.cs.stanford.edu/media/modelnet40_normal_resampled.zip',
|
|
download_path, verify_ssl=False)
|
|
from zipfile import ZipFile
|
|
with ZipFile(download_path) as z:
|
|
z.extractall(path=get_download_dir())
|
|
|
|
CustomDataLoader = partial(
|
|
DataLoader,
|
|
num_workers=num_workers,
|
|
batch_size=batch_size,
|
|
shuffle=True,
|
|
drop_last=True)
|
|
|
|
def train(net, opt, scheduler, train_loader, dev):
|
|
|
|
net.train()
|
|
|
|
total_loss = 0
|
|
num_batches = 0
|
|
total_correct = 0
|
|
count = 0
|
|
loss_f = nn.CrossEntropyLoss()
|
|
with tqdm.tqdm(train_loader, ascii=True) as tq:
|
|
for data, label in tq:
|
|
data = data.data.numpy()
|
|
data = provider.random_point_dropout(data)
|
|
data[:, :, 0:3] = provider.random_scale_point_cloud(data[:, :, 0:3])
|
|
data[:, :, 0:3] = provider.jitter_point_cloud(data[:, :, 0:3])
|
|
data[:, :, 0:3] = provider.shift_point_cloud(data[:, :, 0:3])
|
|
data = torch.tensor(data)
|
|
label = label[:, 0]
|
|
|
|
num_examples = label.shape[0]
|
|
data, label = data.to(dev), label.to(dev).squeeze().long()
|
|
opt.zero_grad()
|
|
logits = net(data)
|
|
loss = loss_f(logits, label)
|
|
loss.backward()
|
|
opt.step()
|
|
|
|
_, preds = logits.max(1)
|
|
|
|
num_batches += 1
|
|
count += num_examples
|
|
loss = loss.item()
|
|
correct = (preds == label).sum().item()
|
|
total_loss += loss
|
|
total_correct += correct
|
|
|
|
tq.set_postfix({
|
|
'AvgLoss': '%.5f' % (total_loss / num_batches),
|
|
'AvgAcc': '%.5f' % (total_correct / count)})
|
|
scheduler.step()
|
|
|
|
def evaluate(net, test_loader, dev):
|
|
net.eval()
|
|
|
|
total_correct = 0
|
|
count = 0
|
|
|
|
with torch.no_grad():
|
|
with tqdm.tqdm(test_loader, ascii=True) as tq:
|
|
for data, label in tq:
|
|
label = label[:,0]
|
|
num_examples = label.shape[0]
|
|
data, label = data.to(dev), label.to(dev).squeeze().long()
|
|
logits = net(data)
|
|
_, preds = logits.max(1)
|
|
|
|
correct = (preds == label).sum().item()
|
|
total_correct += correct
|
|
count += num_examples
|
|
|
|
tq.set_postfix({
|
|
'AvgAcc': '%.5f' % (total_correct / count)})
|
|
|
|
return total_correct / count
|
|
|
|
dev = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
|
|
|
if args.model == 'pointnet':
|
|
net = PointNetCls(40, input_dims=6)
|
|
elif args.model == 'pointnet2_ssg':
|
|
net = PointNet2SSGCls(40, batch_size, input_dims=6)
|
|
elif args.model == 'pointnet2_msg':
|
|
net = PointNet2MSGCls(40, batch_size, input_dims=6)
|
|
|
|
net = net.to(dev)
|
|
if args.load_model_path:
|
|
net.load_state_dict(torch.load(args.load_model_path, map_location=dev))
|
|
|
|
opt = optim.Adam(net.parameters(), lr=1e-3, weight_decay=1e-4)
|
|
|
|
scheduler = optim.lr_scheduler.StepLR(opt, step_size=20, gamma=0.7)
|
|
|
|
train_dataset = ModelNetDataLoader(local_path, 1024, split='train')
|
|
test_dataset = ModelNetDataLoader(local_path, 1024, split='test')
|
|
train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=batch_size, shuffle=True, num_workers=num_workers, drop_last=True)
|
|
test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=batch_size, shuffle=False, num_workers=num_workers, drop_last=True)
|
|
|
|
best_test_acc = 0
|
|
|
|
for epoch in range(args.num_epochs):
|
|
train(net, opt, scheduler, train_loader, dev)
|
|
if (epoch + 1) % 1 == 0:
|
|
print('Epoch #%d Testing' % epoch)
|
|
test_acc = evaluate(net, test_loader, dev)
|
|
if test_acc > best_test_acc:
|
|
best_test_acc = test_acc
|
|
if args.save_model_path:
|
|
torch.save(net.state_dict(), args.save_model_path)
|
|
print('Current test acc: %.5f (best: %.5f)' % (
|
|
test_acc, best_test_acc))
|