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

PyCharm中scikit-learn的predict()、coef_、score未解析属性引用问题求助

解决PyCharm中scikit-learn模型属性未解析警告问题

问题原因

PyCharm的静态代码分析工具无法自动推断出拟合后的scikit-learn模型实例具备predict()、coef_、score这些属性,因此抛出未解析属性引用的警告。若错误地修改代码(比如添加不合适的类型注解),会导致model = model.fit(X_train, y_train)出现语法或类型错误。

解决方法

方法1:优化模型拟合代码(推荐)

scikit-learn的fit()方法会对模型实例进行原地修改并返回自身,无需重新赋值给变量。调整代码后,PyCharm的类型推断能更准确识别模型属性:

model = LinearRegression()
# 直接调用fit,无需重新赋值
model.fit(X_train, y_train)

方法2:添加明确的类型注解

如果需要保留赋值写法,通过类型注解明确模型类型,帮助PyCharm识别属性:

from sklearn.linear_model import LinearRegression

# 方式1:一步初始化并拟合
model: LinearRegression = LinearRegression().fit(X_train, y_train)

# 方式2:分两步添加注解
model = LinearRegression()
model.fit(X_train, y_train)
model: LinearRegression  # 明确类型

方法3:临时禁用特定警告(不推荐)

若仅需临时消除警告,可在对应代码行上方添加PyCharm的专用注释:

# noinspection PyUnresolvedReferences
predicted = model.predict(X_test)

# noinspection PyUnresolvedReferences
pd.DataFrame(zip(X.columns, np.transpose(model.coef_)))

# noinspection PyUnresolvedReferences
print(model.score(X_test, y_test))

额外建议:回归模型用于分类任务的问题

你的代码中用LinearRegression处理二分类任务(y取值为1/-1),这并不合适,建议替换为LogisticRegression,更符合分类场景的需求:

# 替换模型初始化部分
model = LogisticRegression()
model.fit(X_train, y_train)

修改后的完整代码

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import pandas_datareader.data as pdr
import talib as ta
import yfinance as yf
from sklearn import metrics
from sklearn.linear_model import LinearRegression, LogisticRegression
from sklearn.model_selection import cross_val_score

yf.pdr_override()
df = pdr.get_data_yahoo('^NSEI', '2010-01-01')
df = df.dropna()
df = df.iloc[:, :4]
df.head()

df['S_10'] = df['Close'].rolling(window=10).mean()
df['Corr'] = df['Close'].rolling(window=10).corr(df['S_10'])
df['RSI'] = ta.RSI(np.array(df['Close']), timeperiod=20)
df['MACD'] = ta.MOM(np.array(df['Close']), timeperiod=26)
df['Open-Close'] = df['Open'] - df['Close'].shift(1)
df['Open-Open'] = df['Open'] - df['Open'].shift(1)
df = df.dropna()
X = df.iloc[:, :9]

y = np.where(df['Close'].shift(-1) > df['Close'], 1, -1)

split = int(0.7 * len(df))
X_train, X_test, y_train, y_test = X[:split], X[split:], y[:split], y[split:]

# 优化模型拟合代码,消除类型推断问题
model = LinearRegression()
model.fit(X_train, y_train)

pd.DataFrame(zip(X.columns, np.transpose(model.coef_)))

predicted = model.predict(X_test)
print(predicted)

print(metrics.confusion_matrix(y_test, predicted))
print(metrics.classification_report(y_test, predicted))

print(model.score(X_test, y_test))

cross_val = cross_val_score(LinearRegression(), X, y, scoring='accuracy', cv=10)
print(cross_val)
print(cross_val.mean())

df['Predicted_Signal'] = model.predict(X)
df['Nifty_returns'] = np.log(df['Close'] / df['Close'].shift(1))
Cumulative_Nifty_returns = np.cumsum(df[split:]['Nifty_returns'])

df['Startegy_returns'] = df['Nifty_returns'] * df['Predicted_Signal'].shift(1)
Cumulative_Strategy_returns = np.cumsum(df[split:]['Startegy_returns'])

plt.figure(figsize=(10, 5))
plt.plot(Cumulative_Nifty_returns, color='r', label='Nifty Returns')
plt.plot(Cumulative_Strategy_returns, color='g', label='Strategy Returns')
plt.legend()
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 08:57:20