如何创建以无标签dummy data为输入的Caffe网络?解决字节类型报错
Got it, let's break down and fix this error you're seeing when trying to set up a CaffeNet with dummy data for fine-tuning.
The Root Cause
This is a classic Python 3 string/bytes mismatch issue. In Python 3, files opened in binary mode (the default for tempfile.NamedTemporaryFile) only accept bytes-like objects—but your code is trying to write a plain string (from str(n.to_proto())) into it. That's exactly why you're getting the TypeError: a bytes-like object is required, not 'str' message.
Two Simple Fixes
Pick either of these solutions to get your code working:
Option 1: Encode the string to bytes before writing
Modify the line where you write to the temp file to convert the string to UTF-8 bytes:
with tempfile.NamedTemporaryFile(delete=False) as f: # Encode the proto string to bytes before writing f.write(str(n.to_proto()).encode('utf-8'))
Option 2: Open the temp file in text mode explicitly
Tell NamedTemporaryFile to use text mode (mode='w') so you can write strings directly:
# Open in text mode instead of default binary mode with tempfile.NamedTemporaryFile(mode='w', delete=False) as f: f.write(str(n.to_proto()))
Why This Happens
By default, tempfile.NamedTemporaryFile uses the 'w+b' mode in Python 3—this is a binary read/write mode that expects bytes, not strings. The n.to_proto() method generates a protocol buffer object, which when converted to a string is a regular str type, hence the mismatch.
After Fixing
Once you update that line in your caffenet function, your original code should run smoothly:
dummy_data = L.DummyData(shape=dict(dim=[1, 3, 227, 227])) imagenet_net_filename = caffenet(data=dummy_data, train=False) imagenet_net = caffe.Net(imagenet_net_filename, weights, caffe.TEST)
From there, you can set custom input images by updating imagenet_net.blobs['data'].data as needed for your fine-tuning workflow.
内容的提问来源于stack exchange,提问作者Christian Frick

