user2311700
user2311700

Reputation: 17

python naive bayes classifier error

I'm trying to build a naive bayes classifier which read data from a text file and outputs to a text file and my code is gettin an error sayin the the return is outside of the function however i can see no error

# compute the relative frequencies of the
# 2nd explanatory variable taking on the
# values 'A', 'B' and 'C'
# and return a dictionary with these values
def getCatProbs(self, data):
  a_count = 0
  b_count = 0
  c_count = 0
  probs = {}
for row in data:
  if row[1] == ">50K":
     a_count = a_count + 1
  if row[1] == "<=50K":
     b_count = b_count + 1
  else:
     c_count = c_count + 1

     probs[">50K"] = float(a_count)/len(data)
     probs["<=50K"] = float(b_count)/len(data)
     probs['C'] = float(c_count)/len(data)

  return probs

Upvotes: 0

Views: 291

Answers (3)

Andrei
Andrei

Reputation: 56716

In python, indentation matters. For example in your code definition of function getCatProbs is finished after line probs = {}, which clearly leaves the return outside the funciton body.

Here is how this code might look like with proper indents:

# compute the relative frequencies of the
# 2nd explanatory variable taking on the
# values 'A', 'B' and 'C'
# and return a dictionary with these values
def getCatProbs(self, data):
    a_count = 0
    b_count = 0
    c_count = 0
    probs = {}
    for row in data:
        if row[1] == ">50K":
            a_count = a_count + 1
        if row[1] == "<=50K":
            b_count = b_count + 1
        else:
            c_count = c_count + 1

    probs[">50K"] = float(a_count)/len(data)
    probs["<=50K"] = float(b_count)/len(data)
    probs['C'] = float(c_count)/len(data)

    return probs

Upvotes: 2

duffymo
duffymo

Reputation: 308998

Format is meaningful in Python.

It looks to me like you're not consistent in your indentation. The for loop and subsequent lines appear to be off.

I'd recommend using a good IDE. JetBrains makes the best ones on the market. Try PyCharm. It'll make it more difficult to make such mistakes.

Upvotes: 0

BrenBarn
BrenBarn

Reputation: 251558

Your return is indeed outside of your function. The entire for loop is outside of your function. I think you meant to indent the for loop one more level so it's inside the function.

Upvotes: 1

Related Questions