`iplot` can only run inside an IPython Notebook.
时间: 2024-04-02 09:33:33 浏览: 259
这是一个声明,告诉你 `iplot` 只能在 IPython Notebook 中运行,如果你在其他环境中调用 `iplot`,会出现错误。`iplot` 是 Plotly 提供的一种交互式绘图工具,它需要在 IPython Notebook 中运行才能实现交互式显示。如果你想在其他环境中使用 Plotly 绘图,可以考虑使用 `plot` 函数。
相关问题
We can now use a method to plot the loss surface of the network by projecting the parameter updates into two dimensions. You can find more information on that here. But you can just use the provided code. The contour plot will show how the loss will change if you would follow the two main directions of the past parameter updates. Think about the challenges and the optimization process of this landscape. What could impede the convergence of the net? # project states onto the main directions of the gradient updates using n samples over all steps starting from sample x # the directions are calculated using the last sample as a reference directions, state_ids, loss_coordinates = get_state_directions(states, n_states=10, start_from=0, reference_id=-1) # compute the losses over the main directions of the gradient updates x, y, Z, _ = get_loss_grid(net, data_loader, loss_fn, directions=directions, resolution=(20, 20), scale=loss_coordinates.abs().max().item()) # plot the landscape as a contour plot fig = plot_contour(np.copy(x), np.copy(y), np.copy(Z), scale=True) fig.add_traces(go.Scatter(x=np.copy(loss_coordinates[0].cpu().numpy()), y=np.copy(loss_coordinates[1].cpu().numpy()))) print('loss samples:', np.array(losses)[state_ids]) conf_pltly() init_notebook_mode(connected=False) iplot(fig) --------------------------------------------------------------------------- RuntimeError Traceback (most recent call last) <ipython-input-62-26d05ea2d790> in <cell line: 3>() 1 # project states onto the main directions of the gradient updates using n samples over all steps starting from sample x 2 # the directions are calculated using the last sample as a reference ----> 3 directions, state_ids, loss_coordinates = get_state_directions(states, n_states=10, start_from=0, reference_id=-1) 4 5 # compute the losses over the main directions of the gradient updates <ipython-input-60-6cc4aad7dcda> in get_state_directions(states, n_states, start_from, reference_id) 15 params.append(param.view(-1)) 16 ---> 17 params = torch.stack(params, dim=0) 18 reference = params[-1] 19 RuntimeError: stack expects each tensor to be equal size, but got [200704] at entry 0 and [256] at entry 1这个错误怎么改
这个错误是由于在进行 torch.stack(params, dim=0) 操作时,params 中的张量维度不一致导致的。可以通过使用 torch.cat() 来代替 torch.stack(),将 params 列表中的张量按照指定维度拼接起来,从而避免这个错误。具体来说,可以将 get_state_directions() 函数中的 params = torch.stack(params, dim=0) 改为 params = torch.cat(params, dim=0)。
# Set cash inside the strategy cerebro.broker = bt.brokers.BackBroker(coc=True) # 设置启动资金 cerebro.broker.setcash(10000.0) # 设置交易单位大小 # cerebro.addsizer(bt.sizers.FixedSize, stake=5000) # 设置佣金为千分之一 cerebro.broker.setcommission(commission=0.003) # 添加图表设置 cerebro.addobserver(bt.observers.Broker) cerebro.addobserver(bt.observers.Trades) cerebro.addobserver(bt.observers.DrawDown) # Set leverage #cerebro.broker.setcommission() # 添加分析指标 # 收益率 cerebro.addanalyzer(bt.analyzers.Returns, _name='_Returns') # 收益期间 cerebro.addanalyzer(bt.analyzers.TimeReturn, _name='_TimeReturn') # 计算最大回撤相关指标 cerebro.addanalyzer(bt.analyzers.DrawDown, _name='_DrawDown') # 回撤期间 cerebro.addanalyzer(bt.analyzers.TimeDrawDown, _name='_TimeDrawDown') # 计算年化夏普比率 cerebro.addanalyzer(bt.analyzers.SharpeRatio, _name='_SharpeRatio', timeframe=bt.TimeFrame.Days, annualize=True, riskfreerate=0) # 计算夏普比率 # 交易统计信息,如获胜、失败次数 cerebro.addanalyzer(bt.analyzers.TradeAnalyzer, _name='_TradeAnalyzer') # 运行回测 result = cerebro.run() # 输出回测结果 # 提取结果 print("--------------- 收益期间 -----------------") print(result[0].analyzers._TimeReturn.get_analysis()) print("--------------- 最大回撤相关指标 -----------------") print(result[0].analyzers._DrawDown.get_analysis()) print("--------------- 回撤期间 -----------------") print(result[0].analyzers._TimeDrawDown.get_analysis()) print(f"最终资金: {cerebro.broker.getvalue():,.2f} 元") print("收益率:",result[0].analyzers._Returns.get_analysis()['rtot']) print("夏普比率:",result[0].analyzers._SharpeRatio.get_analysis()['sharperatio']) # 绘制图表 cerebro.plot(iplot=False, style='candlestick', barup='red', bardown='green', volume=True, volup='red', voldown='green')这一代码显示IndentationError: unexpected indent
这个错误是因为代码的缩进不正确。你需要检查代码的缩进是否正确,确保每个代码块都有正确的缩进。在 Python 中,缩进是非常重要的,因为它定义了代码块的范围。以下是一个修复缩进的示例:
```
# Set cash inside the strategy
cerebro.broker = bt.brokers.BackBroker(coc=True)
# 设置启动资金
cerebro.broker.setcash(10000.0)
# 设置交易单位大小
# cerebro.addsizer(bt.sizers.FixedSize, stake=5000)
# 设置佣金为千分之一
cerebro.broker.setcommission(commission=0.003)
# 添加图表设置
cerebro.addobserver(bt.observers.Broker)
cerebro.addobserver(bt.observers.Trades)
cerebro.addobserver(bt.observers.DrawDown)
# Set leverage
#cerebro.broker.setcommission()
# 添加分析指标
# 收益率
cerebro.addanalyzer(bt.analyzers.Returns, _name='_Returns')
# 收益期间
cerebro.addanalyzer(bt.analyzers.TimeReturn, _name='_TimeReturn')
# 计算最大回撤相关指标
cerebro.addanalyzer(bt.analyzers.DrawDown, _name='_DrawDown')
# 回撤期间
cerebro.addanalyzer(bt.analyzers.TimeDrawDown, _name='_TimeDrawDown')
# 计算年化夏普比率
cerebro.addanalyzer(bt.analyzers.SharpeRatio, _name='_SharpeRatio', timeframe=bt.TimeFrame.Days, annualize=True, riskfreerate=0)
# 计算夏普比率
# 交易统计信息,如获胜、失败次数
cerebro.addanalyzer(bt.analyzers.TradeAnalyzer, _name='_TradeAnalyzer')
# 运行回测
result = cerebro.run()
# 输出回测结果
# 提取结果
print("--------------- 收益期间 -----------------")
print(result[0].analyzers._TimeReturn.get_analysis())
print("--------------- 最大回撤相关指标 -----------------")
print(result[0].analyzers._DrawDown.get_analysis())
print("--------------- 回撤期间 -----------------")
print(result[0].analyzers._TimeDrawDown.get_analysis())
print(f"最终资金: {cerebro.broker.getvalue():,.2f} 元")
print("收益率:",result[0].analyzers._Returns.get_analysis()['rtot'])
print("夏普比率:",result[0].analyzers._SharpeRatio.get_analysis()['sharperatio'])
# 绘制图表
cerebro.plot(iplot=False, style='candlestick', barup='red', bardown='green', volume=True, volup='red', voldown='green')
```
在这个例子中,我将代码块的缩进调整为四个空格。这是 Python 中通常使用的标准缩进。你需要确保所有代码块的缩进都是一致的,并使用相同的缩进方式,例如空格或制表符。
阅读全文
相关推荐















