Я сейчас пишу магистерскую диссертацию и мне нужна помощь, чтобы найти ошибку.
Сначала короткое объяснение моего кода:
- Данные для моей нейронной сети создаются в базе данных и загружаются в проект через массив data_storage.
- В проекте я разделяю последний столбец (целевой класс) и нормализую все значения. Это создает массивы input_data и output_data.
- Из-за небольшого объема данных я использую перекрестную проверку и разделяю оба массива в одинаковом соотношении на данные обучения и испытаний.
- Каждый шаг перекрестной проверки открывает метод, при котором новая нейронная сеть создается и обучается несколько раз. Каждый раз, когда функция получает новые отсортированные данные. Нейронная сеть и результат оценки затем возвращаются в основную часть программы. Там они добавляются в список.
- Когда перекрестная проверка завершена, отдельные результаты проходов (= каждый экземпляр списка) усредняются.
- Код на данный момент не закончен.
В моей нейронной сети должно быть 9 классов, подобных сценариям, которые я обозначил в базе данных. Но есть проблема с формой, которая впервые появляется в процессе подгонки.
Мой код:
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 3 16:26:14 2019
@author: mattdoe
"""
from data_preprocessor_db import data_storage # validation data
from sklearn.model_selection import StratifiedKFold
from sklearn.metrics import confusion_matrix
from tensorflow.keras.utils import to_categorical, normalize
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from numpy import mean
from numpy import std
from numpy import array
# create and evaluate a single multi-layer-perzeptron
def evaluate_model(Train, Test, Target_Train, Target_Test):
# define model
model = Sequential()
# input layer automatically created
model.add(Dense(9, input_dim=9, kernel_initializer='normal', activation='relu')) # 1st hidden layer
model.add(Dense(9, kernel_initializer='normal', activation='relu')) # 2nd hidden layer
model.add(Dense(9, activation='softmax')) #output layer
# create model
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
# fit model
model.fit(Train, to_categorical(Target_Train), epochs=50, verbose=0)
# evaluate the model
test_loss, test_acc = model.evaluate(Test, to_categorical(Target_Test), verbose=0)
# as well: create a confussion matrix
predicted = model.predict(Test)
conf_mat = confusion_matrix(Target_Test, predicted)
return model, test_acc, conf_mat
# for seperation of data_storage
# Link_ID = []
Input_data, Output_data = list(), list()
# list all results of k-fold cross-validation
scores, members, matrix = list(), list(), list()
# seperate data_storage in Input and Output data
for items in data_storage:
# Link_ID = items[0] # identifier not needed
Input_data.append([items[1], items[2], items[3], items[4], items[5], items[6], items[7], items[8], items[9]]) # Input: all characteristics
Output_data.append(items[10]) # Output: scenario_class 1 to 8
# change to numpy_array (scalar index array)
Input_data = array(Input_data)
Output_data = array(Output_data)
# normalize Data
Input_data = normalize(Input_data)
# Output = normalize(Output) not needed; categorical number
# prepare k-fold cross-validation
kfold = StratifiedKFold(n_splits=15, random_state=1, shuffle=True)
for train_ix, test_ix in kfold.split(Input_data, Output_data):
# select samples
Train, Target_Train = Input_data[train_ix], Output_data[train_ix]
Test, Target_Test = Input_data[test_ix], Output_data[test_ix]
# evaluate model
model, test_acc, conf_mat = evaluate_model(Train, Test, Target_Train, Target_Test)
# display each evalution result
print('>%.3f' % test_acc)
# add result to list
scores.append(test_acc)
members.append(model)
matrix.append(conf_mat)
# summarize expected performance
print('Estimated Accuracy %.3f (%.3f)' % (mean(scores), std(scores)))
# as well in confursion_matrix
print ('Confussion Matrix %' %(mean(matrix)))
# save model // trained neuronal network
model.save('neuronal_network_1.h5')
Моя ошибка:
Traceback (most recent call last):
File "<ipython-input-13-25afb095a816>", line 1, in <module>
runfile('C:/Workspace/Master-Thesis/Programm/MapValidationML/ml_neuronal_network_1.py', wdir='C:/Workspace/Master-Thesis/Programm/MapValidationML')
File "C:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 827, in runfile
execfile(filename, namespace)
File "C:\ProgramData\Anaconda3\lib\site-packages\spyder_kernels\customize\spydercustomize.py", line 110, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Workspace/Master-Thesis/Programm/MapValidationML/ml_neuronal_network_1.py", line 76, in <module>
model, test_acc, conf_mat = evaluate_model(Train, Test, Target_Train, Target_Test)
File "C:/Workspace/Master-Thesis/Programm/MapValidationML/ml_neuronal_network_1.py", line 33, in evaluate_model
model.fit(Train, to_categorical(Target_Train), epochs=50, verbose=0)
File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\keras\engine\training.py", line 643, in fit
use_multiprocessing=use_multiprocessing)
File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\keras\engine\training_arrays.py", line 632, in fit
shuffle=shuffle)
File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\keras\engine\training.py", line 2469, in _standardize_user_data
y, self._feed_loss_fns, feed_output_shapes)
File "C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\keras\engine\training_utils.py", line 685, in check_loss_and_target_compatibility
' while using as loss `' + loss_name + '`. '
ValueError: A target array with shape (847, 10) was passed for an output of shape (None, 9) while using as loss `categorical_crossentropy`. This loss expects targets to have the same shape as the output.