Trying to compute softmax values, getting AttributeError: 'list' object has no attribute 'T'

SDG picture SDG · Feb 29, 2016 · Viewed 7.3k times · Source

First off, here is my code:

"""Softmax."""

scores = [3.0, 1.0, 0.2]

import numpy as np

def softmax(x):
    """Compute softmax values for each sets of scores in x."""
    num = np.exp(x)
    score_len = len(x)
    y = [0] * score_len
    for index in range(1,score_len):
        y[index] = (num[index])/(sum(num))
    return y

print(softmax(scores))

# Plot softmax curves
import matplotlib.pyplot as plt
x = np.arange(-2.0, 6.0, 0.1)
scores = np.vstack([x, np.ones_like(x), 0.2 * np.ones_like(x)])

plt.plot(x, softmax(scores).T, linewidth=2)
plt.show()

Now looking at this question, I can tell that T is the transpose of my list. However, I seem to be getting the error:

AttributeError: 'list' object has no attribute 'T'

I do not understand what's going on here. Is my understanding of this entire situation wrong. I'm trying to get through the Google Deep Learning course and I thought that I could Python by implementing the programs, but I could be wrong. I currently know a lot of other languages like C and Java, but new syntax always confuses me.

Answer

SDG picture SDG · Feb 29, 2016

As described in the comments, it is essential that the output of softmax(scores) be an array, as lists do not have the .T attribute. Therefore if we replace the relevant bits in the question with the code below, we can access the .T attribute again.

num = np.exp(x)
score_len = len(x)
y = np.array([0]*score_len)

It must be noted that we need to use the np.array as non numpy libraries do not usually work with ordinary python libraries.