未解析的导入“serde”,无法确定派生宏“Serialize”的分辨率,导入分辨率被卡住

问题描述 投票:0回答:1

我想在训练神经网络进行文件存储并随后加载文件后实现其保存。然而我遇到了这个错误,我真的很困惑到底是什么问题,我可能只是忽略了一些非常简单的东西,但我找不到任何东西:

error[E0432]: unresolved import `serde`
  --> src\neural_network.rs:15:5
   |
15 | use serde::{Serialize, Deserialize};
   |     ^^^^^ help: a similar path exists: `self::serde`

error: cannot determine resolution for the derive macro `Serialize`
  --> src\neural_network.rs:17:10
   |
17 | #[derive(Serialize, Deserialize)]
   |          ^^^^^^^^^
   |
   = note: import resolution is stuck, try simplifying macro imports

error: cannot determine resolution for the derive macro `Deserialize`
  --> src\neural_network.rs:17:21
   |
17 | #[derive(Serialize, Deserialize)]
   |                     ^^^^^^^^^^^
   |
   = note: import resolution is stuck, try simplifying macro imports

warning: unused import: `Read`
 --> src\neural_network.rs:8:28
  |
8 | use std::io::{self, Write, Read};
  |                            ^^^^
  |
  = note: `#[warn(unused_imports)]` on by default

error[E0277]: the trait bound `NeuralNetwork: Serialize` is not satisfied
   --> src\neural_network.rs:41:39
    |
41  |         let data = bincode::serialize(&self)?;
    |                    ------------------ ^^^^^ the trait `Serialize` is not implemented for `NeuralNetwork`
    |                    |
    |                    required by a bound introduced by this call
    |
    = help: the following other types implement trait `Serialize`:
              &'a T
              &'a mut T
              ()
              (T,)
              (T0, T1)
              (T0, T1, T2)
              (T0, T1, T2, T3)
              (T0, T1, T2, T3, T4)
            and 127 others
    = note: required for `&NeuralNetwork` to implement `Serialize`
note: required by a bound in `bincode::serialize`
   --> C:\Users\nlion\.cargo\registry\src\github.com-1ecc6299db9ec823\bincode-1.3.3\src\lib.rs:108:8
    |
108 |     T: serde::Serialize,
    |        ^^^^^^^^^^^^^^^^ required by this bound in `bincode::serialize`

error[E0277]: `?` couldn't convert the error to `std::io::Error`
  --> src\neural_network.rs:41:45
   |
41 |         let data = bincode::serialize(&self)?;
   |                                             ^ the trait `From<Box<bincode::ErrorKind>>` is not implemented for `std::io::Error`
   |
   = note: the question mark operation (`?`) implicitly performs a conversion on the error value using the `From` trait
   = help: the following other types implement trait `From<T>`:
             <std::io::Error as From<IntoInnerError<W>>>
             <std::io::Error as From<NulError>>
             <std::io::Error as From<getrandom::error::Error>>
             <std::io::Error as From<rand::Error>>
             <std::io::Error as From<std::io::ErrorKind>>
   = note: required for `Result<(), std::io::Error>` to implement `FromResidual<Result<Infallible, Box<bincode::ErrorKind>>>`

Some errors have detailed explanations: E0277, E0432.
For more information about an error, try `rustc --explain E0277`.
warning: `neural-network-scratch` (bin "neural-network-scratch") generated 1 warning
error: could not compile `neural-network-scratch` due to 5 previous errors; 1 warning emitted

我的项目具有以下结构:

├── dataset
│   └── (4 different parts of the MNIST Datasets)
├── src
│   ├── main.rs
│   └── neural_network.rs
└── Cargo.toml

我的货物.toml:

[package]
name = "neural-network-scratch"
version = "0.1.0"

[dependencies]
ndarray = { version = "0.16.1", features = ["serde"] }
rand = "0.8.5"
ndarray-rand = "0.15.0"
bincode = "1.3"
serde = { version = "1.0", features = ["derive"] }

最后是我在neural_network.rs中的代码:

extern crate rand;
extern crate ndarray_rand;
extern crate ndarray;
extern crate bincode;
extern crate serde;

use std::fs::File;
use std::io::{self, Write, Read};
use std::path::PathBuf;
use ndarray::{Array2, Array1};
use ndarray_rand::RandomExt;
use ndarray_rand::rand_distr::Uniform;
use ndarray::prelude::*;

// I tried both of these
//use crate::serde::{Serialize, Deserialize};
use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize)]
pub struct NeuralNetwork {
    pub input_size: usize,
    pub hidden_size: usize,
    pub output_size: usize,
    W1: Array2<f64>,
    W2: Array2<f64>,
    b1: Array1<f64>,
    b2: Array1<f64>,
}

impl NeuralNetwork { pub fn new(input_size: usize, hidden_size: usize, output_size: usize) -> Self {
        NeuralNetwork {
            input_size,
            hidden_size,
            output_size,
            W1: Array::random((input_size, hidden_size), Uniform::new(-1.0, 1.0)),
            W2: Array::random((hidden_size, output_size), Uniform::new(-1.0, 1.0)),
            b1: Array::random(hidden_size, Uniform::new(-1.0, 1.0)),
            b2: Array::random(output_size, Uniform::new(-1.0, 1.0)),
        }
    }

    pub fn save(&self, path: &PathBuf) -> io::Result<()> {
        let data = bincode::serialize(&self)?;
        let mut file = File::create(path)?;
        file.write_all(&data)?;
        Ok(())
    }
}

在main.rs中执行:

fn main() -> Result<(), io::Error> {
    // We initialize the neural network with 784 input neurons, 64 hidden neurons and 10 output neurons.
    // The weights and biases are set at random.
    let mut neural_network = NeuralNetwork::new(784, 64, 10);

    println!("\nNeural network initialized succesfully with input size: {}, hidden size: {}, output size: {}", neural_network.input_size, neural_network.hidden_size, neural_network.output_size);

    let model_path = PathBuf::from(format!("./model.bin"));
    neural_network.save(&model_path);

    Ok(())
}

我删除了一些内容,例如培训过程,因为我认为它们对此是不必要的,但如果您认为缺少解决此问题所需的内容,请随时告诉我,我将编辑我的帖子。谢谢它提前,我真的不知道为什么这不起作用。

我试图停止使用

extern crate serde;
,因为我读到这是不必要的。我更多地研究了宏以及如何派生函数,但我没有找到任何我尚未尝试过的东西导致我来到这里。我还删除了目标目录,使用了
cargo clean
cargo add serde
cargo update
但没有成功。

rust serialization struct rust-cargo serde
1个回答
0
投票

您隐含地使用了 Rust 语言的非常古老的版本。这就是为什么您发现需要

extern crate
以及名称解析无法按您预期工作的原因。

通过在您的

Cargo.toml
:

中声明当前版本来解决此问题
[package]
name = "neural-network-scratch"
version = "0.1.0"
edition = "2021"

然后您的

serde
导入应该可以工作,并且您可以删除所有
extern crate

© www.soinside.com 2019 - 2024. All rights reserved.