Home > OS >  Why did it happen "AttributeError: 'matrix' object has no attribute 'todense
Why did it happen "AttributeError: 'matrix' object has no attribute 'todense

Time:12-07

I want to run the alexnet CNN architecture with a tutorial example but I want to do epoch there is an error AttributeError: 'matrix' object has no attribute 'todense'

cost_history=[]
n_epochs =5
# the execution
sess = tf.compat.v1.Session()
sess.run(init)

train_y = train_y.todense()


for i in range(n_epochs):
    a, c = sess.run([optimizer, cost], feed_dict={x: train_x, y: train_y})  #working
    cost_history = np.append(cost_history,c)  # working
    print('epoch : ', i,  ' - ', 'cost: ', c) #working 

with an error message :

AttributeError                            Traceback (most recent call last)
<ipython-input-103-4749625f3914> in <module>
      5 sess.run(init)
      6 
----> 7 train_y = train_y.todense()
      8 
      9 

AttributeError: 'matrix' object has no attribute 'toarray'

I'm looking for a problem but until now I can't, please help and why it can happen

CodePudding user response:

Remove the line train_y = train_y.todense() from your code. This line is causing the error. Convert the train_y to a Numpy array - you can use it as current implemented (instead of a matrix).

Code with the changed line:

cost_history=[]
n_epochs =5
# the execution
sess = tf.compat.v1.Session()
sess.run(init)

train_y = train_y.toarray()

for i in range(n_epochs):
    a, c = sess.run([optimizer, cost], feed_dict={x: train_x, y: train_y})  #working
    cost_history = np.append(cost_history,c)  # working
    print('epoch : ', i,  ' - ', 'cost: ', c) #working
  • Related