简体   繁体   English

为什么我可以从 python 文件而不是笔记本运行我的 PyTorch 数据集文件?

[英]Why can I run my PyTorch dataset file from a python file but not a notebook?

I've written a custom dataset class in PyTorch in a file dataset.py and tried to test it by running the following code in my notebook with the following code:我在 dataset.py 文件中的 PyTorch 中编写了一个自定义数据集 class 并尝试通过在我的笔记本中使用以下代码运行以下代码来测试它:

from dataset import MyCustomDataset
from torch.utils.data import DataLoader

ds = MyCustomDataset("/Volumes/GoogleDrive/MyDrive/MyProject/data/train.pkl",target_type="labels")
dl = DataLoader(ds,batch_size = 16, shuffle = False)
X, y = next(iter(dl))
print(f"X: {X}, y: {y}")

After some unsuccessful troubleshooting, I tried running the exact same code in a file test.py, which worked without issues!在一些不成功的故障排除之后,我尝试在文件 test.py 中运行完全相同的代码,它没有问题!

Why can't I run this from my notebook?为什么我不能从我的笔记本上运行它?

For me, the problem is usually the pathing somehow, but in this case, all of the files, both.py, .ipynb and "data"-directory are in the same directory "MyProject".对我来说,问题通常是路径问题,但在这种情况下,所有文件,包括 .py、.ipynb 和“数据”目录都在同一个目录“MyProject”中。 I've tried with both absolute paths (as in the example) and with relative paths, but it's the same result in both cases.我尝试过使用绝对路径(如示例中所示)和相对路径,但两种情况下的结果相同。 I'm using vscode if that gives any insight.如果可以提供任何见解,我正在使用 vscode。

Furthermore, the error message in the notebook is "list indices must be integers or slices, not str", unfortunately, the prompt tells me the wrong lines (there's a comment on the line where the error's supposed to be).此外,笔记本中的错误消息是“列表索引必须是整数或切片,而不是 str”,不幸的是,提示告诉我错误的行(错误应该在的行上有注释)。 But if this is really an error, then it should not work in a python file either, right?但如果这真的是一个错误,那么它也不应该在 python 文件中工作,对吧?

Any help or suggestions are welcome!欢迎任何帮助或建议!

Try to check if there is any problem with the path试试看路径是否有问题

import os.path
from os import path
a= path.exists("/Volumes/GoogleDrive/MyDrive/MyProject/data/train.pkl")
print(a)

if it returns true it means path is not the issue and you need to provide more details in your question如果它返回 true,则表示路径不是问题,您需要在问题中提供更多详细信息

Jupyter and Python file has different cwd . Jupyter 和 Python 文件具有不同的cwd You can execute this to get the cwd :您可以执行此操作以获取cwd

import os
print(os.getcwd())

And you can add this in the settings.json file to modify the cwd of jupyter notebook to let it take the ${workspaceFolder} as the cwd like the python file does:您可以在 settings.json 文件中添加它来修改 jupyter notebook 的cwd ,让它像 python 文件一样将 ${workspaceFolder} 作为 cwd:

"jupyter.notebookFileRoot": "${workspaceFolder}",

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM