Skip to content

如何使用GPU训练模型? #32

@lingjiajie

Description

@lingjiajie

您好!

我是的代码是在案例“混合量子经典神经网络模型”的基础上进行修改的。修改的代码如下:

`
x_train, y_train, x_test, y_test = data_select(1000, 100)
model = Net().toGPU()

optimizer = Adam(model.parameters(), lr=0.005)
#分类任务使用交叉熵函数
loss_func = CategoricalCrossEntropy()

#训练次数
epochs = 10
train_loss_list = []
val_loss_list = []
train_acc_list =[]

val_acc_list = []

for epoch in range(1, epochs):

total_loss = []
model.train()
batch_size = 1
correct = 0
n_train = 0

for x, y in data_generator(x_train, y_train, batch_size=1, shuffle=True):

    x = x.reshape(-1, 1, 28, 28)
    x = QTensor(x)
    y = QTensor(y)
    x = x.to_gpu(DEV_GPU_0)
    y = y.to_gpu(DEV_GPU_0)
    optimizer.zero_grad()
    output = model(x)
    loss = loss_func(y, output)
    loss_np = np.array(loss.data)
    np_output = np.array(output.data, copy=False)
    mask = (np_output.argmax(1) == y.argmax(1))
    correct += np.sum(np.array(mask))
    n_train += batch_size
    loss.backward()
    optimizer._step()
    total_loss.append(loss_np)

train_loss_list.append(np.sum(total_loss) / len(total_loss))
train_acc_list.append(np.sum(correct) / n_train)
print("{:.0f} loss is : {:.10f}".format(epoch, train_loss_list[-1]))

`

但是出现下面的问题:

terminate called after throwing an instance of 'std::invalid_argument' what(): tensor --> numpy device not supported, toCPU() first. Aborted (core dumped)

请问这是哪里出了问题?谢谢!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions