我正在尝试使用ndarray来计算点积,但得到了一些我不理解的编译错误。
我的基本功能是
use ndarray::{ArrayD, ArrayBase};
pub fn cosine<L>(v1: &ArrayBase<f64, L>, v2: &ArrayBase<f64, L>) -> f64 {
let x: f64 = v1.dot(&v2) / (v1.dot(v1) * v2.dot(v2)).sqrt();
return x
}
pub fn cosine2(v1: &ArrayD<f64>, v2: &ArrayD<f64>) -> f64 {
let x: f64 = v1.dot(v2) / (v1.dot(v1) * v2.dot(v2)).sqrt();
return x
}编译失败:
error[E0277]: the trait bound `f64: ndarray::data_traits::RawData` is not satisfiedchgraph
--> src/simple.rs:3:1
|
3 | / pub fn cosine<L>(v1: &ArrayBase<f64, L>, v2: &ArrayBase<f64, L>) -> f64 {
4 | | let x: f64 = v1.dot(&v2) / (v1.dot(v1) * v2.dot(v2)).sqrt();
5 | | }
| |_^ the trait `ndarray::data_traits::RawData` is not implemented for `f64`
|
= note: required by `ndarray::ArrayBase`如果我注释掉了cosine,就会收到来自cosine2的错误
error[E0599]: no method named `dot` found for reference `&ndarray::ArrayBase<ndarray::data_repr::OwnedRepr<f64>, ndarray::dimension::dim::Dim<ndarray::dimension::dynindeximpl::IxDynImpl>>` in the current scope
--> src/simple.rs:9:21
|
9 | let x: f64 = v1.dot(v2) / (v1.dot(v1) * v2.dot(v2)).sqrt();
| ^^^ method not found in `&ndarray::ArrayBase<ndarray::data_repr::OwnedRepr<f64>, ndarray::dimension::dim::Dim<ndarray::dimension::dynindeximpl::IxDynImpl>>`(对于其他点积,再复制两份)。为什么第二个版本找不到这个方法?看起来ArrayD是一种基于Array的类型,而ArrayBase又是一种类型,所以ArrayD::dot应该是一个现有的方法。
我只需要通过一个ArrayD,所以我对这两个版本都很满意。
我的Cargo.toml的相关部分是
[dependencies.ndarray]
version = "0.13.1"
[features]
default = ["ndarray/blas"]发布于 2020-11-11 02:06:24
首先,ArrayBase的数据类型不是通过数据类型来索引的,而是该数据类型的RawData包装器。其次,dot需要实现Dot特征。因此,您应该将这两者都添加到特征边界中:
use ndarray::linalg::Dot;
use ndarray::{ArrayBase, ArrayD, RawData};
pub fn cosine<D, L>(v1: &ArrayBase<D, L>, v2: &ArrayBase<D, L>) -> f64
where
D: RawData<Elem = f64>,
ArrayBase<D, L>: Dot<ArrayBase<D, L>, Output = f64>,
{
let x: f64 = v1.dot(&v2) / (v1.dot(v1) * v2.dot(v2)).sqrt();
return x;
}https://stackoverflow.com/questions/64774226
复制相似问题