이제 막 파이토치 공부를 시작한 대학원 생입니다.
원래 맥북으로 주로 공부를 해서 맥북으로 torch 공부를 해보고자 하는데 처음부터 막히는 부분이 있어 문의드립니다.
제 개발 환경은 아래와 같습니다.
MacBook Pro 14 with M1pro
PyTorch version == 1.13.1
python version == 3.9.13
책에서 나오는 예제를 따라서 코드를 작성했는데 오류가 있어 이렇게 문의 드립니다!
모델을 생성해서 학습을 진행하는데는 문제가 없는데 검증을 진행하면 아래 오류가 발생합니다.
혹시 해결방법이나 원인을 아시는 분 계시면 답글 부탁드립니다. 감사합니다.
모델 생성
class Model(nn.Module) :
def __init__(self, embedding_size, output_size, layers, p=0.4):
super().__init__()
self.all_embeddings = nn.ModuleList([nn.Embedding(ni,nf) for ni, nf in embedding_size])
self.embedding_dropout = nn.Dropout(p)
all_layer = []
num_cat_cols = sum((nf for ni, nf in embedding_size))
input_size = num_cat_cols
for i in layers:
all_layer.append(nn.Linear(input_size, i))
all_layer.append(nn.ReLU(inplace=True))
all_layer.append(nn.BatchNorm1d(i))
all_layer.append(nn.Dropout(p))
input_size = i
all_layer.append(nn.Linear(layers[-1], output_size))
self.layers =nn.Sequential(*all_layer)
def forward(self, x_cat) :
embeddings = []
for i, e in enumerate(self.all_embeddings) :
embeddings.append(e(x_cat[:,i]))
x = torch.cat(embeddings, 1)
x = self.embedding_dropout(x)
x = self.layers(x)
return x
모델 객체(instance) 생성
model = Model( cat_embdding_size, 4, [200, 100, 50], p=0.4)
Loss function and Optimizser 정의
loss_function = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
device 설정
if torch.cuda.is_available() : device = torch.device('cuda')
elif torch.backends.mps.is_available() : device = torch.device('mps')
else : device=torch.device('cpu')
print(f'Using {device}')
모델 학습
epochs = 500 # 반복 횟수
aggregated_losses = []
train_outputs = train_outputs.to(device=device, dtype=torch.int64)
for i in range(epochs) :
i += 1
y_pred = model(cat_train_data).to(device)
single_loss = loss_function(y_pred, train_outputs)
aggregated_losses.append(single_loss)
optimizer.zero_grad()
single_loss.backward()
optimizer.step()
print(f'epoch : {i:3} loss : {single_loss.item():10.10f}')
epoch : 500 loss : 0.5807338357
예측 실행
test_outputs = test_outputs.to(device=device, dtype=torch.int64)
cat_test_data = cat_test_data.to(device=device, dtype=torch.int64)
with torch.no_grad():
y_val = model(cat_test_data).to(device)
loss = loss_function(y_val, test_outputs).to(device)
print(f'Loss :{loss:.8f}')
print(y_val[:5])
RuntimeError Traceback (most recent call last)
9 with torch.no_grad():
---> 10 y_val = model(cat_test_data) # .to(device)
11 loss = loss_function(y_val, test_outputs) # .to(device)
13 print(f'Loss :{loss:.8f}')
RuntimeError: Placeholder storage has not been allocated on MPS device!