出现错误user_matrix_num没有被定义
def evaluate_recommendations(test_set, user_matrix_num, user_pearson_num, user_prediction, k=10):
TP = 0 # True Positives
FP = 0 # False Positives
FN = 0 # False Negatives
for user_id in test_set.index:
# Generate recommendations
recommendations = recommend_movies(user_id, user_matrix_num, user_pearson_num, user_prediction, k)
# Get actual liked movies from test set
actual_liked_movies = test_set.loc[user_id][test_set.loc[user_id] > 0].index.tolist()
for movie_id in recommendations:
if movie_id in actual_liked_movies:
TP += 1
else:
FP += 1
for movie_id in actual_liked_movies:
if movie_id not in recommendations:
FN += 1
precision = TP / (TP + FP)
recall = TP / (TP + FN)
f1_score = 2 * (precision * recall) / (precision + recall)
return precision, recall, f1_score
def recommend_movies(user_id, user_matrix_num, user_pearson_num, user_prediction, k=10):
a = user_prediction[:, user_id]
max_indexs = heapq.nlargest(k, range(len(a)), a.take)
return max_indexs
def main():
# Your existing code here...
# Splitting data into training and testing sets (80% train, 20% test)
train_set = df1.sample(frac=0.8, random_state=42)
test_set = df1.drop(train_set.index)
# Preprocessing...
# Training the model...
# Generate recommendations and evaluate
precision, recall, f1_score = evaluate_recommendations(test_set, user_matrix_num, user_pearson_num, user_prediction)
print("Precision:", precision)
print("Recall:", recall)
print("F1 Score:", f1_score)
if __name__ == "__main__":
main()