Получение предвзятого прогноза для моей CNN
В настоящее время я создаю модель CNN, которая может брать набор данных, тренироваться на нем и при тестировании производить высокую скорость классификации. Он работает с набором данных MNIST из pytorch.torchvision, но когда я использую свой собственный набор данных, прогноз обучения очень близок к целевому классу, но прогноз тестирования всегда является одним целевым классом, что означает низкий уровень классификации. Я действительно новичок в этом, и мне нужна помощь, пожалуйста.
Ниже мой учебный и тестовый класс:
Тренировка Def
# Forward Pass
Outputs = cnnModel(Input)
# print ('T: ' + str(Target))
Loss = criterion(Outputs, Target)
lossList.append(Loss.item())
# Backward & Optimise
optimiser.zero_grad()
Loss.backward()
optimiser.step()
#Track Accuracy
totalResult += Target.size(0)
_, predictedResult = torch.max(Outputs.data, 1)
corretResult += (predictedResult == Target).sum().item()
wrongResult += (predictedResult != Target).sum().item()
actualList.append(corretResult / totalResult)
targetList.append(str(Target))
predList.append(str(predictedResult))
targetCounter = Counter(targetList)
predCounter = Counter(predList)
print ('TL COUNT' + str(targetCounter))
print ('PL COUNT' + str(predCounter))
print ('Average Training Accuracy Loss on this Epoch: ' + str(nP.array(actualList).mean()))
print('Accuracy of the Covnet Neural Network model on the Test Images: {} %'.format(100 * corretResult / totalResult))
Тестирование Def
Input = Input.to(deviceConfiguration)
Target = Target.to(deviceConfiguration)
Outputs = cnnModel(Input)
temp, predictedResult = torch.max(Outputs.data, 1)
print(temp)
print(predictedResult)
print("\n")
totalResult += Target.size(0)
corretResult += (predictedResult == Target).sum().item()
wrongResult += (predictedResult != Target).sum().item()
targetList.append(str(Target))
predList.append(str(predictedResult))
targetCounter = Counter(targetList)
predCounter = Counter(predList)
#cont = input('Continue? ')
for key, value in targetCounter.items():
print('Target Class & Occurance: ' + key, value)
print("\n")
for key, value in predCounter.items():
print('Pred Class & Occurance: ' + key, value)
print("\n")
print('Accuracy of the Covnet Neural Network model on the Test Images: {} %'.format(100 * corretResult / totalResult))
print('Misclassification Rate of the Dataset Images : {} %'.format(100 * wrongResult / totalResult))
Мой CNN для вывода
def forward(self, x):
out = self.layer1(x)
out = self.layer2(out)
out = self.layer3(out)
out = out.reshape(out.size(0), -1)
out = self.fc1(out)
#print ('O: ' + str(out.size()))
return out
Мой CSV Reader
def __getitem__(self, index):
singleImageLabel = self.dataLabels[index]
# print ('Path: ' + str(singleImageLabel))
# Create an Empty Numpy Array to Fill
imageAsNumpy = nP.ones((32, 32), dtype = 'uint8')
# Fill the Numpy Array with Data from Pandas DF
for i in range(1):
rowPosition = (i-1) // self.imageHeight
columnPosition = (i-1) % self.imageWidth
indexFirst = self.dataFromCSV.iloc[index][i].split(";")[3]
indexLast = self.dataFromCSV.iloc[index][i].split(";")[6]
imageAsNumpy[rowPosition][columnPosition] = indexFirst + indexLast
imageAsImage = Image.fromarray(imageAsNumpy)
imageAsImage = imageAsImage.convert('RGB')
# Transform Image to Tensor
if self.transform is not None:
imageAsTensor = self.transform(imageAsImage)
# Transform Label to Tensor
labelAsLabel = int(singleImageLabel.split(";")[7])
labelAsTensor = torch.from_numpy(nP.array(labelAsLabel))
# print ('Target: ' + str(labelAsTensor))
# Return Image & the Label
return (imageAsTensor, labelAsLabel)
def __len__(self):
return len(self.dataFromCSV.index)
И это вывод - в терминале
Accuracy of the Covnet Neural Network model on the Test Images: 0.0 %
Misclassification Rate of the Dataset Images : 100.0 %
Rajans-MBP:CNN_Model_GTSRB rajanbindra$ python ./CNN_Model.py
TL COUNTCounter({'tensor([ 26])': 2, 'tensor([ 24])': 1, 'tensor([ 8])': 1, 'tensor([ 9])': 1, 'tensor([ 12])': 1, 'tensor([ 25])': 1, 'tensor([ 2])': 1, 'tensor([ 29])': 1, 'tensor([ 38])': 1})
PL COUNTCounter({'tensor([ 24])': 6, 'tensor([ 26])': 3, 'tensor([ 3])': 1})
Average Training Accuracy Loss on this Epoch: 0.0
Accuracy of the Covnet Neural Network model on the Test Images: 0.0 %
Misclassification Rate of the Dataset Images : 100.0 %
Continue?
Target Class & Occurance: tensor([ 10]) 1
Target Class & Occurance: tensor([ 35]) 1
Target Class & Occurance: tensor([ 28]) 1
Target Class & Occurance: tensor([ 5]) 1
Target Class & Occurance: tensor([ 12]) 1
Target Class & Occurance: tensor([ 2]) 2
Target Class & Occurance: tensor([ 3]) 1
Target Class & Occurance: tensor([ 1]) 1
Target Class & Occurance: tensor([ 17]) 1
Pred Class & Occurance: tensor([ 26]) 10
Accuracy of the Covnet Neural Network model on the Test Images: 0.0 %
Misclassification Rate of the Dataset Images : 100.0 %