[英]Import custom modules in Amazon Sagemaker Jupyter notebook
I want to import a custom module in my jupyter notebook in Sagemaker.我想在 Sagemaker 的 jupyter 笔记本中导入自定义模块。 Trying the import from Untitled1.ipynb I have tried two different structures.尝试从 Untitled1.ipynb 导入我尝试了两种不同的结构。 The first one is:第一个是:
Inside "package folder" there were the files "cross_validation.py" and " init .py".在“包文件夹”中有文件“cross_validation.py”和“ init .py”。 The followings commands have been tried:已经尝试了以下命令:
from package import cross_validation
import package.cross_validation
The second one is第二个是
and I have coded import cross_validation
我已经编码了import cross_validation
In both cases I get no error at all when importing, but I can't use the class inside the module because I receive the error name Class_X is not defined
在这两种情况下,导入时我都没有收到任何错误,但我无法在模块内使用该类,因为我收到错误名称Class_X is not defined
I also have restarted the notebook, just in case and it still not working.我也重新启动了笔记本,以防万一,它仍然无法正常工作。 How could I make it?我怎么能做到?
If you also need to import files from parent directories you can add to the path as such:如果您还需要从父目录导入文件,您可以添加到路径中:
import os
import sys
module_path = "/home/ec2-user/SageMaker/{module_name}"
if module_path not in sys.path:
sys.path.append(module_path)
Then you can import as if you were in a normal python environment from the root of your project然后你可以像在普通的 python 环境中一样从项目的根目录导入
You can add a __init__.py
file to your package
directory to make it a Python package.您可以将__init__.py
文件添加到您的package
目录中以使其成为 Python 包。 Then you will be import the modules from the package inside your Jupyter notebook然后,您将从 Jupyter 笔记本内的包中导入模块
/home/ec2-user/SageMaker
-- Notebook.ipynb
-- mypackage
-- __init__.py
-- mymodule.py
Contents of Notebook.ipynb Notebook.ipynb 的内容
from mypackage.mymodule import SomeClass, SomeOtherClass
For more details, see https://docs.python.org/3/tutorial/modules.html#packages有关更多详细信息,请参阅https://docs.python.org/3/tutorial/modules.html#packages
Thanks for using Amazon SageMaker!感谢您使用 Amazon SageMaker!
If you use SageMaker Studio, you need to take care about the path.如果您使用 SageMaker Studio,则需要注意路径。
In the notebook of SageMaker Studio :在SageMaker Studio的笔记本中:
!df -h
, You will see the line: !df -h
,您将看到以下行:
127.0.0.1:/200005 8.0E 1.3G 8.0E 1% /root
And !pwd
will be: !pwd
将是:
/root
It is different from the bash terminal :它与bash 终端不同:
In bash terminal:在 bash 终端中:
df -h
127.0.0.1:/200005 8.0E 1.4G 8.0E 1% /home/sagemaker-user
pwd
/home/sagemaker-user
So, the outside file path "/home/sagemaker-user" will be mapped into "/root" in your notebooks under SageMaker Studio.因此,外部文件路径“/home/sagemaker-user”将映射到 SageMaker Studio 下笔记本中的“/root”。
So, the module path will change:因此,模块路径将更改:
import sys
sys.path.append('/root/module_name')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.