mnist_data = MNIST('.', download=True, transform=ToTensor()) dataloader = DataLoader(mnist_data, shuffle=True, batch_size=60000) X, y = next(iter(dataloader))
# the active learning loop n_queries = 10 for idx in range(n_queries): print('Query no. %d' % (idx + 1)) query_idx, query_instance = learner.query(X_pool, n_instances=100) learner.teach( X=X_pool[query_idx], y=y_pool[query_idx], only_new=True, ) # remove queried instance from pool X_pool = np.delete(X_pool, query_idx, axis=0) y_pool = np.delete(y_pool, query_idx, axis=0)
在运行时会报错,TypeError: <class 'torch.Tensor'> datatype is not supported
这是因为modAL中的learner并不支持tensor类型的输入,所以这里x_pool和y_pool会出现错误
解决办法把tensor类型转化成numpy数据类型,即在X, y = next(iter(dataloader))后加两行
x=x.detach().cpu().numpy() y=y.detach().cpu().numpy()
这里detach()作用是返回一个新的Tensor,只不过不再有梯度。
如果想把CUDA tensor格式的数据改成numpy时,需要先将其转换成cpu float-tensor随后再转到numpy格式。 numpy不能读取CUDA tensor 需要将它转化为 CPU tensor