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 分钟前
不会画画,也能把故事做成漫画吗?先做这场测试
人工智能·产品·全栈
二进制_博客8 分钟前
rag面试题之多轮对话时的上下文依赖检索设计
人工智能·机器学习
名不经传的养虾人14 分钟前
从0到1:企业级AI项目迭代日记 Vol.90|Agent变快了,Judge定下来了
大数据·数据库·人工智能·ai编程·企业ai
benchmark_cc23 分钟前
批量获取量化数据时,如何设置合理的超时和重试机制?——QuantDash 高性能实战指南
开发语言·人工智能·python·pandas·量化·quantdash
2601_9669496524 分钟前
使用 Pandas 读取批量数据时如何避免内存溢出?QuantDash 量化数据工程师避坑指南
开发语言·python·pandas·tushare·akshare·quantdash
Geek-Chow26 分钟前
06 训练管线:数据如何变成权重
人工智能·算法
树欲静而风不止8628 分钟前
AI赋能研发管理:全星APQP系统打通质量闭环,让高端制造项目管控更聪明
人工智能·制造
%4730 分钟前
DAY 38
人工智能·pytorch·深度学习
65岁退休Coder32 分钟前
LangChain v1.3.4 笔记 - 08 MCP & 相关概念
后端·python·langchain
北京靠谱的GEO优化机构36 分钟前
媒体邀约怎么做才专业?详解企业高端品牌专访传播全流程
大数据·人工智能·媒体