gotensor/README.md

110 lines
2.5 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# gotensor
gotensor 是一个用 Go 语言编写的张量计算库,提供了基本的张量运算、自动微分和反向传播功能。该项目旨在为 Go 语言开发者提供一个高效、易用的张量计算工具。
## 功能特性
- 基本张量运算:加法、减法、乘法、矩阵乘法等
- 张量操作:数乘、转置等
- 自动微分和反向传播
- 支持多种初始化方式:零张量、单位矩阵、随机张量等
## 安装
```bash
go get git.kingecg.top/kingecg/gotensor
```
## 快速开始
```go
package main
import (
"fmt"
"git.kingecg.top/kingecg/gotensor"
)
func main() {
// 创建两个2x2的张量
t1_data := []float64{1, 2, 3, 4}
t1_shape := []int{2, 2}
t1, err := gotensor.NewTensor(t1_data, t1_shape)
if err != nil {
panic(err)
}
t2_data := []float64{5, 6, 7, 8}
t2, err := gotensor.NewTensor(t2_data, t1_shape)
if err != nil {
panic(err)
}
// 执行加法运算
result, err := t1.Add(t2)
if err != nil {
panic(err)
}
fmt.Printf("结果:\n%s\n", result.String())
}
```
## 示例
项目包含多个示例,展示如何使用 gotensor
- [基本运算示例](examples/basic_operations.go):展示基本的张量运算
- [自动微分示例](examples/autograd_example.go):演示自动微分和反向传播
- [线性回归示例](examples/linear_regression.go):使用 gotensor 实现简单的线性回归
运行示例:
```bash
# 基本运算示例
go run examples/basic_operations.go
# 自动微分示例
go run examples/autograd_example.go
# 线性回归示例
go run examples/linear_regression.go
```
## API 文档
### 创建张量
- `NewTensor(data []float64, shape []int)` - 创建新的张量
- `NewZeros(shape []int)` - 创建零张量
- `NewOnes(shape []int)` - 创建全一张量
- `NewIdentity(size int)` - 创建单位矩阵
### 张量运算
- `Add(other *Tensor)` - 张量加法
- `Subtract(other *Tensor)` - 张量减法
- `Multiply(other *Tensor)` - 张量逐元素乘法
- `MatMul(other *Tensor)` - 矩阵乘法
- `Scale(factor float64)` - 数乘
### 其他方法
- `ZeroGrad()` - 将梯度置零
- `Shape()` - 返回张量形状
- `Size()` - 返回张量大小
- `Get(indices ...int)` - 获取指定位置的值
- `Set(value float64, indices ...int)` - 设置指定位置的值
- `Backward()` - 执行反向传播
## 测试
运行测试:
```bash
go test
```
## 许可证
本项目使用 MIT 许可证 - 详见 [LICENSE](LICENSE) 文件。