我正在尝试将循环的长度注册为优化参数,以便优化程序将自动调整循环的长度。
这是一个示例代码(实际问题比较复杂,但是您会明白的):
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
<!-- Navbar -->
<nav class="navbar navbar-dark bg-dark">
<span class="navbar-brand mb-0 h1 mx-auto navbar-brand">Pixel Art Maker</span>
</nav>
<!-- Container to put grid in -->
<div class="container shadow p-3 mb-5 bg-white rounded mt-5 main">
<div class="container canvas d-flex-inline">
</div>
<form class="d-flex-inline w-50 mx-auto">
<div class="d-flex">
<div class="form-group w-25 ml-auto mr-2">
<label class="d-block text-center" for="gridRows">Rows</label>
<input type="number" class="form-control row-input" id="gridRows">
</div>
<div class="form-group w-25 mr-auto ml-2">
<label class="d-block text-center" for="gridColumns">Columns</label>
<input type="number" class="form-control column-input" id="gridColumns">
</div>
</div>
</form>
<div class="form-group w-25 mx-auto">
<button type="submit" class="btn btn-primary w-100">Submit</button>
</div>
<form class="d-flex-inline w-50 mx-auto">
<div class="form-group w-25 mx-auto">
<label for="color">Color</label>
<input type="color" class="form-control colorChoice" id="color">
</div>
</form>
</div>
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS, then local JS -->
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js" integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV" crossorigin="anonymous"></script>
优化似乎不起作用,这是输出:
import torch
positive_iter = torch.tensor([10.0], requires_grad=True)
negative_iter = torch.tensor([20.0], requires_grad=True)
optimizer = torch.optim.Adam([positive_iter, negative_iter], lr=0.02, betas=(0.5, 0.999))
for i in range(100):
loss = torch.tensor([0.0], requires_grad=True)
for g in range(int(positive_iter)):
loss = loss + torch.rand(1)
for d in range(int(negative_iter)):
loss = loss - torch.rand(1) * 2
loss = torch.abs(loss)
loss.backward()
optimizer.step()
print(i, loss.item(), positive_iter.item(), negative_iter.item())
您能否建议如何使for循环长度成为优化参数。
谢谢