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

使用simulated_bifurcation优化时遇RuntimeError:期望Double却得Float

解决PyTorch张量类型不匹配错误(RuntimeError: expected scalar type Double but found Float)

问题代码

import yfinance as yf
import torch
import random # linear algebra
import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)
import yfinance as yf
import matplotlib.pyplot as plt


import json
import numpy as np
#from deap import base, creator, tools, algorithms

from datetime import datetime as dt, timedelta as td
#from datetime import datetime
import simulated_bifurcation as sb


asset_name = 'AAPL'

import numpy as np

def generate_weights(data):
    # Get the number of columns in the data
    num_cols = data.shape[1]

    # Generate random weights between 0 and 1
    weights = np.random.rand(num_cols, num_cols)

    # Normalize the weights
    normalized_weights = weights / np.sum(weights)

    return normalized_weights


data = yf.download(tickers=asset_name, period='1y', interval='1d')
data
m_sb = (torch.DoubleTensor(generate_weights(data)))
m_sb = m.double()  # 此处存在变量未定义的笔误
m_sb 
sb.set_env(time_step=.1, pressure_slope=.01, heat_coefficient=.06)
best_vector, best_value = sb.maximize(m_sb, #domain='int10',
                                      agents=100, device='cuda',
                                      max_steps=10000, sampling_period=30, ballistic= True,
                                      convergence_threshold=50, use_window=True, heated=True, best_only=True)

报错信息

🔁 Iterations       :   0%|          | 0/10000 [00:00<?, ? steps/s]
🏁 Bifurcated agents:   0%|          | 0/100 [00:00<?, ? agents/s]
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
    109 
    110     def __compare_energies(self, sampled_spins: torch.Tensor) -> None:
--> 111         energies = torch.nn.functional.bilinear(
    112             sampled_spins.t(), sampled_spins.t(), torch.unsqueeze(self.ising_tensor, 0)
    113         ).reshape(self.n_agents)

RuntimeError: expected scalar type Double but found Float

解决建议

1. 修正代码中的笔误

原代码中m_sb = m.double()里的变量m未定义,应该修改为:

m_sb = m_sb.double()

2. 统一张量数据类型

报错核心是bilinear函数要求输入张量类型一致,你传入的ising_tensor(即m_sb)是Double类型,但库内部生成的sampled_spins是Float类型,导致类型不匹配。可以通过以下两种方式解决:

方式一:将m_sb转为Float类型(推荐)

直接把生成张量的代码改为Float类型,和库内部的张量类型对齐:

# 替换原有的m_sb定义行
m_sb = torch.FloatTensor(generate_weights(data))
# 无需再转double,直接使用Float类型

方式二:强制库内部张量转为Double类型

如果需要保留Double类型计算,可以在调用sb.maximize前,设置PyTorch的默认张量类型为Double:

# 在调用sb.maximize前添加
torch.set_default_dtype(torch.double)

注意:如果使用CUDA,还要确保设备上的张量类型一致,避免CPU/GPU张量类型不匹配的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 18:24:55