赞
踩
windows、linux先安装以上三个
现在大部分的深度学习环境以及包都是通过yaml或者reqirement.txt或者venv傻瓜式安装,
这样的好处则是可以将环境隔离开来 互不干扰,缺点就是占用空间大。
具体的安装过程后续再更,网上成熟的教程也较多
傻瓜式安装
出现Would you like conda to send this report to the core maintainers? [y/N]: 这种问题
请安装anaconda对应的cuda版本,以上问题是我直接下载最新的版本出现的问题,
https://blog.csdn.net/Ever_____/article/details/127379785
conda create -n dl python=3.7
注意断开vpn
查看环境
conda env list
conda activate dl
pip install torch1.9.1+cu111 torchvision0.10.1+cu111 torchaudio==0.9.1 -f https://download.pytorch.org/whl/torch_stable.html --default-timeout=300 坑壁,尽可能的设置延时,不然下载要完成时 提示timeout,浪费劳资流量
pycharm设置虚拟环境时,找不到环境,解决:先使用系统环境,然后切换conda环境:如下链接
https://blog.csdn.net/kaigemime/article/details/132531737
anaconda版本
Anaconda3-2020.11-Windows-x86_64
cuda版本
11.1
cudnn版本
8.9
python版本
3.7
import argparse import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torchvision import datasets, transforms class Net(nn.Module): def __init__(self): super(Net, self).__init__() self.conv1 = nn.Conv2d(1, 20, 5, 1) self.conv2 = nn.Conv2d(20, 50, 5, 1) self.fc1 = nn.Linear(4 * 4 * 50, 500) self.fc2 = nn.Linear(500, 10) def forward(self, x): x = F.relu(self.conv1(x)) x = F.max_pool2d(x, 2, 2) x = F.relu(self.conv2(x)) x = F.max_pool2d(x, 2, 2) x = x.view(-1, 4 * 4 * 50) x = F.relu(self.fc1(x)) x = self.fc2(x) return F.log_softmax(x, dim=1) def train(args, model, device, train_loader, optimizer, epoch): model.train() for batch_idx, (data, target) in enumerate(train_loader): data, target = data.to(device), target.to(device) optimizer.zero_grad() output = model(data) loss = F.nll_loss(output, target) loss.backward() optimizer.step() if batch_idx % args.log_interval == 0: print('Train Epoch: {} [{}/{} ({:.0f}%)]\tLoss: {:.6f}'.format( epoch, batch_idx * len(data), len(train_loader.dataset), 100. * batch_idx / len(train_loader), loss.item())) def test(args, model, device, test_loader): model.eval() test_loss = 0 correct = 0 with torch.no_grad(): for data, target in test_loader: data, target = data.to(device), target.to(device) output = model(data) test_loss += F.nll_loss(output, target, reduction='sum').item() # sum up batch loss pred = output.argmax(dim=1, keepdim=True) # get the index of the max log-probability correct += pred.eq(target.view_as(pred)).sum().item() test_loss /= len(test_loader.dataset) print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format( test_loss, correct, len(test_loader.dataset), 100. * correct / len(test_loader.dataset))) def main(): parser = argparse.ArgumentParser(description='PyTorch MNIST Example') parser.add_argument('--batch-size', type=int, default=64, metavar='N', help='input batch size for training (default: 64)') parser.add_argument('--test-batch-size', type=int, default=1000, metavar='N', help='input batch size for testing (default: 1000)') parser.add_argument('--epochs', type=int, default=10, metavar='N', help='number of epochs to train (default: 10)') parser.add_argument('--lr', type=float, default=0.01, metavar='LR', help='learning rate (default: 0.01)') parser.add_argument('--momentum', type=float, default=0.5, metavar='M', help='SGD momentum (default: 0.5)') parser.add_argument('--no-cuda', action='store_true', default=False, help='disables CUDA training') parser.add_argument('--seed', type=int, default=1, metavar='S', help='random seed (default: 1)') parser.add_argument('--log-interval', type=int, default=10, metavar='N', help='how many batches to wait before logging training status') parser.add_argument('--save-model', action='store_true', default=False, help='For Saving the current Model') args = parser.parse_args() use_cuda = not args.no_cuda and torch.cuda.is_available() torch.manual_seed(args.seed) device = torch.device("cuda" if use_cuda else "cpu") kwargs = {'num_workers': 1, 'pin_memory': True} if use_cuda else {} train_loader = torch.utils.data.DataLoader( datasets.MNIST('../data', train=True, download=False, transform=transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,)) ])), batch_size=args.batch_size, shuffle=True, **kwargs) test_loader = torch.utils.data.DataLoader( datasets.MNIST('../data', train=False, transform=transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,)) ])), batch_size=args.test_batch_size, shuffle=True, **kwargs) model = Net().to(device) optimizer = optim.SGD(model.parameters(), lr=args.lr, momentum=args.momentum) for epoch in range(1, args.epochs + 1): train(args, model, device, train_loader, optimizer, epoch) test(args, model, device, test_loader) if (args.save_model): torch.save(model.state_dict(), "mnist_cnn.pt") if __name__ == '__main__': main()
https://allentdan.github.io/2020/12/16/pytorch%E9%83%A8%E7%BD%B2torchscript%E7%AF%87/
假设两台windows都装了conda,命名为A和B,A中有虚拟环境py370,现在要将py370迁移到B中,假设B中的anaconda已经装好。
将A中的py370铐到B中的env路径下
查看B中的env下的py370中的conda-meta文件,
该文件夹下有较多的json文件,点开任意一个.json查看可以发现
“link”: {
“source”: “D:\anaconda\pkgs\ca-certificates-2022.10.11-h06a4308_0”,
“type”: 1
},
将所有的.json文件中 ’D盘中安装anaconda路径‘ 替换为 ‘B中anaconda的安装目录‘ 即可,“pkgs以及pkgs之后的路径都不用修改,因此只需要用脚本检测
以下是修改所有json文件[“link”][“source”]的脚本,以将D盘换到E盘为例
import os
import json
folder_path = "path/to/folder" # 指定文件夹路径
for file_name in os.listdir(folder_path): # 遍历文件夹下所有文件
if file_name.endswith('.json'): # 筛选JSON文件
file_path = os.path.join(folder_path, file_name)
with open(file_path, 'r') as f: # 打开JSON文件
data = json.load(f) # 加载JSON数据
if 'link' in data and 'source' in data['link']: # 如果JSON数据中存在“link”键和“source”键
source_path = data['link']['source']
if source_path.startswith('D:\\Anaconda\\'): # 如果链接中包含指定的路径
data['link']['source'] = source_path.replace('D:\\Anaconda\\', 'E:\\Anaconda\\') # 修改路径
with open(file_path, 'w') as f: # 保存修改后的JSON数据
json.dump(data, f, indent=4)
https://blog.csdn.net/dickwinters2011/article/details/123511315
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。