Python 函数不返回任何内容

Python 函数不返回任何内容,python,function,return,Python,Function,Return,我对Python非常陌生。我正在尝试编写一个函数来执行以下操作,并在代码的未来部分中重用该函数: (函数的作用): 查找两个列表元素之间的余弦值 将值添加到列表中并计算平均值 将平均值附加到列表中 返回方法列表 然后,我想根据上述函数返回的列表进行计算。但是,该函数(即knearest_相似度(tfidf_datamatrix))不返回任何内容。第二个函数(即threshold_function())中的打印命令不显示任何内容。有人能看一下代码并告诉我我做错了什么吗 def knearest

我对Python非常陌生。我正在尝试编写一个函数来执行以下操作,并在代码的未来部分中重用该函数: (函数的作用):

  • 查找两个列表元素之间的余弦值
  • 将值添加到列表中并计算平均值
  • 将平均值附加到列表中
  • 返回方法列表
然后,我想根据上述函数返回的列表进行计算。但是,该函数(即knearest_相似度(tfidf_datamatrix))不返回任何内容。第二个函数(即threshold_function())中的打印命令不显示任何内容。有人能看一下代码并告诉我我做错了什么吗

def knearest_similarity(tfidf_datamatrix):
    k_nearest_cosineMean = []
    for datavector in tfidf_datamatrix:
        cosineValueSet = []
        for trainingvector in tfidf_vectorizer_trainingset:
            cosineValue = cx(datavector, trainingvector)
            cosineValueSet.append(cosineValue)
        similarityMean_of_k_nearest_neighbours = np.mean(heapq.nlargest(k_nearest_neighbours, cosineValueSet))    #the cosine similarity score of top k nearest neighbours
        k_nearest_cosineMean.append(similarityMean_of_k_nearest_neighbours)        
    print k_nearest_cosineMean
    return k_nearest_cosineMean


def threshold_function():  
    mean_cosineScore_mean = np.mean(knearest_similarity(tfidf_matrix_testset))
    std_cosineScore_mean = np.std(knearest_similarity(tfidf_matrix_testset))
    threshold = mean_cosineScore_mean - (3*std_cosineScore_mean)
    print "The Mean of the mean of cosine similarity score for a normal Behaviour:", mean_cosineScore_mean #The mean will be used for finding the threshold
    print "The standard deviation of the mean of cosine similarity score:", std_cosineScore_mean  #The standstart deviation is also used to find threshold
    print "The threshold for normal behaviour should be (Mean - 3*standard deviation):", threshold
    return threshold
编辑

我尝试为要使用的函数定义两个全局变量(即tfidf_vectorizer_trainingset和tfidf_matrix_testset)

但是,threshold_function()中的打印命令如下所示:

 The Mean of the mean of cosine similarity score for a normal Behaviour: nan
The standard deviation of the mean of cosine similarity score: nan
The threshold for normal behaviour should be (Mean - 3*standard deviation): nan
EDIT2
我发现k_最近的_余弦中的第一个值是nan。删除该值后,我设法获得了有效的计算结果

I
threshold\u function()的第一行
您调用的
knearest\u相似性(tfidf\u matrix\u testset)
但是您从未定义什么是
tfidf\u matrix\u testset
。你在第二行也这样做。在第三行中,使用第二行的输出。给
tfidf\u matrix\u testset
一个值。

当你说“打印命令…不显示任何内容”时,你的字面意思是什么都没有打印,或者只是打印的内容不包含你想要的数字?如果你能提供你期望看到的东西与你实际看到的东西的详细信息,其他人会更容易帮助你。谢谢,当我把它的值作为全局变量时,threshold_函数()仍然没有给我任何东西。我得到了平均值、标准值和阈值的“nan”值。实际上你是对的。我必须给它一个价值。尽管“k_nearest_cosineman”中有一个“nan”值导致计算结果无效的问题。现在好像有用了。再次感谢。
 The Mean of the mean of cosine similarity score for a normal Behaviour: nan
The standard deviation of the mean of cosine similarity score: nan
The threshold for normal behaviour should be (Mean - 3*standard deviation): nan