# 0
##安装 python 和 pip
```bash
sudo apt update
sudo apt install python3 python3-pip
```
##安装 tinygrad
```bash
git clone
https://github.com/geohot/tinygrad.gitcd tinygrad
pip3 install -r requirements.txt
```
##测试安装
```bash
python3 -m unittest
```
# 1
##创建模型
```python
from tinygrad.tensor import Tensor
class SimpleNN:
def __init__(self, input_size, num_classes):
# 随机初始化权重
self.w1 = Tensor.random(input_size, 64)
self.w2 = Tensor.random(64, num_classes)
def forward(self, x):
# 简单的前向传播
x = x.dot(self.w1).relu()
x = x.dot(self.w2).logsoftmax()
return x
def parameters(self):
# 返回模型参数
return [self.w1, self.w2]
```
## 准备数据
```python
import numpy as np
X = np.random.randn(10, 784)
Y = np.zeros((10, 10))
Y[np.arange(10), np.random.randint(0, 10, size=10)] = 1
```
## 训练模型
```python
def train(model, X, Y, lr=0.001, epochs=100):
# 将 numpy 数组转换为 Tensor
inputs = Tensor(X)
targets = Tensor(Y)
for i in range(epochs):
# 前向传播
out = model.forward(inputs)
# 计算损失(交叉熵)
loss = out.mul(targets).mean()
print(f"Epoch {i}, Loss: {loss.data}")
# 反向传播
model.zero_grad()
loss.backward()
# 更新权重
for param in model.parameters():
param.data -= lr * param.grad
def main():
model = SimpleNN(784, 10)
train(model, X, Y)
if __name__ == "__main__":
main()
```
# 2
## 执行脚本 开始训练过程 看到每个 epoch 的损失输出到终端