PyTorch 코드 작성 문제 및 해결 방안

질문
오류 알림:no module named xxx
xxx 사용자 정의 폴 더 이름
검색 할 수 없 기 때문에 현재 경 로 를 가방 의 검색 디 렉 터 리 에 추가 합 니 다.
해결 방법:

import sys
sys.path.append('..') #             
sys.path.append('/home/xxx') #     
import os
sys.path.append(os.getcwd()) #  #               
현재 터미널 의 명령 줄 에 도 설정 할 수 있 습 니 다.

export PYTHONPATH=$PYTHONPATH:./
오류 알림:AttributeError:'NoneType'객 체 는 속성'shape'높이,너비,채널=img.shape 가 없습니다.
Linux 시스템 에서 img.shape 가 AttributeError:'None Type'object has no attribute'shape'를 잘못 보 고 했 습 니 다.
img=cv2.imread(),그림 을 읽 을 때 img.shape 는 세 개의 양 을 포함 하 는 원 그룹 입 니 다.각각:
img.shape[0]:그림 높이
img.shape[1]:그림 의 너비
img.shape[2]:그림 의 채널 수
해결 방법:읽 은 파일 이 잘못 되 었 거나 파일 경로 가 올 바른 지 확인 합 니 다.
오류 알림:TypeError:슬라이스 인덱스 는 정수 또는 없 음 이거 나 인덱스 메 서 드 가 있어 야 합 니 다.
cropped_im = img[ny1 : ny2, nx1 : nx2, :]
해결 방법:ny1:ny2,nx1:nx2 를 int 형식 으로 변환 해 야 합 니 다.
오류 알림:입력 유형(torch.cuda.Double Tensor)과 weight type(torch.cuda.FloatTensor)은 동일 해 야 합 니 다.
다음 세 소절 은 Data type CPU tensor GPU tensor 입 니 다.
32-bit floating point torch.FloatTensor torch.cuda.FloatTensor
64-bit floating point torch.DoubleTensor torch.cuda.DoubleTensor
오류 유형 변환
np.float 를 np.float 32 로 변경

import torchvision.transforms as transforms
import numpy as np
transform = transforms.ToTensor()
def convert_image_to_tensor(image):
    """convert an image to pytorch tensor
        image: numpy array , h * w * c
        image_tensor: pytorch.FloatTensor, c * h * w
        """
    image = image.astype(np.float32) 
    return transform(image)
오류 알림:런 타임 오류:0 차원 텐서(위치 0)를 연결 할 수 없습니다.
버 전 문제

import torch
x = torch.tensor(0.1)
y = torch.tensor(0.2)
z = torch.cat((x, y))
신식 서법 으로 바꾸다

x = torch.tensor([0.1])
y = torch.tensor([0.2])
z = torch.cat((x, y))
print(z)
결실
tensor([0.1000, 0.2000])
오류 알림:TypeError:'float'object is not subscriptable
더 많아 졌 습 니 다.다음 표 시 는 a=x.tolist()[0]
아래 표 시 된 a=x.tolist()제거
오류 알림:인자'input'(position 1)은 목록 이 아 닌 Tensor 여야 합 니 다.
list 를 tensor 로 변환 해 야 합 니 다.
a 가 list 라 고 가정 해 봐.

torch.tensor(a)
GPU 모델 과 CPU 모델 간 의 전환
원래 저 장 된 것 이 GPU 모델 이 라 고 가정 하면 CPU 모델 로 변환 해 야 합 니 다.

torch.save(model, os.path.join( "./complete.pth"))
cpu_model = torch.load("./complete.pth", map_location=lambda storage, loc: storage)
dummy_input = torch.randn(1, 3, 224, 224)
원래 저 장 된 것 이 CPU 모델 이 라 고 가정 하면 GPU 모델 로 변환 해 야 합 니 다.

device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
torch.save(model, os.path.join( "./complete.pth"))
gpu_model = torch.load("./complete.pth", map_location=lambda storage, loc: storage.cuda)
dummy_input = torch.randn(1, 3, 224, 224)
dummy_input = dummy_input.to(device)
오류 알림 RuntimeError:Subtraction,the-operator,with a bool tensor is not supported.마스크 를 뒤 집 으 려 면~또는 logical 을 사용 하 십시오.not() operator instead.
원 코드

# Store only unsuppressed boxes for this class
image_boxes.append(class_decoded_locs[1 - suppress])
image_labels.append(torch.LongTensor((1 - suppress).sum().item() * [c]).to(device))
image_scores.append(class_scores[1 - suppress])
다음으로 변경

image_boxes.append(class_decoded_locs[~suppress])
image_labels.append(torch.LongTensor((~ suppress).sum().item() * [c]).to(device))
image_scores.append(class_scores[~suppress])
오류 알림 RuntimeError:scalar type Byte 의 예상 객체 이지 만 argument\#2'other'에 대한 scalar type Bool 이 있 습 니 다.th_max
원 코드

suppress = torch.zeros((n_above_min_score), dtype=torch.uint8).to(device) 
다음으로 변경

suppress = torch.zeros((n_above_min_score), dtype=torch.bool).to(device)  
UserWarning: volatile was removed and now has no effect. Use with torch.no_grad(): instead.

#     
...
x = Variable(torch.randn(1), volatile=True)
return x

#  
with torch.no_grad():
    ...
    x = torch.randn(1)
return x
오류 알림
RuntimeError: Attempting to deserialize object on CUDA device 1 but torch.cuda.device_count() is 1. Please use torch.load with map_location to map your storages to an existing device.
또는 Runtime Error:expected device cuda:0 but got device cuda:1
오류 원인 중 하나
CUDA 1 그래 픽 카드 트 레이 닝 으로 저 장 된 모형 파일 을 사 용 했 으 며,CUDA 0 검증 을 사용 했다.
코드 에 적 혀 있어 요.

device = torch.device(“cuda” if torch.cuda.is_available() else “cpu”)
명령 행 에 어떤 GPU 를 볼 수 있 는 지 설정 할 수 있 습 니 다.

export CUDA_VISIBLE_DEVICES=1 #GPU  
export CUDA_VISIBLE_DEVICES=0,1,2,3#4     
코드 에서 도 바 꿀 수 있어 요.

checkpoint = torch.load(checkpoint,map_location=‘cuda:0')
오류 알림
raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPConnectionPool(host='localhost', port=8097): Max retries exceeded with url: /update (Caused by NewConnectionError(': Failed to establish a new connection: [Errno 111] Connection refused',))
Exception in user code:
해결 방안
visdom 시각 화 프로그램 을 시작 하지 않 았 기 때문에 모든 오류 가 발생 했 습 니 다.
터미널 에서 명령 을 실행 하면 다음 과 같은 정 보 를 볼 수 있 습 니 다.

Checking for scripts.
It's Alive!
INFO:root:Application Started
You can navigate to http://localhost:8097
N.Module.cuda()와 Tensor.cuda()
모델 이 든 데이터 든 cuda()는 CPU 에서 GPU 로 의 메모리 이전 을 실현 할 수 있 지만 이들 의 역할 효 과 는 다르다.
Model:

model = model.cuda()
model.cuda()
위의 두 문장 은 같은 효 과 를 거 둘 수 있다.즉,model 자체 에 대한 메모리 이전 이다.
Tensor:

model = Model()
tensor = torch.zeros([2, 3, 10, 10])
model.cuda()
tensor.cuda()
tensor_cuda = tensor.cuda()
model(tensor) #    
model(tensor_cuda) #     
N.Module 과 달리 tensor.cuda 를 호출 하면 이 tensor 대상 이 GPU 메모리 에 있 는 복사 본 을 되 돌려 줄 뿐 자신 을 바 꾸 지 않 습 니 다.따라서 tensor 를 다시 할당 해 야 합 니 다.즉,tensor=tensor.cuda()
PyTorch 0.4 계산 누적 손실의 차이
광범 위 하 게 사용 되 는 모드 로 totalloss+=loss.data[0]를 예 로 들 면.Python 0.4.0 이전에 loss 는(1,)장 량 의 Variable 을 봉 인 했 지만 Python 0.4.0 의 loss 는 현재 0 차원 의 스칼라 입 니 다.스칼라 에 대한 색인 은 의미 가 없습니다.loss.item()을 사용 하면 스칼라 에서 Python 숫자 를 가 져 올 수 있 습 니 다.그래서

total_loss = total_loss + loss.item()
누적 손실 시 Python 숫자 로 변환 하지 않 으 면 프로그램 메모리 사용량 이 증가 할 수 있 습 니 다.이것 은 위 표현 식 의 오른쪽 은 원래 Python 부동 소수점 이 었 으 나,지금 은 0 차원 장 량 이기 때 문 입 니 다.따라서 총 손실 은 장 량 과 그들의 경사도 역 사 를 누적 시 켰 기 때문에 이것 은 매우 큰 autograd 그림 을 만들어 메모리 와 계산 자원 을 소모 할 수 있다.
CPU 와 GPU 장치 에 적응 하 는 trick

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = Model().to(device)

total_loss = 0
for input, target in train_loader:
 input, target = input.to(device), target.to(device)
 ...
 total_loss = total_loss + loss.item()

with torch.no_grad():
 for input, target in test_loader:
 ...
torch.Tensor.detach 사용
공식 설명:현재 그래프 에서 분 리 된 새로운 Tensor 를 반환 합 니 다.
만약 에 모델 A 와 모델 B 가 있다 고 가정 하면 우 리 는 A 의 출력 을 B 의 입력 으로 해 야 한다.그러나 훈련 할 때 우 리 는 모델 B 만 훈련 하면 이렇게 할 수 있다.

input_B = output_A.detach
그것 은 두 개의 계산 그림 의 경사도 전달 을 끊 어 우리 가 필요 로 하 는 기능 을 실현 할 수 있다.
pytorch 에서 loss 함수 의 매개 변수 설정
CrossEntropy Loss 를 예 로 들 면:
CrossEntropyLoss(self, weight=None, size_average=None, ignore_index=-100, reduce=None, reduction='elementwise_mean')
reduce=false,그러면 sizeaverage 매개 변수 가 효력 을 잃 고 벡터 형식의 loss,즉 batch 의 모든 요소 에 대응 하 는 loss 를 직접 되 돌려 줍 니 다.
reduce=True 라면 loss 는 스칼라 를 되 돌려 줍 니 다.
하면,만약,만약...average=true,loss.mean 을 되 돌려 줍 니 다.
하면,만약,만약...average=false,loss.sum 을 되 돌려 줍 니 다.
weight:1D 의 가중치 벡터 를 입력 하여 각 유형의 loss 가중 권 을 입력 하 십시오.다음 공식 과 같 습 니 다.
在这里插入图片描述
ignore_index:무시 할 목표 값 을 선택 하여 입력 경사도 에 기여 하지 않 습 니 다.하면,만약,만약...average=True,무시 되 지 않 는 목표 의 loss 평균 값 만 계산 합 니 다.
reduction:선택 할 수 있 는 매개 변 수 는'none'|'elementwisemean'|'sum'은 매개 변수의 글자 뜻 과 같다.
다 중 GPU 처리 메커니즘
다 중 GPU 를 사용 할 때 PyTorch 의 처리 논 리 는 다음 과 같다 는 것 을 기억 해 야 합 니 다.
각 GPU 에서 모델 을 초기 화 합 니 다.
전방 향 전파 시,batch 를 각 GPU 에 분배 하여 계산 합 니 다.
받 은 출력 은 메 인 GPU 에서 집계 되 고 loss 를 계산 하 며 역방향 으로 전파 되 며 메 인 GPU 의 가중치 를 업데이트 합 니 다.
메 인 GPU 의 모형 을 다른 GPU 에 복사 하 다.
훈련 시 손실
훈련 모델 시 nan 손실 발생
경사도 에 nan 이 나타 날 수 있 는 세 가지 원인:
경사도 폭발.즉,경사도 수치 가 범 위 를 넘 어 nan 으로 변 하 는 것 이다.보통 초등학교 습 률 을 조절 하거나 BN 층 을 추가 하거나 경사도 재단 을 해서 해결 되 었 는 지 시험 해 볼 수 있다.
손실 함수 나 네트워크 디자인.예 를 들 어 0 을 제외 하거나 일부 경계 상황 이 발생 하여 함수 가 유도 할 수 없 게 되 었 습 니 다.예 를 들 어 log(0),sqrt(0).
더러 운 데이터.입력 데이터 가 존재 하 는 지 미리 판단 할 수 있 습 니 다.
nan 데이터 의 판단 방법 을 보충 합 니 다.
주의!nan 이나 inf 와 같은 수 치 는==또는 is 로 판단 할 수 없습니다!안전 을 위해 math.isnan 이나 numpy.isnan 을 통일 적 으로 사용 하 세 요.

import numpy as np
if np.any(np.isnan(input.cpu().numpy())):
 print("Input data has NaN!")
if(np.isnan(loss.item())):
 print("Loss value is NaN!")
pytorch 메모리 누 출
torch.as_tensor(data,dtype=None,device=None)->Tensor:data 를 위해 tensor 를 생 성 합 니 다.
data 가 tensor 이 고 dtype 과 device 가 매개 변수 와 같 으 면 생 성 된 tensor 는 data 와 메모 리 를 공유 합 니 다.data 가 ndarray 이 고 dtype 이 대응 하 며 devices 가 cpu 라면 메모 리 를 공유 합 니 다.다른 경우 에는 메모 리 를 공유 하지 않 습 니 다.

import torch
import numpy
a = numpy.array([1, 2, 3])
t = torch.as_tensor(a)
이상 은 개인 적 인 경험 이 므 로 여러분 에 게 참고 가 되 기 를 바 랍 니 다.여러분 들 도 저 희 를 많이 응원 해 주시 기 바 랍 니 다.

좋은 웹페이지 즐겨찾기