NameError:名称“ XXX”未定义

时间:2020-05-13 10:16:08

标签: python-3.x function nameerror

我有一个函数def viterbi()。输入变量之一是sequence。稍后在函数中,我将调用sequence。但是,这样做会返回:

NameError: name 'sequence' is not defined

这是我的功能:

def viterbi(sequence, p_start=None, p_trans=None, p_stop=None, p_emiss=None):


length = len(sequence)
num_states = len(p_start)
best_path = []

# trellis to store Viterbi scores
trellis = np.full([length, num_states], -np.inf)

# backpointers to backtrack
backpointers = -np.ones([length, num_states], dtype=int)

trellis[0] = p_start + p_emiss[obs2i[sequence[0].obs]] # log(viterbi(1,ck))

# Fill the remaining columns with transition probabilities
for i in range(1, length):
  matrix_product = p_trans + trellis[i - 1]
  backpointers[i] = [max_index(el) for el in matrix_product]
  max_over_c_l = [max(el) for el in matrix_product]
  trellis[i] = max_over_c_l + p_emiss[obs2i[sequence[i].obs]]

# Compute the maximum probability with end probabilities
ending_probabilities = p_stop + trellis[-1]
final_backpointer = max_index(ending_probabilities)
best_score = max(ending_probabilities)

# Compute the best path by backtracking
for seq in range(0,length):
    best_path.append(backpointers[seq][max_index(trellis[seq])])
best_path.append(final_backpointer)

return (best_score, best_path)

我看过类似的问题,但是似乎没有一个像我这样处理相同的问题:

Here,该函数中没有输入变量。

Here,在函数中创建的变量在函数外部被调用。

Here,根本就没有定义变量。

让我感到困惑的是变量sequence是该函数的输入。因此,我希望函数知道sequence是什么。另外,当我在函数内初始化变量length时,它不会返回错误。

谁能告诉我这是怎么回事?我该怎么解决这个问题?

0 个答案:

没有答案