RuntimeError: тип ввода (torch.cuda.FloatTensor) и тип веса (torch.cuda.HalfTensor) должны быть одинаковыми.
Я только начал изучать версию YOLO v5 PyTorch, и мне удалось построить модель, поэтому я попытался реализовать приложение-флягу для прогнозирования в реальном времени с использованием этой обученной модели.
класс для модели нагрузки и прогнозирования
class Model(object):
def __init__(self, model):
self.device = torch_utils.select_device()
print(self.device)
model = torch.load(model, map_location=self.device)['model']
self.half = False and self.device.type != 'cpu'
print('half = ' + str(self.half))
if self.half:
model.half()
# model = model.to(self.device).eval()
model.cuda()
self.loaded_model = model
def predict(self, img):
global session
# img1 = torch.from_numpy(img).to(self.device)
# img = img1.reshape(1, 3, 640, 640)
img = img.half() if self.half else img.float() # uint8 to fp16/32
img /= 255.0 # 0 - 255 to 0.0 - 1.0
print(img.ndimension())
if img.ndimension() == 3:
img = img.unsqueeze(0)
print(self.loaded_model)
img = img.to(self.device)
# img = img.half()
self.preds = self.loaded_model(img, augment=False)[0]
print(self.predict())
return self.preds
Класс камеры для чтения кадров с камеры или видео
model = Model("weights/best.pt")
class Camera(object):
def __init__(self):
# self.video = cv2.VideoCapture('facial_exp.mkv')
self.video = cv2.VideoCapture(0)
def __del__(self):
self.video.release()
def get_frame(self):
_, fr = self.video.read()
loader = transforms.Compose([transforms.ToTensor()])
image = cv2.resize(fr, (640, 640), interpolation=cv2.INTER_AREA)
input_im = image.reshape(1, 640, 640, 3)
pil_im = Image.fromarray(fr)
image = loader(pil_im).float()
# image = Variable(image, requires_grad=True)
image = image.unsqueeze(0)
pred = model.predict(input_im)
pred = model.predict(image)
print(pred)
_, jpeg = cv2.imencode('.jpg', fr)
return jpeg.tobytes()
Некоторые из прокомментированных строк - это способы, которые я пробовал, но всегда ниже строки
self.preds = self.loaded_model(img, augment=False)[0]
выдает ошибку ниже
RuntimeError: Input type (torch.cuda.FloatTensor) and weight type (torch.cuda.HalfTensor) should be the same
любая идея или руководство по решению этой ошибки спасибо.
2 ответа
эта ошибка означает: тип ввода - float32, тип веса (вашей модели) - float16. например, этот код ниже выполняется: model.half() # поэтому тип веса - float16, но этот код ниже не выполняется:img = img.half() # поэтому тип ввода - float32, пожалуйста, проверьте свой код. для получения дополнительной информации о «половине» вы можете обратиться к torch.Tensor.to() и torch.nn.Module.to()
Я столкнулся с той же ошибкой, в основном я не отправлял свою модель на графический процессор, поэтому перемещение модели на устройство с графическим процессором решило ошибку:
model = model.to(device)