当前位置: 首页 > news >正文

PyTorch代码(5)

PyTorch语法

张量的创建

importtorch a=[1,2,3.]print(type(a))b=torch.tensor(a)print(b)print(type(b))print(b.dtype)importnumpyasnp c=np.random.normal((2,3))d=torch.tensor(c)print(d)e=torch.ones_like(d)print(e)f=torch.zeros_like(d)print(f)g=torch.rand_like(d)print(g)print(torch.rand((2,2)))print(torch.randn([2,2]))print(torch.rand([2,2,]).dtype)h=torch.rand([2,2,])print(h.dtype)print(h.shape)print(h.device)print(torch.is_tensor(h))i=torch.tensor(0)print(torch.is_nonzero(i))print('-'*34)print(torch.numel(h))print(torch.zeros([5,5]))a=torch.zeros([5,5],dtype=torch.int32)print(a)print(torch.zeros([5,5]).dtype)print(torch.ones_like(a))print('-'*34)print(torch.arange(5))print(torch.arange(0,5,2))print(torch.range(0,5))print(torch.range(0,2).dtype)print(torch.arange(0,5).dtype)foriintorch.arange(5):print('epoch:',i)print(torch.eye(3))print(torch.ones_like(a)*5)print(torch.full([2,2],2))print(torch.full_like(a,2))a=torch.rand([3,2,])print(a)b=torch.rand([3,2,])print(b)print(torch.cat([a,b],dim=0))

张量的运算API(1)

importtorch b=torch.rand([3,2])print(b)c,d=torch.chunk(b,chunks=2,dim=1)print(c)print(d)print(torch.reshape(torch.reshape(b,[2,3]),[-1]))print('-'*34)src=torch.tensor([[1,2],[3,4],[5,6]])index=torch.tensor([[0,2],[1,0],[2,1]])'''out = torch.zeros_like(src) out.scatter_(dim=0, index=index, src=src) #src [i][j] 这个数,要搬到 out 的 第 index [i][j] 行、第 j 列 print(out) '''a=torch.arange(10).reshape(5,2)#print(a)#print(torch.split(a,[1,4]))''' print(a.shape) print(torch.squeeze(torch.reshape(a,[1,1,5,2]),dim=0).shape) '''b=torch.rand(5,2)print(torch.stack([a,b],dim=0).shape)#torch.Size([2, 5, 2])print(torch.stack([a,b],dim=1).shape)#torch.Size([5, 2, 2])print(torch.cat([a,b],dim=0).shape)#torch.Size([10, 2])print(torch.cat([a,b],dim=1).shape)#torch.Size([5, 4])

张量的运算API(2)

importtorch a=torch.rand([3,2])print(a)#print(torch.take(a,torch.tensor([0,2,4])))''' print(torch.tile(a,dims=[1,2])) print(torch.tile(a,dims=[2,1])) '''''' print(torch.transpose(a,0,1)) print('-'*34) print(torch.unbind(a,dim=0)) print(torch.unbind(a,dim=1)) print('-'*34) print(torch.unsqueeze(a,dim=0).shape) print(torch.unsqueeze(a,dim=1).shape) print(torch.unsqueeze(a,dim=-1).shape) '''b=torch.zeros_like(a)print(torch.where(a>0.5,a,b))

dataset的基本代码实现

fromtorch.utils.dataimportDatasetfromPILimportImageimportosclassMyDataset(Dataset):def__init__(self,root_dir,label_dir):self.root_dir=root_dir self.label_dir=label_dir self.path=os.path.join(self.root_dir,self.label_dir)self.img_path=os.listdir(self.path)def__getitem__(self,index):img_name=self.img_path[index]img_item_path=os.path.join(self.root_dir,self.label_dir,img_name)img=Image.open(img_item_path)label=self.label_dirreturnimg,labeldef__len__(self):returnlen(self.img_path)root_dir='dataset'ants_label_dir='ants'bees_label_dir='bees'ants_dataset=MyDataset(root_dir,ants_label_dir)bees_dataset=MyDataset(root_dir,bees_label_dir)dataset=ants_dataset+bees_dataset

如何用SummaryWriter记录图像和标量

importnumpy numpy.bool8=boolfromtorch.utils.tensorboardimportSummaryWriterimportnumpyasnpfromPILimportImage writer=SummaryWriter('logs')image_path='dataset/ants/0013035.jpg'img_PIL=Image.open(image_path)img_array=np.array(img_PIL)print(type(img_array))print(img_array.shape)writer.add_image("test",img_array,1,dataformats='HWC')#y=2xforiinrange(100):writer.add_scalar('y=2x',2*i,i)writer.close()

使用transforms.ToTensor()将PIL图像转换为Tensor

fromPILimportImagefromtorch.utils.tensorboardimportSummaryWriterfromtorchvisionimporttransforms img_path="dataset/ants/0013035.jpg"img_PIL=Image.open(img_path)writer=SummaryWriter('logs')#1.使用transforms.ToTensor()将PIL图像转换为Tensortransform=transforms.ToTensor()img_tensor=transform(img_PIL)writer.add_image('Tensor_img',img_tensor)writer.close()
http://www.jsqmd.com/news/880662/

相关文章:

  • Android原生代码调试:DS-5环境配置与实战技巧
  • 2026Q2艺术楼梯定制哪家专业:别墅楼梯定制、实木楼梯定制、实木艺术楼梯、弧形钢构楼梯定制、成都实木楼梯、成都楼梯选择指南 - 优质品牌商家
  • Linux 文件权限 rwx 与数字权限 755/644 彻底详解(新手必懂)
  • 现代计算架构优化:零开销循环、SIMD与张量加速
  • 2026年5月视频剪辑制作培训机构排行实测盘点:软件测试线下就业培训/AI软件测试培训/外贸电商设计培训/影视特效剪辑培训/选择指南 - 优质品牌商家
  • 【数据集】省级农村创业活跃度/农户创业活跃度(2005-2024年)
  • 洛谷p1419
  • Arm ETE嵌入式追踪技术:架构解析与调试优化
  • 2026年5月新发布河南IPO企业股权激励选择指南 - 2026年企业推荐榜
  • 基于ISO/IEC 27004的机器学习模型风险测量框架(RMF)实战解析
  • 2026年至今,黄金回收行业口碑与服务标杆企业深度解析:广州宝奢科技 - 2026年企业推荐榜
  • C语言三大经典排序算法详解:快速排序、冒泡排序与选择排序
  • python async/await异步编程设计常用插件
  • 别再死记硬背了!通过一个成绩分析项目,彻底搞懂Linux静态库和共享库的区别
  • 2026负压隔离器技术深度解析:惰性气体手套箱、放射性药品生产热室、放射性药物热室、核医药热室、生物隔离器、真空手套箱选择指南 - 优质品牌商家
  • 2026年现阶段,北京高端住宅两联供优选:合宜人居高端住宅隐蔽工程一体化服务专家 - 2026年企业推荐榜
  • 编程语言排行榜:Java 的保守与 C# 的崛起,背后是「用户体验」的战争
  • 艾多美非传销远离“一夜暴富”,拥抱“细水长流”
  • 四川钢管厂家现货批发|工程专用钢材一站式配送 - 四川盛世钢联营销中心
  • Linux音频调试不求人:用amixer命令行精准控制音量与声道,解决‘有画面没声音’问题
  • 【助睿实验指导】学生用户画像 - 考勤画像可视化分析
  • 别再手动输卡号了!用PaddleOCR+Python实现银行卡信息自动识别(附完整代码)
  • 小学期第二周
  • 不只是编译:在龙芯3A4000的银河麒麟V10上,给FileZilla解决gnutls和wxWidgets依赖的完整思路
  • 2026杭州小红书广告投放技术拆解与靠谱服务商盘点:杭州短视频运营公司、杭州AI搜索优化、杭州GEO优化、杭州SEM广告投放选择指南 - 优质品牌商家
  • 佛山中窄重型门厂家怎么选:佛山高端系统门窗厂家、佛山中窄重型断桥提升门厂家、佛山中窄重型门厂家、佛山全景推拉门窗厂家选择指南 - 优质品牌商家
  • 基础能力系列 - 多线程1 - 内存序
  • Claude Code完整安装与配置指南
  • 别让阴影偷走你的电费!手把手教你用无人机巡检排查光伏板热斑(附Python分析脚本)
  • 四川钢板厂家现货批发|工程专用钢材一站式配送 - 四川盛世钢联营销中心