Pytorch 神经网络搭建步骤

文章目录

python 复制代码
import numpy as np
import torch
from PIL.Image import Image
from torch.autograd import Variable

# 获取数据
def get_data():
    train_X=np.asarray([3.3,4.4,5.5,6.71,6.93,4.168,9.779,6.182,7.59,2.167,7.042,10.791,5.313,7.997,5.654,9.27,3.1])
    train_Y=np.asarray([1.7,2.76,2.09,3.19,1.694,1.537,3.366,2.596,2.53,1.221,2.827,3.465,1.65,2.904,2.42,2.94,1.3])
    dtype=torch.FloatTensor
    X=Variable(torch.from_numpy(train_X).type(dtype),requires_grad=False).view(17,1)
    y=Variable(torch.from_numpy(train_Y).type(dtype),requires_grad=False)
    return X,y
# 随机参数
def get_weights():
    w=Variable(torch.randn(1),requires_grad=True)
    b=Variable(torch.randn(1),requires_grad=True)
    return w,b
w,b=get_weights()
# 模型计算
def simple_network(x):
    y_pred=torch.matmul(x,w)+b
    return y_pred
# 计算损失进行评估
def loss_fn(y,y_pred):
    loss=(y_pred-y).pow(2).sum()
    for param in [w,b]:
        if not param.grad is None:param.grad.data.zero_()
        loss.backward()
        return loss.data[0]
# 优化网络
def optimize(learning_rate):
    w.data-=learning_rate * w.grad.data
    b.data-=learning_rate * b.grad.data
from torch.utils.data import Dataset
class DogsAndCatsDataset(Dataset):
    def __init__(self,root_dir,size=(224,224)):
        self.files=globals(root_dir)
        self.size=size
    def __len__(self):
        return len(self.files)
    def __getitem__(self, item):
        img=np.asarray(Image.open(self.files[item]).resize(self.size))
        label=self.files[item].split('/')[-2]
        return img,label
class myFirstNetwork(torch.nn.Module):
    def __init__(self,input_size,hidden_size,output_size):
        super(myFirstNetwork,self).__init__()
        self.layer1=torch.nn.Linear(input_size,hidden_size)
        self.layer2=torch.nn.Linear(hidden_size,output_size)
    def __forward__(self,input):
        out=self.layer1(input)
        out=torch.nn.ReLU(out)
        out=self.layer2(out)
        return out
相关推荐
机器之心5 分钟前
「世界模型」也被泼冷水了?邢波等人揭开五大「硬伤」,提出新范式
人工智能
费弗里10 分钟前
Python全栈应用开发利器Dash 3.x新版本介绍(4)
python·dash
甲丁12 分钟前
国内 Claude Code 接入指南(免费获得国内代理$100额度)
人工智能
机器之心13 分钟前
刚刚,为对抗哥大退学生开发的AI作弊器,哥大学生造了个AI照妖镜
人工智能
辣辣y18 分钟前
python基础day08
开发语言·python
Binary_ey19 分钟前
AR/VR 显示画质失真?OAS百叶窗波导案例破难题
人工智能·ar·vr·软件需求·光学软件
运营黑客23 分钟前
Grok 4,来了。
人工智能·学习·ai·aigc
xunberg31 分钟前
【MCP 实战派】Node-RED MCP 插件实践指南:从安装到常见问题解析
人工智能·开源
二二孚日31 分钟前
自用华为ICT云赛道AI第一章知识点-机器学习概览
人工智能·华为
weisian15132 分钟前
人工智能-基础篇-24-RAG和LLM到底怎么理解和区分?(LLM是深度训练的大语言生成模型,RAG是LLM更智能的补充技术)
人工智能