我目前正在写硕士论文,需要一些帮助以查找错误。
首先,简要说明一下我的代码:
我的神经网络应该有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.
答案 0 :(得分:0)
@Shubman Panchal:是的,您是对的,但我不明白为什么我的目标数组有10个标签。
所以在我的数据库中以这种方式存储了一些记录(可能是800条):
id|info1|info2|info3|info4|info5|info6|info7|info8|info9|class
--------------------------------------------------------------
1|0.2|0.7|4|2|6|8|1|7.2|8|1
2|0.7|0.4|5|3|5|4|2|3|6.4|5
.........
800|0|0|1|1|1|1|1|1|1|7
这些记录的标记从1到9。
在我的程序中,我将所有记录加载到列表变量data_storage中。 然后,我将这个变量/每条记录拆分为Input_data(info1 ... info9)和Output_data(class)中的内容,顺便删除ID。
Input_data和Output_data都是开头的项目列表。
因此,存储了800个元组。 G。对于ID = 1:(0.2,0.7,4,2,6,8,1,7.2,8)
作为列表Input_data中的一项,(1)
作为列表Output_data中的一项。
之后,我将类型从列表更改为数组,并期望每个列表项现在都是一行。我将检查此数组的格式...
最后,数组的值被标准化。
有人有主意吗?