首页 > 解决方案 > 导入另一个模型时出现 PyTorch 错误

问题描述

我尝试导入最先进的 EfficientNet 模型(pytorch 实现):

from efficientnet_pytorch import EfficientNet

import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import matplotlib.pyplot as plt
from torchvision.transforms import transforms as T
import torchvision
import torch.optim as optim

model = EfficientNet.from_pretrained('efficientnet-b0')

我在下载模型时遇到了这一系列错误:

Downloading: "https://github.com/lukemelas/EfficientNet-PyTorch/releases/download/1.0/efficientnet-b0-355c32eb.pth" to /Users/telaust/.cache/torch/checkpoints/efficientnet-b0-355c32eb.pth
---------------------------------------------------------------------------

TimeoutError                              Traceback (most recent call last)
/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/urllib/request.py in do_open(self, http_class, req, **http_conn_args)
   1316                 h.request(req.get_method(), req.selector, req.data, headers,
-> 1317                           encode_chunked=req.has_header('Transfer-encoding'))
   1318             except OSError as err: # timeout error

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/http/client.py in request(self, method, url, body, headers, encode_chunked)
   1228         """Send a complete request to the server."""
-> 1229         self._send_request(method, url, body, headers, encode_chunked)
   1230 

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/http/client.py in _send_request(self, method, url, body, headers, encode_chunked)
   1274             body = _encode(body, 'body')
-> 1275         self.endheaders(body, encode_chunked=encode_chunked)
   1276 

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/http/client.py in endheaders(self, message_body, encode_chunked)
   1223             raise CannotSendHeader()
-> 1224         self._send_output(message_body, encode_chunked=encode_chunked)
   1225 

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/http/client.py in _send_output(self, message_body, encode_chunked)
   1015         del self._buffer[:]
-> 1016         self.send(msg)
   1017 

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/http/client.py in send(self, data)
    955             if self.auto_open:
--> 956                 self.connect()
    957             else:

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/http/client.py in connect(self)
   1383 
-> 1384             super().connect()
   1385 

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/http/client.py in connect(self)
    927         self.sock = self._create_connection(
--> 928             (self.host,self.port), self.timeout, self.source_address)
    929         self.sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socket.py in create_connection(address, timeout, source_address)
    726     if err is not None:
--> 727         raise err
    728     else:

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/socket.py in create_connection(address, timeout, source_address)
    715                 sock.bind(source_address)
--> 716             sock.connect(sa)
    717             # Break explicitly a reference cycle

TimeoutError: [Errno 60] Operation timed out

During handling of the above exception, another exception occurred:

URLError                                  Traceback (most recent call last)
<ipython-input-5-5e9bdf5b3e02> in <module>
----> 1 model = EfficientNet.from_pretrained('efficientnet-b0')

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/efficientnet_pytorch/model.py in from_pretrained(cls, model_name, advprop, num_classes, in_channels)
    209     def from_pretrained(cls, model_name, advprop=False, num_classes=1000, in_channels=3):
    210         model = cls.from_name(model_name, override_params={'num_classes': num_classes})
--> 211         load_pretrained_weights(model, model_name, load_fc=(num_classes == 1000), advprop=advprop)
    212         if in_channels != 3:
    213             Conv2d = get_same_padding_conv2d(image_size = model._global_params.image_size)

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/efficientnet_pytorch/utils.py in load_pretrained_weights(model, model_name, load_fc, advprop)
    325     # AutoAugment or Advprop (different preprocessing)
    326     url_map_ = url_map_advprop if advprop else url_map
--> 327     state_dict = model_zoo.load_url(url_map_[model_name])
    328     if load_fc:
    329         model.load_state_dict(state_dict)

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/torch/hub.py in load_state_dict_from_url(url, model_dir, map_location, progress, check_hash)
    490         sys.stderr.write('Downloading: "{}" to {}\n'.format(url, cached_file))
    491         hash_prefix = HASH_REGEX.search(filename).group(1) if check_hash else None
--> 492         download_url_to_file(url, cached_file, hash_prefix, progress=progress)
    493 
    494     # Note: extractall() defaults to overwrite file if exists. No need to clean up beforehand.

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-packages/torch/hub.py in download_url_to_file(url, dst, hash_prefix, progress)
    389     # We use a different API for python2 since urllib(2) doesn't recognize the CA
    390     # certificates in older Python
--> 391     u = urlopen(url)
    392     meta = u.info()
    393     if hasattr(meta, 'getheaders'):

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/urllib/request.py in urlopen(url, data, timeout, cafile, capath, cadefault, context)
    220     else:
    221         opener = _opener
--> 222     return opener.open(url, data, timeout)
    223 
    224 def install_opener(opener):

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/urllib/request.py in open(self, fullurl, data, timeout)
    523             req = meth(req)
    524 
--> 525         response = self._open(req, data)
    526 
    527         # post-process response

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/urllib/request.py in _open(self, req, data)
    541         protocol = req.type
    542         result = self._call_chain(self.handle_open, protocol, protocol +
--> 543                                   '_open', req)
    544         if result:
    545             return result

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/urllib/request.py in _call_chain(self, chain, kind, meth_name, *args)
    501         for handler in handlers:
    502             func = getattr(handler, meth_name)
--> 503             result = func(*args)
    504             if result is not None:
    505                 return result

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/urllib/request.py in https_open(self, req)
   1358         def https_open(self, req):
   1359             return self.do_open(http.client.HTTPSConnection, req,
-> 1360                 context=self._context, check_hostname=self._check_hostname)
   1361 
   1362         https_request = AbstractHTTPHandler.do_request_

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/urllib/request.py in do_open(self, http_class, req, **http_conn_args)
   1317                           encode_chunked=req.has_header('Transfer-encoding'))
   1318             except OSError as err: # timeout error
-> 1319                 raise URLError(err)
   1320             r = h.getresponse()
   1321         except:

URLError: <urlopen error [Errno 60] Operation timed out>

我对这个错误感到很困惑,所以我看到这个问题与 URL 有关,但我无法解决它。在此之前我通过 pip 安装了这个模型:

pip3 install efficientnet_pytorch

我该如何解决这个错误?先感谢您

标签: pythonmachine-learningdeep-learningcomputer-visionpytorch

解决方案


推荐阅读