【问题标题】:local variable 'index_three' referenced before assignment error while developing a recommendation engine using Python使用 Python 开发推荐引擎时,在分配错误之前引用了局部变量“index_three”
【发布时间】:2017-06-23 05:38:48
【问题描述】:

我正在开发一个推荐引擎来向本地零售连锁店推荐商品,我正在使用我在开发电影推荐系统时学到的代码,该系统使用电影镜头数据集和用于推荐电影的代码现在这里好像不行。

获取三级项目之间相关性的函数

def get_movie_similarity(level3Id):  
    index_three = list(index_three).index(level3Id)
    return corr_matrixthree[index_three]

一种功能,通过根据用户的 pearson coreation 分数以升序排列与用户购买的商品相似的商品,获取与用户购买最多的商品相似的商品

    def get_movie_recommendations(merged):  
    movie_similarities = np.zeros(corr_matrixthree.shape[0])
    for level3Id in merged:
        movie_similarities = movie_similarities + get_movie_similarity(level3Id)
    similarities_df = pd.DataFrame({'level3Id': index_three,'sum_similarity': movie_similarities})
    similarities_df = similarities_df[~(similarities_df.level3Id.isin(merged))]
    similarities_df = similarities_df.sort_values(by=['sum_similarity'], ascending=False)
    return similarities_df`

我生成的相似度矩阵是用户和他们购买的商品之间的相似度矩阵,其值是您在每件商品上花费的金额。

sample_user = 42140122376
merged[merged.cust_id==sample_user].sort_values(by=['amount_extended'], ascending=False)


sample_user_movies = merged[merged.cust_id==sample_user].level3Id.tolist()  
recommendations = get_movie_recommendations(sample_user_movies)

#We get the top 20 recommended movies
recommendations.level3Id.head(20)

我得到的错误是:

local variable 'index_three' referenced before assignment

Index_three 是数据集中所有项目的索引 而 corr_matrix 3 是使用 pearson 分数生成的项目之间的相似性矩阵。 合并是我的数据集

你能帮帮我吗?

我可以分享我在 jupyter notebook 中的代码!

【问题讨论】:

  • index_three 应该是什么?是清单吗??你能解释一下吗?

标签: python recommendation-engine


【解决方案1】:

为此,您需要了解变量作用域的工作原理。看看这个!

def my_func():
    index3 =5000
    print(index3)

index3=10;
print(index3)
my_func()

输出:

10
5000

注意:即使有两个index3,您也可能认为它们是相同的。但他们不是

my_func 中的index3 是一个局部变量。而您程序中的那个(不在函数中的那个)index3 是不同的!所以在上面的代码中发生的事情是首先print(index3)在我的代码中打印index3(不是在任何函数中......只是在我的程序中)然后my_func()被调用并且my_func()中的print(index3)打印局部变量 index3

看看这个!

def my_func():
    print(index3)

index3=10;
print(index3)
my_func()

输出:

10
10

现在看到两次index310 相同,这意味着它会打印两次全局变量。

现在你的问题来了!:

def my_func():
    index3 =index3+1

index3=10;
print(index3)
my_func()

输出:

10
Traceback (most recent call last):
  File "/home/mr/func.py", line 6, in <module>
    my_func()
  File "/home/mr/func.py", line 2, in my_func
    index3 =index3+1
UnboundLocalError: local variable 'index3' referenced before assignment

为什么?

由于这个index3 =index3+1,所以当它看到index3= 时,它会创建一个局部变量。所以index3=0的意思是把0赋给局部变量。

但是index3 =index3+1 会混淆它!它认为

等待我将 局部变量 index3 分配为 局部变量 index3+1 吗?但是你还没声明呢!

def my_func():
    global index3
    index3 =index3+1
    print(index3)

index3=10
print(index3)
my_func()
print(index3)

输出:

10
11
11

现在它采用函数中的 global 值并发生变化。所以 index3 被函数改变了。

注意:使用全局变量是不好的编码习惯。

def getIndex3():
    return index3

def my_func():
    index3 = getIndex3()
    index3 =index3+1
    print(index3)

index3=10
print(index3)
my_func()
print(index3)

现在输出:

10
11
10

你明白其中的不同吗?这就是您的程序显示该错误的原因。就是这个意思local variable 'index_three' referenced before assignment

【讨论】:

    【解决方案2】:

    在您定义的每个函数中,您都在使用 index_three 变量。

    在函数get_movie_similarity 中,你使用的是like -

    index_three = list(index_three).index(level3Id)
    

    为了使上述语句起作用,index_tree 应该有一些价值。 因此,如果可以的话,至少通过 index_three 来运行或使其成为全球性的。

    我上面解释的例子:

    def get_str():
    """Give me new string with appending given string with word new"""
        val =  val + "_new"
        return val
    
    print get_str()
    

    当我执行上面的程序时,我会得到如下错误:

    C:\Users\dinesh\Desktop>python multi.py
    Traceback (most recent call last):
      File "multi.py", line 358, in <module>
        get_str()
      File "multi.py", line 355, in get_str
        val =  val + "_new"
    UnboundLocalError: local variable 'val' referenced before assignment
    

    和你得到的一样。我解决了上述错误如下:

    def get_str(val):
        val =  val + "_new"
        return val
    
    print get_str("Dinesh")
    
    C:\Users\dinesh\Desktop>python multi.py
    Dinesh_new
    

    注意:不建议将变量设为全局变量。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-18
      • 2018-07-16
      • 2016-04-07
      相关资源
      最近更新 更多