alright let's start over again and see the code we train model ok. This is the code we train our model:
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchvision.datasets as datasets
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
import numpy as np

# Define the transform to normalize the pixel values
transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))])

# Download the dataset and apply the transform
trainset = datasets.MNIST(root='./data', train=True, download=True, transform=transform)
testset = datasets.MNIST(root='./data', train=False, download=True, transform=transform)

# Create data loaders to load the data in batches
batch\_size = 64
trainloader = torch.utils.data.DataLoader(trainset, batch\_size=batch\_size, shuffle=True)
testloader = torch.utils.data.DataLoader(testset, batch\_size=batch\_size, shuffle=False)

# Define the neural network architecture
class Net(nn.Module):
 def \_\_init\_\_(self):
 super(Net, self).\_\_init\_\_()
 self.fc1 = nn.Linear(784, 128)
 self.fc2 = nn.Linear(128, 64)
 self.fc3 = nn.Linear(64, 10)

 def forward(self, x):
 x = x.view(-1, 784) # Flatten the input tensor
 x = F.relu(self.fc1(x))
 x = F.relu(self.fc2(x))
 x = self.fc3(x)
 return F.log\_softmax(x, dim=1)

model = Net()

# Define the loss function and optimizer
criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)

# Train the neural network

num\_epochs = 15
for epoch in range(num\_epochs):
 running\_loss = 0.0
 for i, (inputs, labels) in enumerate(trainloader):
 optimizer.zero\_grad()
 outputs = model(inputs)
 loss = criterion(outputs, labels)
 loss.backward()
 optimizer.step()

 running\_loss += loss.item()
 if i % 100 == 99: # Print every 100 mini-batches
 print('Epoch {}/{}, Iteration {}, Loss: {:.4f}'.format(epoch+1, num\_epochs, i+1, running\_loss/100))
 running\_loss = 0.0

 # Evaluate the model on the test set
 correct = 0
 total = 0
 with torch.no\_grad():
 for inputs, labels in testloader:
 outputs = model(inputs)
 \_, predicted = torch.max(outputs.data, 1)
 total += labels.size(0)
 correct += (predicted == labels).sum().item()

 accuracy = correct / total
 print('Epoch {}/{}, Test accuracy: {:.4f}'.format(epoch+1, num\_epochs, accuracy))

def view\_classify(img, ps):
 ''' Function for viewing an image and it's predicted classes.
 '''
 ps = ps.data.numpy().squeeze()

 fig, (ax1, ax2) = plt.subplots(figsize=(6,9), ncols=2)
 ax1.imshow(img.resize\_(1, 28, 28).numpy().squeeze())
 ax1.axis('off')
 ax2.barh(np.arange(10), ps)
 ax2.set\_aspect(0.1)
 ax2.set\_yticks(np.arange(10))
 ax2.set\_yticklabels(np.arange(10))
 ax2.set\_title('Class Probability')
 ax2.set\_xlim(0, 1.1)
 plt.tight\_layout()
valset = datasets.MNIST('PATH\_TO\_STORE\_TESTSET', download=True, train=False, transform=transform)
valloader = torch.utils.data.DataLoader(valset, batch\_size=64, shuffle=True)
images, labels = next(iter(valloader))

img = images[0].view(1, 784)
with torch.no\_grad():
 logps = model(img)

ps = torch.exp(logps)
probab = list(ps.numpy()[0])
print("Predicted Digit =", probab.index(max(probab)))
view\_classify(img.view(1, 28, 28), ps)

correct\_count, all\_count = 0, 0
for images,labels in valloader:
 for i in range(len(labels)):
 img = images[i].view(1, 784)
 # Turn off gradients to speed up this part
 with torch.no\_grad():
 logps = model(img)

 # Output of the network are log-probabilities, need to take exponential for probabilities
 ps = torch.exp(logps)
 probab = list(ps.numpy()[0])
 pred\_label = probab.index(max(probab))
 true\_label = labels.numpy()[i]
 if(true\_label == pred\_label):
 correct\_count += 1
 all\_count += 1

print("Number Of Images Tested =", all\_count)
print("\nModel Accuracy =", (correct\_count/all\_count))
 
# Save the model
torch.save(model.state\_dict(), 'my\_model.pth')

# Download the saved model file
from google.colab import files
files.download('my\_model.pth')
now let's load the model in the flask app and write the predict server to predict the image we request
다시 시작해서 모델을 훈련하는 코드를 확인해 보겠습니다. 다음은 모델을 훈련하는 코드입니다:import torchimport torch.nn as nnimport torch.nn.functional as Fimport torch.optim as optimtorchvision.datasets를 datasets로 가져옵니다.torchvision.transforms를 transforms로 가져옵니다.matplotlib.pyplot을 plt로 가져옵니다.numpy를 np로 가져옵니다.# 픽셀 값을 정규화하기 위해 트랜스폼을 정의합니다.transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.5,), (0.5,))])# 데이터셋을 다운로드하고 트랜스폼을 적용합니다.trainset = datasets.MNIST(root='./data', train=True, download=True, transform=transform)testset = datasets.MNIST(root='./data', train=False, download=True, transform=transform)# 데이터를 일괄적으로 로드하기 위한 데이터 로더 생성batch\_size = 64trainloader = torch.utils.data.DataLoader(trainset, batch\_size=batch\_size, shuffle=True)testloader = torch.utils.data.DataLoader(testset, batch\_size=batch\_size, shuffle=False)# 신경망 아키텍처 정의class Net(nn.Module): def \_\_init\_\_(self): super(Net, self).\_\_init\_\_() self.fc1 = nn.Linear(784, 128) self.fc2 = nn.Linear(128, 64) self.fc3 = nn.Linear(64, 10) def forward(self, x): x = x.view(-1, 784) # 입력 텐서 평활화 x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) 반환 F.log\_softmax(x, dim=1)model = Net()# 손실 함수 및 최적화 함수 정의criterion = nn.CrossEntropyLoss()optimizer = optim.SGD(model.parameters(), lr=0.01, momentum=0.5)# 신경망 훈련num\_epochs = 15범위(num\_epochs)의 epoch에 대해: running\_loss = 0.0 for i, (입력, 레이블) in enumerate(trainloader): optimizer.zero\_grad() 출력 = 모델(입력) loss = criterion(outputs, labels) loss.backward() optimizer.step() running\_loss += loss.item() if i % 100 == 99: # 100개의 미니 배치마다 인쇄 print('Epoch {}/{}, Iteration {}, Loss: {:.4f}'.format(epoch+1, num\_epochs, i+1, running\_loss/100)) running\_loss = 0.0 # 테스트 세트에서 모델 평가 correct = 0 total = 0 with torch.no\_grad(): 입력의 경우, 테스트 로더의 레이블: 출력 = 모델(입력) \_, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted == labels).sum().item() 정확도 = 정확도 / 합계 print('에포크 {}/{}, 테스트 정확도: {:.4f}'.format(epoch+1, num\_epochs, accuracy))def view\_classify(img, ps): ''' 이미지와 예측된 클래스를 보기 위한 함수입니다. ''' ps = ps.data.numpy().squeeze() fig, (ax1, ax2) = plt.subplots(figsize=(6,9), ncols=2) ax1.imshow(img.resize\_(1, 28, 28).numpy().squeeze()) ax1.axis('off') ax2.barh(np.array(10), ps) ax2.set\_aspect(0.1) ax2.set\_yticks(np.arange(10)) ax2.set\_틱라벨(np.arange(10)) ax2.set\_title('클래스 확률') ax2.set\_xlim(0, 1.1) plt.tight\_layout()valset = datasets.MNIST('PATH\_TO\_STORE\_TESTSET', download=True, train=False, transform=transform)valloader = torch.utils.data.DataLoader(valset, batch\_size=64, shuffle=True)이미지, 레이블 = next(iter(valloader))img = images[0].view(1, 784)torch.no\_grad(): logps = 모델(img)ps = torch.exp(logps)probab = list(ps.numpy()[0])print("예상 숫자 =", probab.index(max(probab)))view\_classify(img.view(1, 28, 28), ps)correct\_count, all\_count = 0, 0이미지의 경우, 발로더의 레이블: for i in range(len(labels)): img = images[i].view(1, 784) # 이 부분의 속도를 높이려면 그라디언트를 끄세요. 이 부분의 속도를 높이려면 그라디언트를 끕니다: logps = model(img) # 네트워크의 출력은 로그 확률이며, 확률에 지수를 사용해야 합니다. ps = torch.exp(logps) probab = list(ps.numpy()[0]) pred\_label = probab.index(max(probab)) true\_label = labels.numpy()[i] if(true\_label == pred\_label): correct\_count += 1 all\_count += 1print("테스트한 이미지 수 =", all\_count)print("\n모델 정확도 =", (correct\_count/all\_count)) # 모델 저장torch.save(model.state\_dict(), 'my\_model.pth')# 저장된 모델 파일 다운로드구글 콜랩에서 파일 가져오기files.download('my\_model.pth')이제 플라스크 앱에서 모델을 로드하고 우리가 요청한 이미지를 예측하기 위해 예측 서버를 작성해 보겠습니다.