python - python 函数不返回任何内容

标签 python function return

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

  • 求两个列表元素之间的余弦值
  • 将值添加到列表中并计算平均值
  • 将平均值附加到列表
  • 返回手段列表

然后我想根据上述函数返回的列表进行计算。但是,该函数(即 knearest_similarity(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)。

#fitting tfidf transfrom for training data
tfidf_vectorizer_trainingset = tfidf_vectorizer.fit_transform(readfile(trainingdataDir)).toarray()

#tfidf transform the test set based on the training set
tfidf_matrix_testset = tfidf_vectorizer.transform(readfile(testingdataDir)).toarray().

但是 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

编辑2 我发现 k_nearest_cosineMean 中的第一个值是 nan。删除该值后,我设法获得有效的计算。

最佳答案

threshold_function()的第一行中,您调用knearest_similarity(tfidf_matrix_testset),但是您从未定义tfidf_matrix_testset是什么。您也在第二行中执行此操作。在第三行中,您使用第二行的输出。给 tfidf_matrix_testset 一个值。

关于python - python 函数不返回任何内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33360148/

相关文章:

python - Selenium Webdriver 在子元素中查找元素

r - 函数返回 Rmarkdown 图中并排打印的多个绘图,而不是一个在另一个之上

c# - 为什么在使用 Environment.Exit() 时需要返回,而不是抛出的异常?

wpf - 在密码框中捕获返回键的最佳方法是什么? (WPF/XAML)

javascript - 使用 JSON 解析/解析 js 对象时,返回方法中的函数范围会丢失

php - 仅当 count 为 0 时返回 false

python - 多维Newton Raphson的同时优化/时间复杂度

Python 'If not' 语法

python - 使用 Python C API 时检查返回值有多重要?

c - 返回多维数组的函数