0

テキストファイルからデータを読み取ってテキストファイルに出力する単純なベイズ分類器を構築しようとしていますが、戻り値が関数の外にあるというエラーがコードに表示されますが、エラーは表示されません

# 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
4

3 に答える 3

2

Python では、インデントが重要です。たとえば、関数のコード定義では、関数本体の外側を明確に残すgetCatProbs行の後に終了します。probs = {}return

適切なインデントを使用すると、このコードは次のようになります。

# 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
于 2013-04-25T19:59:01.777 に答える
1

あなたのリターンは確かにあなたの機能の外にあります。forループ全体が関数の外にあります。forループをもう1レベルインデントして、関数内に入れるつもりだったと思います。

于 2013-04-25T19:55:30.293 に答える
0

フォーマットは Python では意味があります。

インデントに一貫性がないように見えます。for ループ以降の行がオフになっているように見えます。

優れた IDE を使用することをお勧めします。JetBrains は、市場で最高のものを製造しています。PyCharmを試してください。そのような間違いを犯しにくくなります。

于 2013-04-25T19:55:46.107 に答える