训练ResNet50网络出错
为使您的问题得到快速解决,在建立Issues前,请您先通过如下方式搜索是否有相似问题:【搜索issue关键字】【使用labels筛选】【官方文档】
- 标题:利用Natural Images fine tune
- 版本、环境信息: 1)PaddlePaddle版本:paddlepaddle-gpu 1.8.0.post107 3)GPU:gtx950m ,cuda 10.2, V10.2.89 4)系统环境:py3.7+win10 家庭普通版
- 训练信息 1)单机,单卡 2)6169m
- 问题描述: 这个是b站上边别人fine-tune Natural Images 视频的文件(录制时间2018年),视频文件显示运行良好,没有任何bug。自己加载文件目录也是正确的,但是当运行时候就会报错,下边先展示运行moudle代码
#先来尝试一下完全使用 ImageNet预训练的权重,效果怎样吧
test_program` = fluid.Program()
test_startup = fluid.Program()
with fluid.program_guard(test_program, test_startup):
with fluid.unique_name.guard():
image = fluid.layers.data(name='image', shape=(-1, 3, 224, 224), dtype='float32')
label = fluid.layers.data(name='label', shape=(-1, 1), dtype='int64')
_, fetch_list = create_network(image, label, is_test=True)
# 大家如果没有 GPU,可以将其改为 False
# 注意: CPU 中 PaddlePaddle 并不一定实现了所有的 Operator 的训练,一般建议大家使用 GPU
use_gpu = True
place = fluid.CUDAPlace(0) if use_gpu else fluid.CPUPlace()
exe = `fluid.Executor(place)
# 初始化一下 Executor
exe.run(program=test_startup)
# 载入预训练的模型参数
def _predicate(var):
# 查看 var 参数是不是在预训练模型路径内
return os.path.exists(os.path.join(pretrained_model_path, var.name))
fluid.io.load_vars(exe, pretrained_model_path, predicate=_predicate, main_program=test_program)
data = exe.run(program=test_program, fetch_list=fetch_list, feed={'image': images, 'label': labels})
# 把数据从 data 中取出来 (data 是一个列表,顺序与 fetch_list 相同)
image, label = data[0:2]
out, confidence, top5_scores, top5_indices = data[2:6]
loss, acc_top1, acc_top5 = data[6:]
display_batch(image)
print('ImageNet 预训练模型情况: loss=%06.3f top-1=%05.2f%% top-5=%05.2f%%' % (
loss, acc_top1 * 100, acc_top5 * 100))
log_topk_info(None, top5_scores, top5_indices)
# 之后要重新创建模型进行针对 Natural Images 的再训练,故这里的 Program 和 Executor 都不再需要了
exe.close()
报错信息
TypeError Traceback (most recent call last)
<ipython-input-17-bb3713832880> in <module>
8 image = fluid.layers.data(name='image', shape=(-1, 3, 224, 224), dtype='float32')
9 label = fluid.layers.data(name='label', shape=(-1, 1), dtype='int64')
---> 10 _, fetch_list = create_network(image, label, is_test=True)
11
12 # 大家如果没有 GPU,可以将其改为 False
<ipython-input-13-3a2c2fad7823> in create_network(image, label, class_dim, is_test)
9
10 model = ResNet(is_test=is_test)
---> 11 out = model.net(image, class_dim=class_dim)
12
13 confidence = fluid.layers.softmax(out)
<ipython-input-12-9f956ea050fb> in net(self, input, class_dim)
49 initializer=fluid.initializer.Uniform(-stdv, stdv), trainable=True)
50 out = fluid.layers.fc(
---> 51 input=pool, size=class_dim, act=None, is_test=self.is_test, param_attr=fc_param_attr)
52
53 return out
TypeError: fc() got an unexpected keyword argument 'is_test'
不知道有什么解决办法没有?应该不是gpu原因,gpu=true 看有人issue里边说TypeError:可能是版本问题,假如是版本问题,18年录制的视频,应该使用哪种paddle版本,我是直接paddle官网首页按照系统选择安装的,望解答!多谢各位!!
1.6之前的版本,fc接口有is_test参数 https://github.com/PaddlePaddle/Paddle/blob/a5696153a013552bfaa612ca407eba318e18ba54/python/paddle/fluid/layers/nn.py#L218 1.6之后我们进行了升级,移除了is_test参数 https://github.com/PaddlePaddle/Paddle/blob/28f871d4bd9f239aefb2118bf3a83225630160af/python/paddle/fluid/layers/nn.py#L233 这边建议使用新版paddle,参考fc接口使用文档,修改源码即可 https://www.paddlepaddle.org.cn/documentation/docs/zh/api_cn/layers_cn/fc_cn.html#fc
@huangjun12 1.6以前的paddle版本在哪里下载?不太会修改源码,is_test还牵扯到create_network函数
@huangjun12 包括class resnet ,create_network 都牵扯到了is_test函数,要修改的话如何修改,把is_test 全部改成act="tanh"吗?
@huangjun12 1.6以前的paddle版本在哪里下载?不太会修改源码,is_test还牵扯到create_network函数
可以先阅读官网的安装文档 https://www.paddlepaddle.org.cn/documentation/docs/zh/develop/install/install_Ubuntu.html pip方式安装的话,可以使用如下命令 pip install paddlepaddle-gpu==1.5.2.post97 (此命令为gpu版的paddle,版本号为1.5.2,使用环境为cuda9,cudnn7) 其它可选版本参考 https://pypi.org/project/paddlepaddle-gpu/#history
@huangjun12 您好,有conda安装原来版本的网站吗?您给的最后一个网址是pip安装的,官网安装文档只能安装最新的paddle!
请问,假如要修改源码的话,需要怎么修改呀?我在源码里边好像并没有找到fc函数,只在class resnet、和def creat_network里边找到了is_test参数,按照文档的意思,好像把act放在fluid.layers.fc内的参数了,没有is_test了
请问,假如要修改源码的话,需要怎么修改呀?我在源码里边好像并没有找到fc函数,只在class resnet、和def creat_network里边找到了is_test参数,按照文档的意思,好像把act放在fluid.layers.fc内的参数了,没有is_test了
方便贴一下用到的代码吗
@huangjun12 您好,有conda安装原来版本的网站吗?您给的最后一个网址是pip安装的,官网安装文档只能安装最新的paddle!
conda下面也是可以用pip安装的
请问,假如要修改源码的话,需要怎么修改呀?我在源码里边好像并没有找到fc函数,只在class resnet、和def creat_network里边找到了is_test参数,按照文档的意思,好像把act放在fluid.layers.fc内的参数了,没有is_test了
方便贴一下用到的代码吗
您好! 与is_test有关的代码如下
# 列出所有数据集里的图片,给出 (路径, 类名) 的列表
# - 训练时,使用每个分类里前 80%
# - 验证时,使用每个分类里后 20%
def list_files(basepath, mode='all'):
assert mode in ['train', 'test', 'all']
files = []
for name in label_names:
class_files = sorted(os.listdir(os.path.join(basepath, name)))
part = int(len(class_files) * 0.8)
if mode == 'train':
class_files = class_files[:part]
elif mode == 'test':
class_files = class_files[part:]
for file in class_files:
files.append((os.path.join(basepath, name, file), name))
return files
class BaseReader(object):
"""定义 PaddlePaddle 的 Reader 的生成类
由它提供生成 train_reader 和 test_reader 两种类型的 Reader
使用两种类型的 reader 的原因是因为 train 和 test 在图像预处理 (图像增强) 的部分使用的操作不相同
在训练的过程中,尽可能希望模型能够看到更多更丰富更多样化的输入数据,所以经常会使用类似于
* 随机切块
* 随机翻转
* 随机调整图像明度、色彩
等等操作。
而预测/验证的情况下,尽可能要保证图像原本完整的信息,可能会使用的有
* 图像拉伸
* 图像中心切块
等等尽量能够保留最多最显著图像内容部分的操作。
"""
@staticmethod
def rescale_image(img, target_size):
width, height = img.size
percent = float(target_size) / min(width, height)
resized_width = int(round(width * percent))
resized_height = int(round(height * percent))
img = img.resize((resized_width, resized_height), PIL.Image.LANCZOS)
return img
@staticmethod
def resize_image(img, target_size):
img = img.resize((target_size, target_size), PIL.Image.LANCZOS)
return img
@staticmethod
def crop_image(img, target_size, center=True):
width, height = img.size
size = target_size
if center == True:
w_start = (width - size) / 2
h_start = (height - size) / 2
else:
w_start = np.random.randint(0, width - size + 1)
h_start = np.random.randint(0, height - size + 1)
w_end = w_start + size
h_end = h_start + size
img = img.crop((w_start, h_start, w_end, h_end))
return img
@staticmethod
def random_crop(img, size, scale=[0.08, 1.0], ratio=[3. / 4., 4. / 3.]):
aspect_ratio = math.sqrt(np.random.uniform(*ratio))
w = 1. * aspect_ratio
h = 1. / aspect_ratio
bound = min((float(img.size[0]) / img.size[1]) / (w**2),
(float(img.size[1]) / img.size[0]) / (h**2))
scale_max = min(scale[1], bound)
scale_min = min(scale[0], bound)
target_area = img.size[0] * img.size[1] * np.random.uniform(scale_min, scale_max)
target_size = math.sqrt(target_area)
w = int(target_size * w)
h = int(target_size * h)
i = np.random.randint(0, img.size[0] - w + 1)
j = np.random.randint(0, img.size[1] - h + 1)
img = img.crop((i, j, i + w, j + h))
img = img.resize((size, size), PIL.Image.LANCZOS)
return img
@staticmethod
def random_flip(img):
if np.random.randint(0, 2) == 1:
img = img.transpose(PIL.Image.FLIP_LEFT_RIGHT)
return img
@staticmethod
def rotate_image(img):
angle = np.random.randint(-10, 11)
img = img.rotate(angle)
return img
def create_train_reader(self, files):
def _reader():
for file, labelname in files:
image = PIL.Image.open(file)
image = BaseReader.rotate_image(image)
image = BaseReader.random_crop(image, 224)
image = BaseReader.random_flip(image)
image = np.array(image).astype('float32').transpose((2, 0, 1)) / 255
image = normalize_image(image)
label = label_class[labelname]
yield image, label
return _reader
def create_test_reader(self, files):
def _reader():
for file, labelname in files:
image = PIL.Image.open(file)
image = BaseReader.resize_image(image, 224)
image = BaseReader.crop_image(image, 224)
image = np.array(image).astype('float32').transpose((2, 0, 1)) / 255
image = normalize_image(image)
label = label_class[labelname]
yield image, label
return _reader
def image_grid(images, padding=3, pad_value=0):
"""从一批图像生成一张图像
images : 要求是 np.ndarray 符合 (batch, width, height, channel)
padding : 是两张图像之间的间隔像素
pad_value: 是间隔像素的颜色
"""
batch_size = images.shape[0]
nrows, ncols, ncnls = images.shape[1:]
impcol = math.ceil(math.sqrt(batch_size))
improw = math.ceil(batch_size / impcol)
ret_rows = improw * nrows + padding * (improw + 1)
ret_cols = impcol * ncols + padding * (impcol + 1)
ret = np.ones((ret_rows, ret_cols, ncnls)) * pad_value
for ridx in range(improw):
for cidx in range(impcol):
idx = ridx * impcol + cidx
if idx >= batch_size:
break
img = images[idx]
rlb = (padding + nrows) * ridx + padding
rub = (padding + nrows) * (ridx + 1)
clb = (padding + ncols) * cidx + padding
cub = (padding + ncols) * (cidx + 1)
ret[rlb:rub, clb:cub, :] = img
return ret
def display_image(image):
"""显示一张图像
image 是 np.ndarray,符合 (batch, width, height, channel)
归一化到 [0, 1]
"""
image = (image * 255).astype(np.uint8)
image = PIL.Image.fromarray(image)
display(image)
def display_batch(images):
"""显示一批图像
image 是 np.ndarray,符合 (batch, channel, width, height)
"""
images = np.array([denorm_image(image) for image in images])
images = images.transpose(0, 2, 3, 1)
images = image_grid(images)
display_image(images)
class ResNet():
def __init__(self, is_test=False):
self.is_test = is_test
def net(self, input, class_dim=1000):
# if layers == 50:
# depth = [3, 4, 6, 3]
# elif layers == 101:
# depth = [3, 4, 23, 3]
# elif layers == 152:
# depth = [3, 8, 36, 3]
# num_filters = [64, 128, 256, 512]
conv = self.conv_bn_layer(
input=input, num_filters=64, filter_size=7, stride=2, act='relu', trainable=False)
conv = fluid.layers.pool2d(
input=conv, pool_size=3, pool_stride=2, pool_padding=1, pool_type='max')
# 原本官方代码,这里我们针对 ResNet-50 进行展开,看起来更清晰
# for block in range(len(depth)):
# for i in range(depth[block]):
# conv = self.bottleneck_block(
# input=conv,
# num_filters=num_filters[block],
# stride=2 if i == 0 and block != 0 else 1)
conv = self.bottleneck_block(input=conv, num_filters=64, stride=1, trainable=False)
conv = self.bottleneck_block(input=conv, num_filters=64, stride=1, trainable=False)
conv = self.bottleneck_block(input=conv, num_filters=64, stride=1, trainable=False)
conv = self.bottleneck_block(input=conv, num_filters=128, stride=2, trainable=False)
conv = self.bottleneck_block(input=conv, num_filters=128, stride=1, trainable=False)
conv = self.bottleneck_block(input=conv, num_filters=128, stride=1, trainable=False)
conv = self.bottleneck_block(input=conv, num_filters=128, stride=1, trainable=False)
conv = self.bottleneck_block(input=conv, num_filters=256, stride=2, trainable=False)
for _ in range(5):
conv = self.bottleneck_block(input=conv, num_filters=256, stride=1, trainable=False)
conv = self.bottleneck_block(input=conv, num_filters=512, stride=2, trainable=False)
conv = self.bottleneck_block(input=conv, num_filters=512, stride=1, trainable=False)
conv = self.bottleneck_block(input=conv, num_filters=512, stride=1, trainable=True)
pool = fluid.layers.pool2d(input=conv, pool_size=7, pool_type='avg', global_pooling=True)
# 设置 全连接层 参数初始化,并且一定为 trainable
stdv = 1.0 / math.sqrt(pool.shape[1] * 1.0)
fc_param_attr = fluid.param_attr.ParamAttr(
initializer=fluid.initializer.Uniform(-stdv, stdv), trainable=True)
out = fluid.layers.fc(
input=pool, size=class_dim, act=None, is_test=self.is_test, param_attr=fc_param_attr)
return out
def conv_bn_layer(self,
input,
num_filters,
filter_size,
stride=1,
groups=1,
act=None,
trainable=True):
param_attr = fluid.ParamAttr(trainable=trainable)
conv = fluid.layers.conv2d(
input=input,
num_filters=num_filters,
filter_size=filter_size,
stride=stride,
padding=(filter_size - 1) // 2,
groups=groups,
act=None,
bias_attr=False,
param_attr=param_attr)
return fluid.layers.batch_norm(
input=conv, act=act, is_test=self.is_test, param_attr=param_attr)
def shortcut(self, input, ch_out, stride, trainable=True):
ch_in = input.shape[1]
if ch_in != ch_out or stride != 1:
return self.conv_bn_layer(input, ch_out, 1, stride=stride, trainable=trainable)
else:
return input
def bottleneck_block(self, input, num_filters, stride, trainable=True):
conv0 = self.conv_bn_layer(
input=input,
num_filters=num_filters,
filter_size=1,
stride=1,
act='relu',
trainable=trainable)
conv1 = self.conv_bn_layer(
input=conv0,
num_filters=num_filters,
filter_size=3,
stride=stride,
act='relu',
trainable=trainable)
conv2 = self.conv_bn_layer(
input=conv1,
num_filters=num_filters * 4,
filter_size=1,
stride=1,
act=None,
trainable=trainable)
short = self.shortcut(input, num_filters * 4, stride, trainable=trainable)
return fluid.layers.elementwise_add(x=short, y=conv2, act='relu')
def create_network(image, label, class_dim=1000, is_test=False):
# image 以及 label 是 Variable 类型,在再训练过程中,他们是在 py_reader 的数据流中产生的
# 其类型和大小如下:
# image = fluid.layers.data(name='image', shape=(-1, 3, 224, 224), dtype='float32')
# label = fluid.layers.data(name='label', shape=(-1, 1), dtype='int64')
# is_test 是表明现在是在创建训练还是验证模型
# 由于是两个 fluid.Program 上下文,故建议分别创建
model = ResNet(is_test=is_test)
out = model.net(image, class_dim=class_dim)
confidence = fluid.layers.softmax(out)
top5_scores, top5_indices = fluid.layers.topk(confidence, k=5)
loss = fluid.layers.cross_entropy(input=confidence, label=label)
loss = fluid.layers.mean(x=loss)
acc_top1 = fluid.layers.accuracy(input=out, label=label, k=1)
acc_top5 = fluid.layers.accuracy(input=out, label=label, k=5)
fetch_list = [
image.name, label.name,
out.name, confidence.name, top5_scores.name, top5_indices.name,
loss.name, acc_top1.name, acc_top5.name
]
return loss, fetch_list
# 取得文件列表
train_files = list_files(files_path, mode='train')
test_files = list_files(files_path, mode='test')
np.random.shuffle(train_files)
np.random.shuffle(test_files)
# 预览一下他们 :)
print('训练文件列表:')
for i in range(batch_size):
print(train_files[i])
print('验证文件列表:')
for i in range(batch_size):
print(test_files[i])
base_reader = BaseReader()
# 先来看看在 PaddlePaddle 里面这个 reader 怎么用,我们以验证数据作为例子
base_test_reader = base_reader.create_test_reader(test_files)
for data in base_test_reader():
print('image-shape:', data[0].shape)
print('label:', data[1])
break
print()
base_test_reader = paddle.batch(base_test_reader, batch_size=batch_size)
for data in base_test_reader():
print('data-type:', type(data))
print('data-length:', len(data))
print('image-shape:', data[0][0].shape)
print('label:', data[0][1])
break
print()
# 使用 numpy 将列表变成批数据的方法如下:
# 使用 np.stack(列表)
# 这里先将列表中的 image 部分取出变成一个列表,然后再 stack
images = [data[i][0] for i in range(batch_size)]
images = np.stack(images).astype(np.float32)
print('images-shape:', images.shape)
print('images-type:', images.dtype)
# label 部分同理
labels = [data[i][1] for i in range(batch_size)]
labels = np.stack(labels).reshape((batch_size, 1)).astype(np.int64)
print('labels-shape:', labels.shape)
print('labels-type:', labels.dtype)
print('labels:')
print(labels)
def log_topk_info(label, topk_scores, topk_indices):
batch_size = topk_scores.shape[0]
if label is not None:
# label 大小 (batch, 1) -> (batch, ) 方便操作
label = label.flatten()
for bidx in range(batch_size):
if label is not None:
true_idx = label[bidx]
print('label: %03d, ' % true_idx, end='')
else:
print('label: ---, ', end='')
for kidx in range(5):
topk_score = topk_scores[bidx, kidx]
topk_index = topk_indices[bidx, kidx]
print('%03d(%6.2f%%) ' % (topk_index, topk_score * 100), end='')
print()
# 先来尝试一下完全使用 ImageNet 预训练的权重,效果怎样吧
test_program = fluid.Program()
test_startup = fluid.Program()
with fluid.program_guard(test_program, test_startup):
with fluid.unique_name.guard():
image = fluid.layers.data(name='image', shape=(-1, 3, 224, 224), dtype='float32')
label = fluid.layers.data(name='label', shape=(-1, 1), dtype='int64')
_,fetch_list = create_network(image, label, is_test=True)
# 大家如果没有 GPU,可以将其改为 False
# 注意: CPU 中 PaddlePaddle 并不一定实现了所有的 Operator 的训练,一般建议大家使用 GPU
use_gpu = True
place = fluid.CUDAPlace(0) if use_gpu else fluid.CPUPlace()
exe = fluid.Executor(place)
# 初始化一下 Executor
exe.run(program=test_startup)
# 载入预训练的模型参数
def _predicate(var):
# 查看 var 参数是不是在预训练模型路径内
return os.path.exists(os.path.join(pretrained_model_path, var.name))
fluid.io.load_vars(exe, pretrained_model_path, predicate=_predicate, main_program=test_program)
data = exe.run(program=test_program, fetch_list=fetch_list, feed={'image': images, 'label': labels})
# 把数据从 data 中取出来 (data 是一个列表,顺序与 fetch_list 相同)
image, label = data[0:2]
out, confidence, top5_scores, top5_indices = data[2:6]
loss, acc_top1, acc_top5 = data[6:]
display_batch(image)
print('ImageNet 预训练模型情况: loss=%06.3f top-1=%05.2f%% top-5=%05.2f%%' % (
loss, acc_top1 * 100, acc_top5 * 100))
log_topk_info(None, top5_scores, top5_indices)
# 之后要重新创建模型进行针对 Natural Images 的再训练,故这里的 Program 和 Executor 都不再需要了
exe.close()
最后一个模块是运行时报错的,错误是
TypeError Traceback (most recent call last)
<ipython-input-14-5bb32700a75c> in <module>
8 image = fluid.layers.data(name='image', shape=(-1, 3, 224, 224), dtype='float32')
9 label = fluid.layers.data(name='label', shape=(-1, 1), dtype='int64')
---> 10 _,fetch_list = create_network(image, label, is_test=True)
11
12 # 大家如果没有 GPU,可以将其改为 False
<ipython-input-10-3a2c2fad7823> in create_network(image, label, class_dim, is_test)
9
10 model = ResNet(is_test=is_test)
---> 11 out = model.net(image, class_dim=class_dim)
12
13 confidence = fluid.layers.softmax(out)
<ipython-input-9-9f956ea050fb> in net(self, input, class_dim)
49 initializer=fluid.initializer.Uniform(-stdv, stdv), trainable=True)
50 out = fluid.layers.fc(
---> 51 input=pool, size=class_dim, act=None, is_test=self.is_test, param_attr=fc_param_attr)
52
53 return out
TypeError: fc() got an unexpected keyword argument 'is_test'
`class ResNet(): def init(self, is_test=False): self.is_test = is_test
def net(self, input, class_dim=1000):
# if layers == 50:
# depth = [3, 4, 6, 3]
# elif layers == 101:
# depth = [3, 4, 23, 3]
# elif layers == 152:
# depth = [3, 8, 36, 3]
# num_filters = [64, 128, 256, 512]
conv = self.conv_bn_layer(
input=input, num_filters=64, filter_size=7, stride=2, act='relu', trainable=False)
conv = fluid.layers.pool2d(
input=conv, pool_size=3, pool_stride=2, pool_padding=1, pool_type='max')
# 原本官方代码,这里我们针对 ResNet-50 进行展开,看起来更清晰
# for block in range(len(depth)):
# for i in range(depth[block]):
# conv = self.bottleneck_block(
# input=conv,
# num_filters=num_filters[block],
# stride=2 if i == 0 and block != 0 else 1)
conv = self.bottleneck_block(input=conv, num_filters=64, stride=1, trainable=False)
conv = self.bottleneck_block(input=conv, num_filters=64, stride=1, trainable=False)
conv = self.bottleneck_block(input=conv, num_filters=64, stride=1, trainable=False)
conv = self.bottleneck_block(input=conv, num_filters=128, stride=2, trainable=False)
conv = self.bottleneck_block(input=conv, num_filters=128, stride=1, trainable=False)
conv = self.bottleneck_block(input=conv, num_filters=128, stride=1, trainable=False)
conv = self.bottleneck_block(input=conv, num_filters=128, stride=1, trainable=False)
conv = self.bottleneck_block(input=conv, num_filters=256, stride=2, trainable=False)
for _ in range(5):
conv = self.bottleneck_block(input=conv, num_filters=256, stride=1, trainable=False)
conv = self.bottleneck_block(input=conv, num_filters=512, stride=2, trainable=False)
conv = self.bottleneck_block(input=conv, num_filters=512, stride=1, trainable=False)
conv = self.bottleneck_block(input=conv, num_filters=512, stride=1, trainable=True)
pool = fluid.layers.pool2d(input=conv, pool_size=7, pool_type='avg', global_pooling=True)
# 设置 全连接层 参数初始化,并且一定为 trainable
stdv = 1.0 / math.sqrt(pool.shape[1] * 1.0)
fc_param_attr = fluid.param_attr.ParamAttr(
initializer=fluid.initializer.Uniform(-stdv, stdv), trainable=True)
out = fluid.layers.fc(
input=pool, size=class_dim, act=None, is_test=self.is_test, param_attr=fc_param_attr)
return out`
只需要将这里的is_test删去,
out = fluid.layers.fc(
input=pool, size=class_dim, act=None, is_test=self.is_test, param_attr=fc_param_attr)
修改为
out = fluid.layers.fc(
input=pool, size=class_dim, act=None, param_attr=fc_param_attr)
@huangjun12 非常感谢您,可是在改好后,原来的moudle调通了,接下来的moudle又有了错误,您能看下什么原因吗,好像还是版本原因,不知道如何修改源码。谢谢您
# 全局默认上下文是 fluid.default_main_program() 和 fluid.default_startup_program()
# 然而,为了更好地掌控,我们选择如下方式自己创建 Program 上下文
# 生成训练部分上下文
train_program = fluid.Program()
train_startup = fluid.Program()
# 使用 program_guard() 选择 train_program 和 train_startup 作为上下文
# 这样,在 with 块中,新产生的 Operator 和 Variable 将会添加到他们之中
with fluid.program_guard(train_program, train_startup):
# fluid.unique_name.guard() 会处理使得上下文中 Operator 和 Variable 的名字不会同名冲突
with fluid.unique_name.guard():
# 注意:从数据流入 PaddlePaddle 后端开始,即从 py_reader 开始,
# 所有的 Operator 和 Variable 必须保证在同一个 Program 上下文中
# 否则的话会造成异常情况
# py_reader 部分主要是给予 python 部分数据流的数据以类型信息
# 例如,矩阵的大小,矩阵的类型等等
train_reader = fluid.layers.py_reader(
capacity=64,
shapes=[(-1, 3, 224, 224), (-1, 1)],
dtypes=('float32', 'int64'),
name='train_reader')
train_reader.decorate_paddle_reader(base_train_reader)
# read_file() 的功能和其名字有些出入,主要作用是执行参数 reader
# 在数据流中生成 Variable(s),而不是读取一个文件之类的功用
train_image, train_label = fluid.layers.read_file(train_reader)
# 使用训练模式创建网络,即添加到 train_program 中去
loss, train_fetch_list = create_network(
train_image, train_label, class_dim=len(label_names), is_test=False)
# 优化器是用于对网络求导并反向传播训练网络的
# 这里我们使用 Adam 这个优化器进行 fine-tune (再训练),大家也可以选择一些其他的优化器
# 此处学习率设定为 0.005 如果发现 loss 的输出有明显震荡或者很快发散 (变得很大或者达到 NaN)
# 请重新启动 python 内核,并将其减小
optimizer = fluid.optimizer.Adam(learning_rate=0.005)
optimizer.minimize(loss)
# 生成验证部分上下文
test_program = fluid.Program()
test_startup = fluid.Program()
with fluid.program_guard(test_program, test_startup):
with fluid.unique_name.guard():
test_reader = fluid.layers.py_reader(
capacity=64,
shapes=[(-1, 3, 224, 224), (-1, 1)],
dtypes=('float32', 'int64'),
name='test_reader')
test_reader.decorate_paddle_reader(base_test_reader)
test_image, test_label = fluid.layers.read_file(test_reader)
_, test_fetch_list = create_network(
test_image, test_label, class_dim=len(label_names), is_test=True)
# 验证部分不需要优化器
# 大家如果没有 GPU,可以将其改为 False
# 注意: CPU 中 PaddlePaddle 并不一定实现了所有的 Operator 的训练,一般建议大家使用 GPU
use_gpu = True
place = fluid.CUDAPlace(0) if use_gpu else fluid.CPUPlace()
exe = fluid.Executor(place)
# 运行两个上下文的初始化部分
exe.run(program=train_startup)
exe.run(program=test_startup)
# 载入预训练的模型参数
def _predicate(var):
# 不要载入最后一个 全连接层 (名字中含有 fc),因为 ImageNet 的最后输出是 1000 分类
# 现在 NaturalImages 这个数据集是 8 分类,导致全连接层的参数矩阵大小不一致
if 'fc' in var.name:
return False
return os.path.exists(os.path.join(pretrained_model_path, var.name))
fluid.io.load_vars(exe, pretrained_model_path, predicate=_predicate, main_program=train_program)
错误信息
2020-05-20 20:29:24,822-WARNING: paddle.fluid.layers.py_reader() may be deprecated in the near future. Please use paddle.fluid.io.DataLoader.from_generator() instead.
---------------------------------------------------------------------------
EnforceNotMet Traceback (most recent call last)
<ipython-input-16-6840936cb321> in <module>
35 # 请重新启动 python 内核,并将其减小
36 optimizer = fluid.optimizer.Adam(learning_rate=0.005)
---> 37 optimizer.minimize(loss)
38
39 # 生成验证部分上下文
<decorator-gen-187> in minimize(self, loss, startup_program, parameter_list, no_grad_set)
E:\Program Files\Anaconda3\envs\paddle_env python=3.7\lib\site-packages\paddle\fluid\dygraph\base.py in __impl__(func, *args, **kwargs)
201 def __impl__(func, *args, **kwargs):
202 with _switch_tracer_mode_guard_(is_train=False):
--> 203 return func(*args, **kwargs)
204
205 return __impl__(func)
E:\Program Files\Anaconda3\envs\paddle_env python=3.7\lib\site-packages\paddle\fluid\optimizer.py in minimize(self, loss, startup_program, parameter_list, no_grad_set)
832 startup_program=startup_program,
833 parameter_list=parameter_list,
--> 834 no_grad_set=no_grad_set)
835
836 optimize_ops = self.apply_optimize(
E:\Program Files\Anaconda3\envs\paddle_env python=3.7\lib\site-packages\paddle\fluid\optimizer.py in backward(self, loss, startup_program, parameter_list, no_grad_set, callbacks)
675 with program_guard(program, startup_program):
676 params_grads = append_backward(loss, parameter_list,
--> 677 act_no_grad_set, callbacks)
678 # Note: since we can't use all_reduce_op now,
679 # dgc_op should be the last op of one grad.
E:\Program Files\Anaconda3\envs\paddle_env python=3.7\lib\site-packages\paddle\fluid\backward.py in append_backward(loss, parameter_list, no_grad_set, callbacks, checkpoints)
1414
1415 _append_backward_vars_(target_grad_block, fwd_op_num, grad_to_var,
-> 1416 grad_info_map)
1417
1418 program.current_block_idx = current_block_idx
E:\Program Files\Anaconda3\envs\paddle_env python=3.7\lib\site-packages\paddle\fluid\backward.py in _append_backward_vars_(block, start_op_idx, grad_to_var, grad_info_map)
1114 # infer_shape and infer_type
1115 op_desc.infer_var_type(block.desc)
-> 1116 op_desc.infer_shape(block.desc)
1117
1118 for arg in op_desc.output_arg_names():
EnforceNotMet:
--------------------------------------------
C++ Call Stacks (More useful to developers):
--------------------------------------------
Windows not support stack backtrace yet.
------------------------------------------
Python Call Stacks (More useful to users):
------------------------------------------
File "E:\Program Files\Anaconda3\envs\paddle_env python=3.7\lib\site-packages\paddle\fluid\framework.py", line 2610, in append_op
attrs=kwargs.get("attrs", None))
File "E:\Program Files\Anaconda3\envs\paddle_env python=3.7\lib\site-packages\paddle\fluid\layer_helper.py", line 43, in append_op
return self.main_program.current_block().append_op(*args, **kwargs)
File "E:\Program Files\Anaconda3\envs\paddle_env python=3.7\lib\site-packages\paddle\fluid\layers\nn.py", line 4197, in batch_norm
type="batch_norm", inputs=inputs, outputs=outputs, attrs=attrs)
File "<ipython-input-9-3f57d71afcc8>", line 76, in conv_bn_layer
input=conv, act=act, is_test=self.is_test, param_attr=param_attr)
File "<ipython-input-9-3f57d71afcc8>", line 106, in bottleneck_block
trainable=trainable)
File "<ipython-input-9-3f57d71afcc8>", line 41, in net
conv = self.bottleneck_block(input=conv, num_filters=512, stride=1, trainable=False)
File "<ipython-input-10-3a2c2fad7823>", line 11, in create_network
out = model.net(image, class_dim=class_dim)
File "<ipython-input-16-6840936cb321>", line 30, in <module>
train_image, train_label, class_dim=len(label_names), is_test=False)
File "E:\Program Files\Anaconda3\envs\paddle_env python=3.7\lib\site-packages\IPython\core\interactiveshell.py", line 3331, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "E:\Program Files\Anaconda3\envs\paddle_env python=3.7\lib\site-packages\IPython\core\interactiveshell.py", line 3254, in run_ast_nodes
if (await self.run_code(code, result, async_=asy)):
File "E:\Program Files\Anaconda3\envs\paddle_env python=3.7\lib\site-packages\IPython\core\interactiveshell.py", line 3063, in run_cell_async
interactivity=interactivity, compiler=compiler, result=result)
File "E:\Program Files\Anaconda3\envs\paddle_env python=3.7\lib\site-packages\IPython\core\async_helpers.py", line 68, in _pseudo_sync_runner
coro.send(None)
File "E:\Program Files\Anaconda3\envs\paddle_env python=3.7\lib\site-packages\IPython\core\interactiveshell.py", line 2886, in _run_cell
return runner(coro)
File "E:\Program Files\Anaconda3\envs\paddle_env python=3.7\lib\site-packages\IPython\core\interactiveshell.py", line 2858, in run_cell
raw_cell, store_history, silent, shell_futures)
File "E:\Program Files\Anaconda3\envs\paddle_env python=3.7\lib\site-packages\ipykernel\zmqshell.py", line 536, in run_cell
return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
File "E:\Program Files\Anaconda3\envs\paddle_env python=3.7\lib\site-packages\ipykernel\ipkernel.py", line 300, in do_execute
res = shell.run_cell(code, store_history=store_history, silent=silent)
File "E:\Program Files\Anaconda3\envs\paddle_env python=3.7\lib\site-packages\tornado\gen.py", line 209, in wrapper
yielded = next(result)
File "E:\Program Files\Anaconda3\envs\paddle_env python=3.7\lib\site-packages\ipykernel\kernelbase.py", line 545, in execute_request
user_expressions, allow_stdin,
File "E:\Program Files\Anaconda3\envs\paddle_env python=3.7\lib\site-packages\tornado\gen.py", line 209, in wrapper
yielded = next(result)
File "E:\Program Files\Anaconda3\envs\paddle_env python=3.7\lib\site-packages\ipykernel\kernelbase.py", line 268, in dispatch_shell
yield gen.maybe_future(handler(stream, idents, msg))
File "E:\Program Files\Anaconda3\envs\paddle_env python=3.7\lib\site-packages\tornado\gen.py", line 209, in wrapper
yielded = next(result)
File "E:\Program Files\Anaconda3\envs\paddle_env python=3.7\lib\site-packages\ipykernel\kernelbase.py", line 365, in process_one
yield gen.maybe_future(dispatch(*args))
File "E:\Program Files\Anaconda3\envs\paddle_env python=3.7\lib\site-packages\tornado\gen.py", line 748, in run
yielded = self.gen.send(value)
File "E:\Program Files\Anaconda3\envs\paddle_env python=3.7\lib\site-packages\tornado\gen.py", line 787, in inner
self.run()
File "E:\Program Files\Anaconda3\envs\paddle_env python=3.7\lib\site-packages\tornado\ioloop.py", line 743, in _run_callback
ret = callback()
File "E:\Program Files\Anaconda3\envs\paddle_env python=3.7\lib\site-packages\tornado\ioloop.py", line 690, in <lambda>
lambda f: self._run_callback(functools.partial(callback, future))
File "E:\Program Files\Anaconda3\envs\paddle_env python=3.7\lib\asyncio\events.py", line 88, in _run
self._context.run(self._callback, *self._args)
File "E:\Program Files\Anaconda3\envs\paddle_env python=3.7\lib\asyncio\base_events.py", line 1786, in _run_once
handle._run()
File "E:\Program Files\Anaconda3\envs\paddle_env python=3.7\lib\asyncio\base_events.py", line 541, in run_forever
self._run_once()
File "E:\Program Files\Anaconda3\envs\paddle_env python=3.7\lib\site-packages\tornado\platform\asyncio.py", line 149, in start
self.asyncio_loop.run_forever()
File "E:\Program Files\Anaconda3\envs\paddle_env python=3.7\lib\site-packages\ipykernel\kernelapp.py", line 583, in start
self.io_loop.start()
File "E:\Program Files\Anaconda3\envs\paddle_env python=3.7\lib\site-packages\traitlets\config\application.py", line 664, in launch_instance
app.start()
File "E:\Program Files\Anaconda3\envs\paddle_env python=3.7\lib\site-packages\ipykernel_launcher.py", line 16, in <module>
app.launch_new_instance()
File "E:\Program Files\Anaconda3\envs\paddle_env python=3.7\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "E:\Program Files\Anaconda3\envs\paddle_env python=3.7\lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
----------------------
Error Message Summary:
----------------------
NotFoundError: Output(Scale@GRAD) and Output(Bias@GRAD) must be null or not be null at same time. But now, has Scale@Grad=[0], has Bias@GRAD=[1]
[Hint: Expected (has_scale_grad == has_bias_grad) == true, but received (has_scale_grad == has_bias_grad):0 != true:1.] at (D:\1.8.0\paddle\paddle\fluid\operators\batch_norm_op.cc:468)
[operator < batch_norm_grad > error]
把这三个删掉即可
![]()
把这三个删掉即可
您好,我在出错的moudle里边并没有找到您画框的参数parm_atter,也没找到def conv_bn_layer函数呀。这个参数是在class renest内的,我在resnet内修改后,他紧接下来就显示文件找不到了。请问不是上次comment代码中需要修改吗?是要修改resnet吗,修改resnet后,在下边几段代码中,分别报错如下。请您看看该怎么修改,有些凌乱了,感谢您
# 取得文件列表
train_files = list_files(files_path, mode='train')
test_files = list_files(files_path, mode='test')
np.random.shuffle(train_files)
np.random.shuffle(test_files)
# 预览一下他们 :)
print('训练文件列表:')
for i in range(batch_size):
print(train_files[i])
print('验证文件列表:')
for i in range(batch_size):
print(test_files[i])
报错
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-21-023b249c925d> in <module>
1 # 取得文件列表
----> 2 train_files = list_files(files_path, mode='train')
3 test_files = list_files(files_path, mode='test')
4
5 np.random.shuffle(train_files)
NameError: name 'list_files' is not defined
base_reader = BaseReader()
# 先来看看在 PaddlePaddle 里面这个 reader 怎么用,我们以验证数据作为例子
base_test_reader = base_reader.create_test_reader(test_files)
for data in base_test_reader():
print('image-shape:', data[0].shape)
print('label:', data[1])
break
print()
base_test_reader = paddle.batch(base_test_reader, batch_size=batch_size)
for data in base_test_reader():
print('data-type:', type(data))
print('data-length:', len(data))
print('image-shape:', data[0][0].shape)
print('label:', data[0][1])
break
print()
# 使用 numpy 将列表变成批数据的方法如下:
# 使用 np.stack(列表)
# 这里先将列表中的 image 部分取出变成一个列表,然后再 stack
images = [data[i][0] for i in range(batch_size)]
images = np.stack(images).astype(np.float32)
print('images-shape:', images.shape)
print('images-type:', images.dtype)
# label 部分同理
labels = [data[i][1] for i in range(batch_size)]
labels = np.stack(labels).reshape((batch_size, 1)).astype(np.int64)
print('labels-shape:', labels.shape)
print('labels-type:', labels.dtype)
print('labels:')
print(labels)
报错:
-
NameError Traceback (most recent call last)
<ipython-input-22-da2d0a702f98> in <module>
----> 1 base_reader = BaseReader()
2
3 # 先来看看在 PaddlePaddle 里面这个 reader 怎么用,我们以验证数据作为例子
4 base_test_reader = base_reader.create_test_reader(test_files)
5
NameError: name 'BaseReader' is not defined
# 先来尝试一下完全使用 ImageNet 预训练的权重,效果怎样吧
test_program = fluid.Program()
test_startup = fluid.Program()
with fluid.program_guard(test_program, test_startup):
with fluid.unique_name.guard():
image = fluid.layers.data(name='image', shape=(-1, 3, 224, 224), dtype='float32')
label = fluid.layers.data(name='label', shape=(-1, 1), dtype='int64')
_,fetch_list = create_network(image, label, is_test=True)
# 大家如果没有 GPU,可以将其改为 False
# 注意: CPU 中 PaddlePaddle 并不一定实现了所有的 Operator 的训练,一般建议大家使用 GPU
use_gpu = True
place = fluid.CUDAPlace(0) if use_gpu else fluid.CPUPlace()
exe = fluid.Executor(place)
# 初始化一下 Executor
exe.run(program=test_startup)
# 载入预训练的模型参数
def _predicate(var):
# 查看 var 参数是不是在预训练模型路径内
return os.path.exists(os.path.join(pretrained_model_path, var.name))
fluid.io.load_vars(exe, pretrained_model_path, predicate=_predicate, main_program=test_program)
data = exe.run(program=test_program, fetch_list=fetch_list, feed={'image': images, 'label': labels})
# 把数据从 data 中取出来 (data 是一个列表,顺序与 fetch_list 相同)
image, label = data[0:2]
out, confidence, top5_scores, top5_indices = data[2:6]
loss, acc_top1, acc_top5 = data[6:]
display_batch(image)
print('ImageNet 预训练模型情况: loss=%06.3f top-1=%05.2f%% top-5=%05.2f%%' % (
loss, acc_top1 * 100, acc_top5 * 100))
log_topk_info(None, top5_scores, top5_indices)
# 之后要重新创建模型进行针对 Natural Images 的再训练,故这里的 Program 和 Executor 都不再需要了
exe.close()
报错
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-24-5bb32700a75c> in <module>
1 # 先来尝试一下完全使用 ImageNet 预训练的权重,效果怎样吧
2
----> 3 test_program = fluid.Program()
4 test_startup = fluid.Program()
5
NameError: name 'fluid' is not defined
方便把代码和数据打包发给我吗?
方便把代码和数据打包发给我吗?
好的,但是我在您主页上并没有找到您的邮箱,方便私信我吗?我的邮箱是[email protected],十分感谢您
qq: 2399845970
已经发到您的邮箱了,您查收下,看看是什么问题。
方便把代码和数据打包发给我吗?
好的,但是我在您主页上并没有找到您的邮箱,方便私信我吗?我的邮箱是[email protected],十分感谢您
qq: 2399845970
已经发到您的邮箱了,您查收下,看看是什么问题。 您好,请问收到了吗?有什么问题吗?
方便把代码和数据打包发给我吗?
好的,但是我在您主页上并没有找到您的邮箱,方便私信我吗?我的邮箱是[email protected],十分感谢您
qq: 2399845970
已经发到您的邮箱了,您查收下,看看是什么问题。 您好,请问收到了吗?有什么问题吗?
加你qq了,私聊吧
Since you haven't replied for more than a year, we have closed this issue/pr. If the problem is not solved or there is a follow-up one, please reopen it at any time and we will continue to follow up. 由于您超过一年未回复,我们将关闭这个issue/pr。 若问题未解决或有后续问题,请随时重新打开,我们会继续跟进。