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

股票预测机器学习模型运行输出含警告问题求助

解决股票预测模型的两类警告问题

你的代码里的两个警告都是因为直接把多维数组/单元素Series转成标量的方式已经被弃用,以下是具体原因和修复方案:

警告原因分析

  1. DeprecationWarning:model.predict()返回的是一维数组(哪怕只有一个预测值),直接用float()转换这种数组会触发警告,这种转换方式已不再被推荐。
  2. FutureWarning:today_data["High"]是单元素的pandas Series,直接调用float()转换它会在未来版本的pandas中抛出TypeError,官方已弃用该用法。

修复后的完整代码

import yfinance as yf
from sklearn.linear_model import LinearRegression

start_date = "2000-01-01"
end_date = None
model = LinearRegression()
tickers = ("AMZN","AAPL","TSLA")

for stock_symbol in tickers:
    stock_data = yf.download(tickers=stock_symbol, start=start_date, end=end_date, interval="1d")
    model.fit(stock_data[['Open', 'Low', 'Close', 'Volume']], stock_data['High'])

    today_data = yf.download(stock_symbol, period="1d", interval="1d")
    today_features = today_data[['Open', 'Low', 'Close', 'Volume']]
    predicted_high_tomorrow = model.predict(today_features)

    # 修复警告:用.item()获取数组/Series的标量值,替代直接float()转换
    predicted_scalar = predicted_high_tomorrow.item()
    today_high_scalar = today_data["High"].item()

    if predicted_scalar > today_high_scalar:
        status = "BUY"
    else:
        status = "SELL"

    print(f"{stock_symbol}  {today_high_scalar}    {predicted_scalar}   {status}")

关键修改点

  • 对于模型预测的数组predicted_high_tomorrow,用.item()提取唯一标量值,这是numpy数组获取单元素的推荐方式。
  • 对于单元素Seriestoday_data["High"],同样用.item()获取标量值,这也是pandas官方推荐的安全写法,避免了版本兼容性问题。

补充:你也可以用predicted_high_tomorrow[0]和today_data["High"].iloc[0]实现同样效果,但.item()会确保数据是单元素,否则抛出ValueError,安全性更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 23:34:54