pytoch M2芯片测试

今天才发现我的新片是M2芯片,而不是M1芯片,有点尴尬
在这里插入图片描述
参考网址
https://www.oldcai.com/ai/pytorch-train-MNIST-with-gpu-on-mac/

测试结果如下

M2_cpu.py

# https://www.oldcai.com/ai/pytorch-train-MNIST-with-gpu-on-mac/
import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision.datasets import MNIST
from torchvision.transforms import ToTensorprint(f"PyTorch version: {torch.__version__}")# Check PyTorch has access to MPS (Metal Performance Shader, Apple's GPU architecture)
print(f"Is MPS (Metal Performance Shader) built? {torch.backends.mps.is_built()}")
print(f"Is MPS available? {torch.backends.mps.is_available()}")# Set the device
device = "cpu"
device = torch.device(device)
print(f"Using device: {device}")# Define the CNN model
class HandwritingRecognitionModel(nn.Module):def __init__(self):super().__init__()# Define the convolutional layersself.conv1 = nn.Conv2d(1, 16, kernel_size=3, padding=1)self.conv2 = nn.Conv2d(16, 32, kernel_size=3, padding=1)# Define the pooling and dropout layersself.pool = nn.MaxPool2d(2, 2)self.dropout1 = nn.Dropout(0.25)self.dropout2 = nn.Dropout(0.5)# Define the fully connected layersself.fc1 = nn.Linear(32 * 7 * 7, 128)self.fc2 = nn.Linear(128, 10)def forward(self, x):# Pass the input through the convolutional layersx = self.conv1(x)x = self.pool(x)x = self.dropout1(x)x = self.conv2(x)x = self.pool(x)x = self.dropout2(x)# Reshape the output for the fully connected layersx = x.view(-1, 32 * 7 * 7)# Pass the output through the fully connected layersx = self.fc1(x)x = self.fc2(x)# Return the final outputreturn x# Load the MNIST dataset
train_dataset = MNIST("./data", train=True, download=True, transform=ToTensor())
test_dataset = MNIST("./data", train=False, download=True, transform=ToTensor())# Define the data loaders
train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=64, shuffle=False)# Define the model
model = HandwritingRecognitionModel().to(device)# Define the loss function and optimizer
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)from time import time 
t0 = time()
# Train the model for 10 epochs
for epoch in range(10):# Set the model to training modemodel.train()# Iterate over the training datafor images, labels in train_loader:images, labels = images.to(device), labels.to(device)# Pass the input through the modeloutputs = model(images)# Compute the lossloss = loss_fn(outputs, labels)# Backpropagate the errorloss.backward()# Update the model parametersoptimizer.step()# Set the model to evaluation modemodel.eval()# Evaluate the model on the validation setwith torch.no_grad():correct = 0total = 0for images, labels in test_loader:images, labels = images.to(device), labels.to(device)# Pass the input through the modeloutputs = model(images)# Get the predicted labels_, predicted = torch.max(outputs.data, 1)# Update the total and correct countstotal += labels.size(0)correct += (predicted == labels).sum()# Print the accuracyprint(f"Epoch {epoch + 1}: Accuracy = {100 * correct / total:.2f}%")t1 =time()
print("10 epoch cost {}s".format(t1-t0))

结果如下
在这里插入图片描述

M2_MPS.py

import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision.datasets import MNIST
from torchvision.transforms import ToTensorprint(f"PyTorch version: {torch.__version__}")# Check PyTorch has access to MPS (Metal Performance Shader, Apple's GPU architecture)
print(f"Is MPS (Metal Performance Shader) built? {torch.backends.mps.is_built()}")
print(f"Is MPS available? {torch.backends.mps.is_available()}")# Set the device
device = "mps" if torch.backends.mps.is_available() else "cpu"
device = torch.device(device)
print(f"Using device: {device}")# Define the CNN model
class HandwritingRecognitionModel(nn.Module):def __init__(self):super().__init__()# Define the convolutional layersself.conv1 = nn.Conv2d(1, 16, kernel_size=3, padding=1)self.conv2 = nn.Conv2d(16, 32, kernel_size=3, padding=1)# Define the pooling and dropout layersself.pool = nn.MaxPool2d(2, 2)self.dropout1 = nn.Dropout(0.25)self.dropout2 = nn.Dropout(0.5)# Define the fully connected layersself.fc1 = nn.Linear(32 * 7 * 7, 128)self.fc2 = nn.Linear(128, 10)def forward(self, x):# Pass the input through the convolutional layersx = self.conv1(x)x = self.pool(x)x = self.dropout1(x)x = self.conv2(x)x = self.pool(x)x = self.dropout2(x)# Reshape the output for the fully connected layersx = x.view(-1, 32 * 7 * 7)# Pass the output through the fully connected layersx = self.fc1(x)x = self.fc2(x)# Return the final outputreturn x# Load the MNIST dataset
train_dataset = MNIST("./data", train=True, download=True, transform=ToTensor())
test_dataset = MNIST("./data", train=False, download=True, transform=ToTensor())# Define the data loaders
train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True)
test_loader = DataLoader(test_dataset, batch_size=64, shuffle=False)# Define the model
model = HandwritingRecognitionModel().to(device)# Define the loss function and optimizer
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)from time import time 
t0 = time()
# Train the model for 10 epochs
for epoch in range(10):# Set the model to training modemodel.train()# Iterate over the training datafor images, labels in train_loader:images, labels = images.to(device), labels.to(device)# Pass the input through the modeloutputs = model(images)# Compute the lossloss = loss_fn(outputs, labels)# Backpropagate the errorloss.backward()# Update the model parametersoptimizer.step()# Set the model to evaluation modemodel.eval()# Evaluate the model on the validation setwith torch.no_grad():correct = 0total = 0for images, labels in test_loader:images, labels = images.to(device), labels.to(device)# Pass the input through the modeloutputs = model(images)# Get the predicted labels_, predicted = torch.max(outputs.data, 1)# Update the total and correct countstotal += labels.size(0)correct += (predicted == labels).sum()# Print the accuracyprint(f"Epoch {epoch + 1}: Accuracy = {100 * correct / total:.2f}%")t1 =time()
print("10 epoch cost {}s".format(t1-t0))

结果如下
在这里插入图片描述

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/101725.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

antd Form shouldUpdate 关联展示 form 数组赋值

form 数组中嵌套数值更新 注意:数组是引用类型 项目需求,表单中包含多个产品信息,使用form.list 数组嵌套,提货方式如果是邮寄展示地址,如果是自提,需要在该条目中增加两项 代码如下:// An hi…

acwing算法基础之基础算法--双指针算法

目录 1 知识点2 模板 1 知识点 双指针算法的核心思想&#xff1a; for (int i 0; i < n; i) {for (int j 0; j < m; j) {//do somethings} }利用某些性质&#xff08;比如单调性&#xff09;&#xff0c;将上面朴素算法优化到 O ( N ) O(N) O(N)。 以输出空格间隔的…

Nacos(替代Eureka)注册中心

Nacos初步学习 Nacos 是一个开源的服务注册和配置中心&#xff0c;它允许您注册、注销和发现服务实例&#xff0c;并提供了配置管理的功能。下面是Nacos的最基础用法&#xff1a; 1. 服务注册和发现&#xff1a; 首先&#xff0c;您需要将您的应用程序或服务注册到Nacos中。…

黑马JVM总结(三十一)

&#xff08;1&#xff09;类加载器-概述 启动类加载器-扩展类类加载器-应用程序类加载器 双亲委派模式&#xff1a; 类加载器&#xff0c;加载类的顺序是先依次请问父级有没有加载&#xff0c;没有加载自己才加载&#xff0c;扩展类加载器在getParent的时候为null 以为Boots…

《设计一款2轮车充电桩系统》

以深圳为例&#xff0c;深圳有400万台电动2轮车&#xff0c;以每个月电费20元计算&#xff0c;深圳每个月用在2轮车充电上的费用为8000万左右。1年10个亿的市场规模。 前景可观&#xff0c;竞争也非常激烈。 本文主要讨论技术实现方案。 方法&#xff1a; 24v/36v直流输出 需…

接口自动化测试 —— 协议、请求流程

一、架构 CRM客户关系管理系统 SAAS Software As A Service 软件即服务 PAAS Platform AS A Service 平台即服务 快速交付→ 快&#xff1a;自己去干、有结果、事事有回音、持续改进 单体架构——》垂直架构——》面向服务架构——》微服务架构&#xff08;分布式&#xf…

MyBatis动态SQL(if、choose、when和otherwise)标签

动态 SQL 是 MyBatis 的强大特性之一。在 JDBC 或其它类似的框架中&#xff0c;开发人员通常需要手动拼接 SQL 语句。根据不同的条件拼接 SQL 语句是一件极其痛苦的工作。例如&#xff0c;拼接时要确保添加了必要的空格&#xff0c;还要注意去掉列表最后一个列名的逗号。而动态…

C#(Csharp)我的基础教程(四)(我的菜鸟教程笔记)-Windows项目结构分析、UI设计和综合事件应用的探究与学习

目录 windows项目是我们.NET学习一开始必备的内容。 1、窗体类&#xff08;主代码文件窗体设计器后台代码文件&#xff09; 主窗体对象的创建&#xff1a;在Program类里面&#xff1a; Application.Run(new FrmMain());这句代码就决定了&#xff0c;当前窗体是项目的主窗体。…

Vuex基础使用存取值+异步请求

一.Vuex简介 vuex是什么&#xff1f; Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态&#xff0c;并以相应的规则保证状态以一种可预测的方式发生变化。 什么情况使用 Vuex&#xff1f; Vuex 可以帮助我们管理共享状态&#…

阿里云域名免费配置HTTPS

阿里云域名配置HTTPS - 知乎

C++学习——new 和 delete 运算符简介

以下内容源于C语言中文网的学习与整理&#xff0c;非原创&#xff0c;如有侵权请告知删除。 在C语言中&#xff0c;动态地分配内存用 malloc() 函数&#xff0c;释放内存用 free() 函数。如下所示&#xff1a; int* p(int*)malloc(sizeof(int)*10);//分配10个int型的内存空间f…

jwttoken+redis+springsecurity

思路 jwttoken不设置过期时间 redis管理过期时间&#xff0c;并且续签 redis中key"login:"userId, valuejwtUser 再次访问时&#xff0c;解析token中userId&#xff0c;并且根据过期时间自动续签JWT 实现登录认证 Token 自动续期方案 pom文件配置 <!--Redis--&…

XLSX json转文本流 json转文件

封装一个公共 xlsx.js import { read, utils, writeFile } from xlsx // 文本流转json // 入参&#xff1a;文本流 回调 入参{} export const readJsonFromFile (file, callBackFn, opt) > {const reader new FileReader()reader.readAsArrayBuffer(file)reader.onload …

vue原生实现element上传多张图片浏览删除

vue原生实现element上传多张图片浏览删除 <div class"updata-component" style"width:100%;"><div class"demo-upload-box clearfix"><div class"demo-upload-image-box" v-if"imageUrlArr && imageUrlAr…

点云从入门到精通技术详解100篇-点云特征学习模型及其在配准中的应用(续)

目录 基于局部邻域的点云特征学习模型 3.1引言 3.2自适应邻域选择算法

算法-动态规划-编辑距离

算法-动态规划-编辑距离 1 题目概述 1.1 题目出处 https://leetcode.cn/problems/longest-increasing-subsequence/ 1.2 题目描述 2 动态规划 2.1 思路 dp[i][j] 表示 word1[0,i) 变换为 word2[0,j)的最少步数&#xff0c;那么转移表达式&#xff1a; i和j上的字符相同时…

[网鼎杯 2018]Comment git泄露 / 恢复 二次注入 .DS_Store bash_history文件查看

首先我们看到账号密码有提示了 我们bp爆破一下 我首先对数字爆破 因为全字符的话太多了 爆出来了哦 所以账号密码也出来了 zhangwei zhangwei666 没有什么用啊 扫一下吧 有git git泄露 那泄露看看 真有 <?php include "mysql.php"; session_start(); if(…

子层连接结构

目录 1、子层连接结构介绍 2、子层连接结构 3、代码实现 1、子层连接结构介绍 输入到每个子层以及规范化层的过程中&#xff0c;还使用了残差连接&#xff08;跳跃连接&#xff09;&#xff0c;因此我们把这一部分整体结构叫子层连接&#xff08;代表子层及其连接结构&#xf…

常见Http请求形式

一、请求参数的类型 我们在做boot项目时&#xff0c;常常会向接口发起请求&#xff0c;有些请求需要附带一些参数&#xff0c;比如说分页查询&#xff0c;就需要带上pageNum(当前页)和pageSize(页面大小)等参数 有两种方式可以传递这样的参数 query类型&#xff0c;参数通过…

Spring面试题

一、Spring面试题 1、Bean的生命周期 1.调用bean的构造方法创建Bean 2.通过反射调用Set方法设 bean的属性 3.如果Bean 实现了实现了BeanNameAware接口&#xff0c;Spring将调用setBeanName()&#xff0c;设置 Bean的name 4.如果Bean实现了BeanFactoryAware接口&#xff0c…