c++ 实现np.argmin和np.argmax

忘记从哪里看到的别人的代码了,侵删

#include <algorithm>
#include <vector>
#include <iostream>
#include <array>
using namespace std;
template<class ForwardIterator>
inline size_t argmin(ForwardIterator first, ForwardIterator last)
{
	return std::distance(first, std::min_element(first, last));
}

template<class ForwardIterator>
inline size_t argmax(ForwardIterator first, ForwardIterator last)
{
	return std::distance(first, std::max_element(first, last));
}

int main() {
	array<int, 7> numbers{ 2, 4, 8, 0, 6, -1, 3 };
	int minIndex = argmax(numbers.begin(), numbers.end());
	cout << minIndex << '\n';
	vector<float> prices = { 12.5f, 8.9f, 100.0f, 24.5f, 30.0f };
	float maxIndex = argmin(prices.begin(), prices.end());
	cout << maxIndex << '\n';
	return 0;
}
`np.argmin` 和 `torch.min` 是用于找到张量中最小值的索引的函数,但它们来自不同的库,具有一些区别。 `np.argmin` 是 NumPy 库中的函数,用于在 NumPy 数组中找到最小值的索引。它的使用方式如下: ```python import numpy as np arr = np.array([5, 2, 8, 1, 9]) min_index = np.argmin(arr) print(min_index) # 输出:3 ``` 在这个例子中,我们定义了一个 NumPy 数组 `arr`,并使用 `np.argmin(arr)` 找到了最小值的索引。输出结果为 3,表示最小值在数组中的索引位置。 `torch.min` 是 PyTorch 库中的函数,用于在 PyTorch 张量中找到最小值的索引。它的使用方式如下: ```python import torch tensor = torch.tensor([5, 2, 8, 1, 9]) min_value, min_index = torch.min(tensor, dim=0) print(min_index.item()) # 输出:3 ``` 在这个例子中,我们定义了一个 PyTorch 张量 `tensor`,并使用 `torch.min(tensor, dim=0)` 找到了最小值的索引。输出结果为 3,表示最小值在张量中的索引位置。 需要注意的是,`torch.min` 函数在返回最小值索引时会返回一个张量,并且我们需要使用 `.item()` 方法将其转换为标量值。而 `np.argmin` 直接返回最小值索引的标量值。 此外,`torch.min` 还可以指定 `dim` 参数来沿着特定的维度进行最小值的计算。这使得我们可以在多维张量中找到每个维度的最小值索引。 总结起来,`np.argmin` 是 NumPy 库中用于找到 NumPy 数组中最小值索引的函数,而 `torch.min` 是 PyTorch 库中用于找到 PyTorch 张量中最小值索引的函数,并且支持沿着不同维度进行计算。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值