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

PyCharm中sklearn的linear出现未解析引用问题求助

问题原因及解决方案

你遇到的问题是变量名称使用错误:

  • 你通过model = linear_model.LinearRegression()创建了线性回归模型的实例,这个实例的名称是model
  • 但后续调用系数、截距和预测方法时,错误地使用了未定义的linear变量,这才导致PyCharm提示“unresolved reference 'linear'”

修正后的代码如下:

import sklearn
from sklearn.utils import shuffle
from sklearn import linear_model
import pandas as pd
import numpy as np

# 假设这里你已经正确初始化了df和prediction变量
df = df[[...]]

x = np.array(df.drop([prediction], 1))
y = np.array(df[prediction])

x_train, x_test, y_train, y_test = sklearn.model_selection.train_test_split(x, y, test_size=0.1)
model = linear_model.LinearRegression()
model.fit(x_train, y_train)
accuracy = model.score(x_test, y_test)
print(accuracy)

# 将所有linear替换为model
print("Coefficient: \n", model.coef_)
print("Intercept: \n", model.intercept_)
predictions = model.predict(x_test)

补充说明:

  • linear_model是你导入的sklearn子模块,LinearRegression()是该模块下的类
  • 只有当你实例化类得到对象(也就是这里的model)后,才能通过对象调用类的实例属性(coef_、intercept_)和实例方法(predict())
  • 你之前混淆了模块名、类名和实例对象名,才出现了未定义引用的错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 09:25:29