gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 23:05:06 24 4
gpt4 key购买 nike

我对 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com