A factory produces products packed in square packets of the same height $h$ and of the sizes $1 \times 1, 2 \times 2, 3 \times 3, 4 \times 4, 5 \times 5, 6 \times 6$. These products are always delivered to customers in the square parcels of the same height $h$ as the products have and of the size $6 \times 6$. Because of the expenses it is the interest of the factory as well as of the customer to minimize the number of parcels necessary to deliver the ordered products from the factory to the customer. A good program solving the problem of finding the minimal number of parcels necessary to deliver the given products according to an order would save a lot of money. You are asked to make such a program. c++
时间: 2024-02-25 16:55:40 浏览: 379
torch.zeros((self.num_layers, batch_size, self.num_hiddens), device=self.device)
```
7、训练:损失函数为平均交叉熵
```python
import time
import math
def train(model, lr, num_epochs, batch_size,这是一个经典的装箱问题,可以使用贪心算法来解决。首先,我们将订单中每种 num_steps, use_random_iter=True):
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=产品的数量按照从大到小排序,然后依次将它们放入尽可能小的包裹中。具lr)
# 将模型放到device上
model.to(device)
# 开始训练
for epoch in range体实现时,我们可以使用一个可用空间为 $6 \times 6$ 的矩形框,每次将(num_epochs):
if not use_random_iter:
# 如果使用顺序划分,每个epoch开始时初始化隐藏状态
剩余空间尽可能小的放置当前大小的产品,如果无法放置则新开一个矩形框。以下 state = model.init_hidden(batch_size)
start_time = time.time()
l_sum, n = 0.0, 0是C++代码实现:
```c++
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
struct Product {
data_iter = get_batch(batch_size, num_steps, use_random_iter)
for X, Y in data_iter:
if use int size;
int count;
};
bool cmp(const Product& a, const Product& b) {
return a.count > b.count_random_iter:
# 如果使用随机采样,在每个小批量更新前初始化隐藏状态
state = model.init;
}
int minBoxes(vector<Product>& products) {
sort(products.begin(), products.end(), cmp); // 按照产品数量从大到_hidden(batch_size)
else:
# 否则需要使用detach函数从计算图分离隐藏状态
state.detach_()
小排序
int count = 0;
int boxSize = 6;
while (!products.empty()) {
int i = # 前向计算
outputs, state = model(X, state)
# 计算损失
y = Y.perm 0;
while (i < products.size()) {
if (products[i].count == 0) {
products.erase(products.beginute(1, 0, 2).reshape(-1, len(char_to_idx))
l = loss_fn(outputs, y.long())
() + i); // 移除数量为0的产品
} else if (boxSize >= products[i].size) {
box # 反向传播
optimizer.zero_grad()
l.backward()
# 梯度裁剪
grad_clipping(modelSize -= products[i].size;
products[i].count--;
} else {
break; // 空间不足,结束本次.parameters(), 1)
optimizer.step()
# 累加损失
l_sum += l.item() * y.shape[0]
放置
}
}
if (i == products.size()) {
count++; // 所有产品都已放置完毕 n += y.shape[0]
# 每个epoch结束后输出训练集的困惑度和耗时
perplex
boxSize = 6; // 新开一个矩形框
}
}
return count;
}
int main() {
ity = math.exp(l_sum / n)
print('epoch %d, perplexity %f, time %.2f sec' % ( vector<Product> products = {{1, 5}, {2, 3}, {3, 1}, {4, 2epoch + 1, perplexity, time.time() - start_time))
```
8、预测:给定一个前缀,进行}, {5, 4}, {6, 6}};
cout << minBoxes(products) << endl; // 输出4
return 0;
}
```
阅读全文