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
相关推荐
是Dream呀10 小时前
一个账号调用N个AI模型!从LLM到视频生成的丝滑解决方案
人工智能·大模型·aigc·音视频·deepseek
程序员爱钓鱼11 小时前
Python 实战:如何读取多格式 Excel 并实现跨表匹配合并(支持 XLS / XLSX)
后端·python·面试
2301_7972673411 小时前
神经网络组植物分类学习规划与本周进展综述15
人工智能·神经网络·学习
xuehaikj11 小时前
【实战案例】基于dino-4scale_r50_8xb2-36e_coco的棉田叶片病害识别与分类项目详解
人工智能·数据挖掘
算法与编程之美11 小时前
探索不同的优化器、损失函数、batch_size对分类精度影响
人工智能·机器学习·计算机视觉·分类·batch
程序员爱钓鱼11 小时前
Python编程实战:实现一个 Excel 批量处理工具(桌面实用脚本)
后端·python·ipython
MicrosoftReactor11 小时前
技术速递|GitHub Copilot 和 AI Agent 如何拯救传统系统
人工智能·github·copilot·agent
Solyn_HAN11 小时前
Python 生信进阶:Biopython 库完全指南(序列处理 + 数据库交互)
python·生物信息学·biopython
only-code11 小时前
SeqXGPT:Sentence-Level AI-Generated Text Detection —— 把大模型的“波形”变成测谎仪
人工智能·大语言模型·ai检测·文本检测