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
相关推荐
gorgeous(๑>؂<๑)4 分钟前
【DeepSeek-OCR系列第一篇】Language Modelling with Pixels【ICLR23】
人工智能·语言模型·自然语言处理·ocr
开放知识图谱6 分钟前
论文浅尝 | LightPROF:一种轻量级推理框架,用于大型语言模型在知识图谱上的应用(AAAI2025)
人工智能·语言模型·自然语言处理·知识图谱
vlln8 分钟前
【论文速读】LLM+AL: 用符号逻辑校准语言模型的规划能力
人工智能·语言模型·自然语言处理
Antonio91521 分钟前
【图像处理】图像错切变换
图像处理·人工智能
小白银子24 分钟前
零基础从头教学Linux(Day 56)
linux·运维·python
文火冰糖的硅基工坊25 分钟前
[人工智能-大模型-85]:大模型应用层 - AI/AR眼镜:华为智能眼镜、苹果智能眼镜、Google Glass智能眼镜的软硬件技术架构
人工智能·华为·ar
B站计算机毕业设计之家32 分钟前
计算机视觉:python手写数字识别系统 手写数字检测 CNN算法 卷积神经网络 OpenCV和Keras模型 大数据毕业设计(建议收藏)✅
python·神经网络·opencv·计算机视觉·cnn·手写数字·数字识别
wolfseek33 分钟前
opencv模版匹配
c++·人工智能·opencv·计算机视觉
B站计算机毕业设计之家36 分钟前
Python手势识别检测系统 基于MediaPipe的改进SSD算法 opencv+mediapipe 深度学习 大数据 (建议收藏)✅
python·深度学习·opencv·计算机视觉·1024程序员节
犽戾武37 分钟前
1. 简单回顾Numpy神经网络
人工智能·神经网络·numpy