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
相关推荐
梅孔立2 分钟前
yum update 报错 Cannot find a valid baseurl for repo: centos-sclo-rh/x86_64 等解决办法
linux·python·centos
聚客AI6 分钟前
解构高效提示工程:分层模型、文本扩展引擎与可视化调试全链路指南
人工智能·llm·掘金·日新计划
喝过期的拉菲13 分钟前
使用 Pytorch Lightning 时追踪指标和可视化指标
pytorch·可视化·lightning·指标追踪
前端付豪18 分钟前
13、你还在 print 调试🧾?教你写出自己的日志系统
后端·python
摆烂工程师19 分钟前
Claude Code 落地实践的工作简易流程
人工智能·claude·敏捷开发
亚马逊云开发者21 分钟前
得心应手:探索 MCP 与数据库结合的应用场景
人工智能
这里有鱼汤23 分钟前
hvPlot:用你熟悉的 Pandas,画出你没见过的炫图
后端·python
大明哥_26 分钟前
100 个 Coze 精品案例 - 小红书爆款图文,单篇点赞 20000+,用 Coze 智能体一键生成有声儿童绘本!
人工智能
聚客AI26 分钟前
🚀拒绝试错成本!企业接入MCP协议的避坑清单
人工智能·掘金·日新计划·mcp
源码站~34 分钟前
基于Flask+Vue的豆瓣音乐分析与推荐系统
vue.js·python·flask·毕业设计·毕设·校园·豆瓣音乐