使用rust编写一个二层神经网络
时间: 2023-03-19 19:21:26 浏览: 139
好的,下面是使用 Rust 编写一个简单的二层神经网络的代码示例:
```rust
extern crate ndarray;
extern crate rand;
use ndarray::{Array, Array2, Axis};
use rand::prelude::*;
fn main() {
// 定义输入和输出数据
let inputs = Array2::from_shape_vec((4, 2), vec![0.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0]).unwrap();
let outputs = Array::from_vec(vec![0.0, 1.0, 1.0, 0.0]);
// 定义神经网络的结构
let input_size = 2;
let hidden_size = 3;
let output_size = 1;
// 初始化神经网络的权重和偏置
let mut rng = thread_rng();
let w1 = Array::random((input_size, hidden_size), StandardNormal, &mut rng);
let b1 = Array::random(hidden_size, StandardNormal, &mut rng);
let w2 = Array::random((hidden_size, output_size), StandardNormal, &mut rng);
let b2 = Array::random(output_size, StandardNormal, &mut rng);
// 训练神经网络
let learning_rate = 0.1;
let num_iterations = 10000;
for _ in 0..num_iterations {
let hidden_layer = inputs.dot(&w1) + &b1;
let activated_hidden_layer = hidden_layer.mapv(|x| 1.0 / (1.0 + (-x).exp()));
let output_layer = activated_hidden_layer.dot(&w2) + &b2;
let predicted_output = output_layer.mapv(|x| 1.0 / (1.0 + (-x).exp()));
let error = &predicted_output - &outputs;
let d_predicted_output = &error * &predicted_output * (&Array::ones(outputs.len()) - &predicted_output);
let error_hidden_layer = d_predicted_output.dot(&w2.t());
let d_hidden_layer = error_hidden_layer * &activated_hidden_layer * (&Array::ones(hidden_layer.len()) - &activated_hidden_layer);
w2 -= learning_rate * &activated_hidden_layer.t().dot(&d_predicted_output);
b2 -= learning_rate * d_predicted_output.sum_axis(Axis(0));
w1 -= learning_rate * &inputs.t().dot(&d_hidden_layer);
b1 -= learning_rate * d_hidden_layer.sum_axis(Axis(0));
}
// 测试神经网络
let test_input = Array::from_vec(vec![1.0, 0.0]);
let hidden_layer = test_input.dot(&w1) + &b1;
let activated_hidden_layer = hidden_layer.mapv(|x| 1.0 / (1.0 + (-x).exp()));
let output_layer = activated_hidden_layer.dot(&w2) + &b2;
let predicted_output = output_layer.mapv(|x| 1.0 / (1.0 + (-x).exp()));
println!("预测输出:{:?}", predicted_output);
}
```
这个代码示例实现了一个二层神经网络,包括输入层、隐藏层和输出层。输入层包含 2 个神经元,隐藏层包含 3 个
阅读全文