You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

构建协同过滤推荐系统时遇AttributeError:'function'对象无'fit'属性

协同过滤推荐系统训练报错:AttributeError: 'function' object has no attribute 'fit'

我是深度学习新手,正在用Surprise库构建协同过滤推荐系统,使用CSV数据集训练模型时遇到错误:AttributeError: 'function' object has no attribute 'fit'。

完整代码

import numpy as np 
import pandas as pd 
import matplotlib.pyplot as plt

# Import the surprise packages
from surprise import Dataset
from surprise import Reader
from surprise.prediction_algorithms.matrix_factorization import SVD as FunkSVD

# Import GridSearchCV for algorithm tuning
from surprise.model_selection import GridSearchCV

# Import train_test_split
from surprise.model_selection import train_test_split

# Read in the prepared dataframe from the user_cleanup notebook
user_df = pd.read_csv('user_clean.csv')
user_df.head()

# Merge the two dataframes on appid
df = user_df.merge(games_df,on='appid')
df = df.drop('name',1)
df.head()

# Let's take a look at one of the most prominent users in the dataset, user 24469287
df[df['user_id'] == 24469287]

# Let's find this users favorite games using the 1-5 rating scale
print(f"Shape:{df[(df['user_id'] == 24469287) & (df['rating_5'] == 5)].shape}")
display(df[(df['user_id'] == 24469287) & (df['rating_5'] == 5)])

# Prepare the dataframes for the surprise package
# Dataframe needs to contain 3 columns: user id, item id, and rating
# For the 1-10 scale
rating_10_df = df.filter(['user_id','appid','rating_10'])
rating_10_df = rating_10_df.sort_values(by=['user_id','appid'])
# And the 1-5 scale
rating_5_df = df.filter(['user_id','appid','rating_5'])
rating_5_df = rating_5_df.sort_values(by=['user_id','appid'])

# Confirm dataframe is set up properly (user, item, rating)
rating_10_df.head()

# initialize the reader with 1-10 rating scale
my_reader = Reader(rating_scale=(0,10))

# load the dataframe with the reader
md = Dataset.load_from_df(rating_10_df, my_reader)

%%time

# Set the parameter grid for optimization
param_grid = {
    # Number of latent factors. More factors could give better results, but can also lead overfitting
    'n_factors': [50, 100, 150], 
    # Number of epochs. Number of iterations the algorithm will run
    'n_epochs': [10, 20, 50],
    # Learning rate. The speed at which algorithm learns. Larger values give faster learning, but smaller values give more accurate learning.
    'lr_all': [0.005, 0.1],
    'biased': [False] }

# Set GridSearchCV with 5 fold cross-validation using the FunkSVD
GS = GridSearchCV(FunkSVD, param_grid, measures=['rmse','mae','fcp'], cv=5)
# Fit the model to the data
GS.fit(md)

问题原因及解决方法

核心原因

报错说明GS是一个函数而非GridSearchCV类的实例,无法调用fit方法,常见触发场景有三种:

  1. 导入错误:误把GridSearchCV模块当成类导入,导致实例化后得到的是函数而非类对象。
  2. 变量覆盖:代码其他部分(如之前的Jupyter单元格)定义了同名的GridSearchCV函数,覆盖了从Surprise库导入的类。
  3. Jupyter魔法命令位置错误:%%time必须放在单元格第一行,否则会导致后续代码无法正确执行,GS未被正确初始化为GridSearchCV实例。

解决步骤

  • 检查导入语句:确保导入的是GridSearchCV类,正确语句为:

    from surprise.model_selection import GridSearchCV
    

    避免写成import surprise.model_selection.grid_search as GridSearchCV这类错误形式。

  • 排查变量覆盖:检查所有代码单元格,是否存在自定义的GridSearchCV函数,如有则重命名该函数,避免与库类名冲突。

  • 调整魔法命令位置:将%%time移至对应单元格的第一行,确保后续代码正常执行:

    %%time
    # Set the parameter grid for optimization
    param_grid = {
        'n_factors': [50, 100, 150], 
        'n_epochs': [10, 20, 50],
        'lr_all': [0.005, 0.1],
        'biased': [False] 
    }
    
    GS = GridSearchCV(FunkSVD, param_grid, measures=['rmse','mae','fcp'], cv=5)
    GS.fit(md)
    
  • 重启内核重置环境:如果以上操作无效,重启Jupyter内核并重新运行所有代码,清除之前的变量残留。

内容的提问来源于stack exchange,提问作者Sombor Shuffle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 20:09:23