奇怪的错误
Created by: shaoshenchen
环境:AI Studio高级版
错误
TypeError: conv2d(): incompatible function arguments. The following argument types are supported:
1. (arg0: paddle::imperative::VarBase, arg1: paddle::imperative::VarBase, *args) -> paddle::imperative::VarBase
Invoked with: <paddle.fluid.core_avx.VarBase object at 0x7f04dd29bf70>, name: "conv2d_0.w_0"
type {
type: LOD_TENSOR
lod_tensor {
tensor {
data_type: FP32
dims: 32
dims: 3
dims: 3
dims: 3
}
}
}
persistable: true
, 'strides', [1, 1], 'paddings', [1, 1], 'dilations', [1, 1], 'groups', 1, 'use_cudnn', True
代码
import paddle
import paddle.fluid as fluid
import numpy as np
from paddle.fluid.dygraph import Conv2D, Pool2D, Linear, BatchNorm
from paddle.fluid.layers import softmax, cross_entropy, mean, accuracy
from paddle.fluid.optimizer import AdamOptimizer
from visualdl import LogWriter
cfg = {
"batch_size": 128,
"epoch_num": 20,
"learning_rate": 1e-4,
"save_model_dir": "model/MiniVGG"
}
train_reader = paddle.batch(
fluid.io.shuffle(
paddle.dataset.cifar.train100(), 5000),
batch_size=cfg["batch_size"], drop_last=True)
test_reader = paddle.batch(
fluid.io.shuffle(
paddle.dataset.cifar.test100(), 5000),
batch_size=cfg["batch_size"], drop_last=True)
class MiniVGG(fluid.dygraph.Layer):
def __init__(self):
super().__init__()
self.conv_layers = [32, 64, 128]
self.fc_layers = [1024, 1024]
# (3, 32, 32)
self._conv1_1 = Conv2D(num_channels=3, num_filters=self.conv_layers[0], filter_size=3, padding=1)
self._conv1_2 = Conv2D(num_channels=self.conv_layers[0], num_filters=self.conv_layers[0], filter_size=3, padding=1)
self._pool1 = Pool2D(pool_size=2, pool_stride=2)
# (32, 16, 16)
self._conv2_1 = Conv2D(num_channels=self.conv_layers[0], num_filters=self.conv_layers[1], filter_size=3, padding=1)
self._conv2_2 = Conv2D(num_channels=self.conv_layers[1], num_filters=self.conv_layers[1], filter_size=3, padding=1)
self._pool2 = Pool2D(pool_size=2, pool_stride=2)
# (64, 8, 8)
self._conv3_1 = Conv2D(num_channels=self.conv_layers[1], num_filters=self.conv_layers[2], filter_size=3, padding=1)
self._conv3_2 = Conv2D(num_channels=self.conv_layers[2], num_filters=self.conv_layers[2], filter_size=3, padding=1)
self._conv3_3 = Conv2D(num_channels=self.conv_layers[2], num_filters=self.conv_layers[2], filter_size=3, padding=1)
self._pool3 = Pool2D(pool_size=2, pool_stride=2)
# (128, 4, 4)
self._bn = BatchNorm(self.conv_layers[2])
self._fc1 = Linear(self.conv_layers[2]*4*4, self.fc_layers[0], act="relu")
self._fc2 = Linear(self.fc_layers[0], self.fc_layers[1], act="relu")
self._fc3 = Linear(self.fc_layers[1], 100, act="softmax")
def forward(self, x):
x = self._conv1_1(x)
x = self._conv1_2(x)
x = self._pool1(x)
x = self._conv2_1(x)
x = self._conv2_2(x)
x = self._pool2(x)
x = self._conv3_1(x)
x = self._conv3_2(x)
x = self._conv3_3(x)
x = self._pool3(x)
x = self._bn(x)
x = fluid.layers.reshape(x, [-1, self.conv_layers[2]*4*4])
x = self._fc1(x)
x = self._fc2(x)
x = self._fc3(x)
return x
writer = LogWriter("log")
vdl_count1 = 0
vdl_count2 = 0
vgg = MiniVGG() # 模型
with fluid.dygraph.guard(fluid.CUDAPlace(0)):
for epoch in range(cfg["epoch_num"]):
for batch_id, data in enumerate(train_reader()):
# 定义数据(define)
img = fluid.dygraph.to_variable(
np.array(
[x[0].reshape(3, 32, 32) for x in data]
).astype(np.float32)
)
label = fluid.dygraph.to_variable(
np.array(
[y[1] for y in data]
).astype(np.int64).reshape(-1, 1)
)
# 前向计算(forward)
pred = vgg(img)
pred = fluid.layers.reshape(pred, [-1, 100])
# 损失函数(loss)
loss = cross_entropy(pred, label)
loss = fluid.layers.mean(loss)
loss.backward()
acc = fluid.layers.accuracy(pred, label)
# 优化(backward)
adam = AdamOptimizer( # 优化器
learning_rate=cfg["learning_rate"],
parameter_list=vgg.parameters())
adam.minimize(loss)
vgg.clear_gradients()
if batch_id % 50 == 0:
print("Epoch {0} Batch {1} Loss{2} Acc{3}".format(
epoch, batch_id, loss.numpy(), acc.numpy()))
writer.add_scalar(tag="Train/loss", step=vdl_count1, value=loss.numpy()[0])
writer.add_scalar(tag="Train/acc", step=vdl_count1, value=acc.numpy()[0])
vdl_count1 += 1
# 评估
loss_list = list()
acc_list = list()
for batch_id, data in enumerate(test_reader()):
img = fluid.dygraph.to_variable(
np.array(
[x[0].reshape(3, 32, 32) for x in data]
).astype(np.float32))
label = fluid.dygraph.to_variable(
np.array(
[y[1] for y in data]
).astype(np.int64).reshape(-1, 1))
# forward
pred = vgg(img)
# loss
loss = cross_entropy(pred, label)
loss = mean(loss)
acc = accuracy(pred, label)
if batch_id % 10 == 0:
writer.add_scalar(tag="Test/loss", step=vdl_count2, value=loss.numpy()[0])
writer.add_scalar(tag="Test/acc", step=vdl_count2, value=acc.numpy()[0])
vdl_count2 += 1
# 记录loss和acc
loss_list.append(loss.numpy()[0])
acc_list.append(acc.numpy()[0])
print("Eval ———— Loss {} Acc {}\n".format(
float(np.array(loss_list).mean()), float(np.array(acc_list).mean())))
state_dict = vgg.state_dict()
fluid.save_dygraph(state_dict, cfg["save_model_dir"])
print("Save dygraph succeed!")
解决办法
重新运行一次出错的代码即可。出错的原因尽然是“出错”?不可思议~哪位RD小哥哥能解答一下