记录安装pytorch的问题与解决

pytorch的简介

PyTorch既可以看作加入了GPU支持的numpy,同时也可以看成一个拥有自动求导功能的强大的深度神经网络。pytorch百度百科
它是一个基于Python的可续计算包,提供两个高级功能:1、具有强大的GPU加速的张量计算(如NumPy)。2、包含自动求导系统的的深度神经网络。

出现的问题以及解决过程记录

-直接使用pip安装:pip install torch
出现的问题是:Running setup.py install for torch ... error
pip出错截图

-使用官网下载的whl包
网址:https://download.pytorch.org/whl/torch_stable.html
在这里要注意版本信息:
cu92: cuda9.2
torch-1.4.0 : torch版本 1.4.0
cp37 : python版本3.7
win: windows 系统
我下载的是:

https://www.vocabulary.com/lists/6978474
cu102/torchvision-0.7.0-cp38-cp38-win_amd64.whl
cu102/torch-1.6.0-cp38-cp38-win_amd64.whl

https://www.vocabulary.com/lists/6978666

在使用pip安装时再次报错:
torch-1.6.0-cp38-cp38-win_amd64.whl is not a supported wheel on this platform.
此次报错是pip不支持改文件名称,百度之后发现可以通过查看pip支持的文件名格式,改名解决问题。

import pip
print(pip.pep425tags.get_supported())
  • 1
  • 2

运行完之后报错:AttributeError: module 'pip' has no attribute 'pep425tags'
再次查找资料,提示64位应该使用:

import pip._internal
print(pip._internal.pep.get_supported())
  • 1
  • 2

运行之后仍然报错:AttributeError: module 'pip._internal' has no attribute 'pep425tags'
最后使用了另一个命令查看:

import wheel.pep425tags as w
print(w.get_supported())
#如果第二句报错,使用:
#print(w.get_supported("win_amd64"))

得到结果:

[('cp37', 'cp37m', 'win_amd64'), ('cp37', 'none', 'win_amd64'), ('cp37', 'none', 'any'), ('cp3', 'none', 'any'), ('cp36', 'none', 'any'), ('cp35', 'none', 'any'), ('cp34', 'none', 'any'), ('cp33', 'none', 'any'), ('cp32', 'none', 'any'), ('cp31', 'none', 'any'), ('cp30', 'none', 'any'), ('py3', 'none', 'win_amd64'), ('py37', 'none', 'any'), ('py3', 'none', 'any'), ('py36', 'none', 'any'), ('py35', 'none', 'any'), ('py34', 'none', 'any'), ('py33', 'none', 'any'), ('py32', 'none', 'any'), ('py31', 'none', 'any'), ('py30', 'none', 'any')]
  • 1

使用这种方法改完名字之后,还是error,无奈,只能换!!!!!

  • 使用Anaconda Prompt的conda命令安装
    百度是个好地方,找到方法→win10从零安装配置pytorch全过程图文详解文章已经介绍的很不错了,步骤也很全。但是我又双叒叕出错了,记录一下:
    打开anaconda prompt之后,运行命令都是Solving environment: failed,使用更新命令conda update -n base conda也是报错Solving environment: failed,后来还是度娘指导了我:https://www.vocabulary.com/lists/6978759通过在anaconda cmd中输入“conda config --show-sources"找到.condac文件,将以下内容粘贴:
channels:
  - defaults
show_channel_urls: true
channel_alias: https://mirrors.tuna.tsinghua.edu.cn/anaconda
default_channels:
  - https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/main
  - https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/free
  - https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/r
  - https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/pro
  - https://mirrors.tuna.tsinghua.edu.cn/anaconda/pkgs/msys2
custom_channels:
  conda-forge: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
  msys2: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
  bioconda: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
  menpo: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
  pytorch: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud
  simpleitk: https://mirrors.tuna.tsinghua.edu.cn/anaconda/cloud

后来实践证明,这一步要在win10从零安装配置pytorch全过程图文详解之前做完,因为教程内部的命令会更改.condac文件的配置内容。方法参照:anaconda 报错之Solving environment: failed,完成这一步之后,就可以conda create -n your_env_name python = x.x,然后使用环境安装包了。

部分代码展示

(base) C:\Users\DELL>conda create -n pytorch python=3.8
Solving environment: done


==> WARNING: A newer version of conda exists. <==
  current version: 4.5.11
  latest version: 4.8.4

Please update conda by running

    $ conda update -n base -c defaults conda



## Package Plan ##

  environment location: E:\SOFT\Anaconda\envs\pytorch

  added / updated specs:
    - python=3.8


The following packages will be downloaded:

    package                    |            build
    ---------------------------|-----------------
    wincertstore-0.2           |           py38_0          15 KB  defaults
    zlib-1.2.11                |       h62dcd97_4         132 KB  defaults
    wheel-0.35.1               |             py_0          36 KB  defaults
    python-3.8.5               |       h5fd99cc_1        18.7 MB  defaults
    certifi-2020.6.20          |           py38_0         160 KB  defaults
    sqlite-3.33.0              |       h2a8f88b_0         1.3 MB  defaults
    vs2015_runtime-14.16.27012 |       hf0eaf9b_3         2.4 MB  defaults
    openssl-1.1.1g             |       he774522_1         5.8 MB  defaults
    pip-20.2.2                 |           py38_0         2.0 MB  defaults
    ca-certificates-2020.7.22  |                0         164 KB  defaults
    setuptools-49.6.0          |           py38_0         958 KB  defaults
    ------------------------------------------------------------
                                           Total:        31.6 MB

The following NEW packages will be INSTALLED:

    ca-certificates: 2020.7.22-0            defaults
    certifi:         2020.6.20-py38_0       defaults
    openssl:         1.1.1g-he774522_1      defaults
    pip:             20.2.2-py38_0          defaults
    python:          3.8.5-h5fd99cc_1       defaults
    setuptools:      49.6.0-py38_0          defaults
    sqlite:          3.33.0-h2a8f88b_0      defaults
    vc:              14.1-h0510ff6_4        defaults
    vs2015_runtime:  14.16.27012-hf0eaf9b_3 defaults
    wheel:           0.35.1-py_0            defaults
    wincertstore:    0.2-py38_0             defaults
    zlib:            1.2.11-h62dcd97_4      defaults

Proceed ([y]/n)? y

选择yes

Downloading and Extracting Packages
wincertstore-0.2     | 15 KB     | ############################################################################ | 100%
zlib-1.2.11          | 132 KB    | ############################################################################ | 100%
wheel-0.35.1         | 36 KB     | ############################################################################ | 100%
python-3.8.5         | 18.7 MB   | ############################################################################ | 100%
certifi-2020.6.20    | 160 KB    | ############################################################################ | 100%
sqlite-3.33.0        | 1.3 MB    | ############################################################################ | 100%
vs2015_runtime-14.16 | 2.4 MB    | ############################################################################ | 100%
openssl-1.1.1g       | 5.8 MB    | ############################################################################ | 100%
pip-20.2.2           | 2.0 MB    | ############################################################################ | 100%
ca-certificates-2020 | 164 KB    | ############################################################################ | 100%
setuptools-49.6.0    | 958 KB    | ############################################################################ | 100%
Preparing transaction: done
Verifying transaction: done
Executing transaction: done
#
# To activate this environment, use
#
#     $ conda activate pytorch
#
# To deactivate an active environment, use
#
#     $ conda deactivate


(base) C:\Users\DELL>conda activate pytorch

(pytorch) C:\Users\DELL>

做到这一步是代表conda create -n your_env_name python = x.x成功,接下来按照win10从零安装配置pytorch全过程图文详解继续做,根绝自己的电脑配置来。

Downloading and Extracting Packages
vs2015_runtime-14.16 | 2.4 MB    | ############################################################################ | 100%
libssh2-1.9.0        | 218 KB    | ############################################################################ | 100%
mkl-service-2.3.0    | 200 KB    | ############################################################################ | 100%
conda-package-handli | 678 KB    | ############################################################################ | 100%
pytorch-1.6.0        | 175.8 MB  | ############################################################################ | 100%
mkl_random-1.1.0     | 270 KB    | ################################################################################################################################################# | 100%
sqlite-3.33.0        | 1.3 MB    | ################################################################################################################################################# | 100%
conda-4.8.4          | 3.1 MB    | ################################################################################################################################################# | 100%
certifi-2020.6.20    | 160 KB    | ################################################################################################################################################# | 100%
numpy-base-1.19.1    | 4.9 MB    | ################################################################################################################################################# | 100%
mkl_fft-1.1.0        | 132 KB    | ################################################################################################################################################# | 100%
pycurl-7.43.0.5      | 69 KB     | ################################################################################################################################################# | 100%
libcurl-7.71.1       | 289 KB    | ################################################################################################################################################# | 100%
curl-7.43.0          | 292 KB    | ################################################################################################################################################# | 100%
numpy-1.19.1         | 21 KB     | ################################################################################################################################################# | 100%
qt-5.9.7             | 92.3 MB   | ################################################################################################################################################# | 100%
cryptography-3.1     | 592 KB    | ################################################################################################################################################# | 100%
krb5-1.18.2          | 848 KB    | ################################################################################################################################################# | 100%
Preparing transaction: done
Verifying transaction: done
Executing transaction: done
  • 1

安装完成Torch之后,需要在pycharm中配置(pycharm与anaconda共享库),https://www.vocabulary.com/lists/6978925配置完成之后,导包import torch不出错则成功。方法参考大概步骤如下:
在这里插入图片描述
最后可检查导入

import torch
  • 1

… …

希望对翻到的你有所帮助,也欢迎补充学习

  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,这是一个使用 PyTorch 实现的示例代码,其中包括两个神经网络模型来解决椭圆形界面问题: ```python import torch from torch import nn, optim from torch.utils.data import DataLoader, Dataset import numpy as np import matplotlib.pyplot as plt # 定义一个椭圆形界面的数据集 class EllipseDataset(Dataset): def __init__(self, num_samples=1000, noise=0.05): super().__init__() self.num_samples = num_samples self.noise = noise # 生成随机的椭圆的参数 self.a = np.random.uniform(0.5, 1.5) self.b = np.random.uniform(0.5, 1.5) self.theta = np.random.uniform(0, 2*np.pi) self.center = np.random.uniform(-1, 1, size=2) # 生成随机的样本点 x = np.random.uniform(-2, 2, size=(self.num_samples, 2)) y = ((x[:, 0] - self.center[0]) * np.cos(self.theta) + (x[:, 1] - self.center[1]) * np.sin(self.theta)) ** 2 / self.a ** 2 + ((x[:, 0] - self.center[0]) * np.sin(self.theta) - (x[:, 1] - self.center[1]) * np.cos(self.theta)) ** 2 / self.b ** 2 y += np.random.normal(scale=self.noise, size=y.shape) self.data = torch.from_numpy(np.hstack([x, y.reshape(-1, 1)])).float() def __getitem__(self, index): return self.data[index] def __len__(self): return self.num_samples # 定义一个简单的全连接神经网络模型 class SimpleNet(nn.Module): def __init__(self): super().__init__() self.fc1 = nn.Linear(2, 64) self.fc2 = nn.Linear(64, 32) self.fc3 = nn.Linear(32, 1) def forward(self, x): x = nn.functional.relu(self.fc1(x)) x = nn.functional.relu(self.fc2(x)) x = self.fc3(x) return x # 定义一个深度神经网络模型 class DeepNet(nn.Module): def __init__(self): super().__init__() self.fc1 = nn.Linear(2, 64) self.fc2 = nn.Linear(64, 64) self.fc3 = nn.Linear(64, 64) self.fc4 = nn.Linear(64, 1) def forward(self, x): x = nn.functional.relu(self.fc1(x)) x = nn.functional.relu(self.fc2(x)) x = nn.functional.relu(self.fc3(x)) x = self.fc4(x) return x # 训练模型 def train(model, train_loader, criterion, optimizer, num_epochs=100): losses = [] for epoch in range(num_epochs): epoch_loss = 0 for batch in train_loader: optimizer.zero_grad() output = model(batch[:, :2]) loss = criterion(output, batch[:, 2:]) loss.backward() optimizer.step() epoch_loss += loss.item() epoch_loss /= len(train_loader) losses.append(epoch_loss) print(f"Epoch {epoch+1}/{num_epochs}, Loss: {epoch_loss}") return losses # 生成数据集 train_dataset = EllipseDataset(num_samples=1000, noise=0.05) train_loader = DataLoader(train_dataset, batch_size=32, shuffle=True) # 定义模型和优化器 simple_net = SimpleNet() deep_net = DeepNet() criterion = nn.MSELoss() simple_optimizer = optim.Adam(simple_net.parameters(), lr=0.01) deep_optimizer = optim.Adam(deep_net.parameters(), lr=0.01) # 训练简单的全连接神经网络模型 simple_losses = train(simple_net, train_loader, criterion, simple_optimizer, num_epochs=50) # 训练深度神经网络模型 deep_losses = train(deep_net, train_loader, criterion, deep_optimizer, num_epochs=50) # 画出损失函数曲线 plt.plot(simple_losses, label="Simple Net") plt.plot(deep_losses, label="Deep Net") plt.legend() plt.xlabel("Epoch") plt.ylabel("Loss") plt.show() # 画出椭圆形界面和模型预测的分割线 x = np.linspace(-2, 2, num=100) y = np.linspace(-2, 2, num=100) xx, yy = np.meshgrid(x, y) z_simple = simple_net(torch.from_numpy(np.hstack([xx.reshape(-1, 1), yy.reshape(-1, 1)])).float()).detach().numpy().reshape(xx.shape) z_deep = deep_net(torch.from_numpy(np.hstack([xx.reshape(-1, 1), yy.reshape(-1, 1)])).float()).detach().numpy().reshape(xx.shape) fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(10, 5)) ax1.contourf(xx, yy, (xx - train_dataset.center[0])**2 / train_dataset.a**2 + (yy - train_dataset.center[1])**2 / train_dataset.b**2, levels=20, cmap=plt.cm.Blues) ax1.set_title("Ellipse") ax2.contourf(xx, yy, z_simple, levels=20, cmap=plt.cm.Blues) ax2.set_title("Simple Net") fig.tight_layout() plt.show() fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(10, 5)) ax1.contourf(xx, yy, (xx - train_dataset.center[0])**2 / train_dataset.a**2 + (yy - train_dataset.center[1])**2 / train_dataset.b**2, levels=20, cmap=plt.cm.Blues) ax1.set_title("Ellipse") ax2.contourf(xx, yy, z_deep, levels=20, cmap=plt.cm.Blues) ax2.set_title("Deep Net") fig.tight_layout() plt.show() ``` 在这个示例代码中,我们定义了一个 `EllipseDataset` 类来生成一个随机的椭圆形界面数据集。我们还定义了两个神经网络模型,一个是简单的全连接神经网络模型,另一个是深度神经网络模型。我们使用均方误差作为损失函数,使用 Adam 优化器进行优化。 我们首先训练了简单的全连接神经网络模型,然后训练了深度神经网络模型。在训练过程中,我们记录了每个 epoch 的损失函数值,最后画出损失函数曲线。最后,我们将椭圆形界面和两个模型预测的分割线画出来,以便比较它们的效果。 请注意,这个示例代码只是一个简单的示例,用于演示如何使用 PyTorch 实现解决椭圆形界面问题的神经网络模型。您可以根据您的实际需求进行修改和改进。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值