Reputation: 29
for my master degree, I'm trying to create a simple neuronal network. But there are some errors in my code, so the programm stops and doesn't create a trained model.
I couldn't figure out what the error message wants to tell me and what I need to change in my code. Hence I need your help. I googled the error, but neither understood, nor could I solve my error in any way with the proposed ideas of other posts.
Can anyone explain me why tensorflow wants to create a graph and how it is possible that the framework doesn't know the needed function for it? Do I just have to install a package for the visualisation? Is it Possible to ignore this error?
I don't need any graphics. But does the computer need it for the classification and calculation with a ml-algorithm?
Please excuse my poor English and my unawareness of Tensorflow either.
Thanks in advance!
I've installed the newest tensorflow version 2.0.0-beta1, as well as the latest keras version.
Moreover, I've tried to create some graphs to show the classification process. Doesn't work.
I also activated the step-by-step debugging mode to find out my problem. It seems the error appears inside the evaluate_model function in which I create, train and evaluate a neuronal network.
The error occurs during the model creation process (model = Sequantial()).
# -*- 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 keras.utils import to_categorical
from keras.models import Sequential
from keras.layers import Dense
from keras.utils import normalize
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, Output = 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.append([items[1], items[2], items[3], items[4], items[5], items[6], items[7], items[8], items[9]]) # Input: all characteristics
Output.append(items[10]) # Output: scenario_class 1 to 8
# change to numpy_array (scalar index array)
Input = array(Input)
Output = array(Output)
# normalize Data
Input = normalize(Input)
# 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, Output):
# select samples
Train, Target_Train = Input[train_ix], Output[train_ix]
Test, Target_Test = Input[test_ix], Output[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')
This Traceback is shown in Spyder:
Traceback (most recent call last):
File "<ipython-input-12-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 786, 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 77, 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 24, in evaluate_model
model = Sequential()
File "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\sequential.py", line 87, in __init__
super(Sequential, self).__init__(name=name)
File "C:\ProgramData\Anaconda3\lib\site-packages\keras\legacy\interfaces.py", line 91, in wrapper
return func(*args, **kwargs)
File "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\network.py", line 96, in __init__
self._init_subclassed_network(**kwargs)
File "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\network.py", line 294, in _init_subclassed_network
self._base_init(name=name)
File "C:\ProgramData\Anaconda3\lib\site-packages\keras\engine\network.py", line 109, in _base_init
name = prefix + '_' + str(K.get_uid(prefix))
File "C:\ProgramData\Anaconda3\lib\site-packages\keras\backend\tensorflow_backend.py", line 74, in get_uid
graph = tf.get_default_graph()
AttributeError: module 'tensorflow' has no attribute 'get_default_graph'
Upvotes: 2
Views: 3551
Reputation: 306
Change the imported module.Hope this method can solve your mistake.
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
from tensorflow.keras.utils import normalize
Upvotes: 1
Reputation: 2682
If you are using tf 2.0 beta make sure that all your keras imports are tensorflow.keras...
any keras imports will pickup the standard keras package that assumes tensorflow 1.4.
i.e. use:
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, ...
Upvotes: 3