LoginSignup
1

More than 3 years have passed since last update.

AWSのLambdaLayersでpandasを使おうとしたらトラブった話

Last updated at Posted at 2019-10-19

記事概要

  • トラブルの内容
    • AWS Layersでpandasを使えるようにしたかった
    • numpyのインポートでエラー
  • 解決策
    • AmazonLinux2ではなくてAmazonLinuxを使う
    • Pythonのバージョンを合わせる

最近コンテナで開発環境を用意していたから、Pythonのバージョンに全然気を使っていなかった。

AWS Lambda Layersとは

これまでLambdaでnumpyやpandasを使おうとすると

  • AmazonLinuxインスタンスを用意
  • 利用するモジュールをpip install
  • Lambda関数の本体スクリプトと共にzipファイルにまとめる
  • AWSにアップロードする

デプロイパッケージを作成する必要があった。おまけにコンソールからスクリプトが見えないし、メンテナンスやデバッグもかなりめんどくさい。

それを解決するのがLayers機能。

AWS Lambda レイヤー - AWS Lambda

出てきたエラー

エラーメッセージは下記の通り。なんかnumpyがうまく動いてないらしい。

START RequestId: 7cf66e49-c9f4-48d3-8212-3b9279a8ee02 Version: $LATEST
Unable to import module 'lambda_function': 

IMPORTANT: PLEASE READ THIS FOR ADVICE ON HOW TO SOLVE THIS ISSUE!

Importing the multiarray numpy extension module failed.  Most
likely you are trying to import a failed build of numpy.
Here is how to proceed:
- If you're working with a numpy git repository, try `git clean -xdf`
  (removes all files not under version control) and rebuild numpy.
- If you are simply trying to use the numpy version that you have installed:
  your installation is broken - please reinstall numpy.
- If you have already reinstalled and that did not fix the problem, then:
  1. Check that you are using the Python you expect (you're using /var/lang/bin/python3.6),
     and that you have no directories in your PATH or PYTHONPATH that can
     interfere with the Python and numpy versions you're trying to use.
  2. If (1) looks fine, you can open a new issue at
     https://github.com/numpy/numpy/issues.  Please include details on:
     - how you installed Python
     - how you installed numpy
     - your operating system
     - whether or not you have multiple versions of Python installed
     - if you built from source, your compiler versions and ideally a build log

     Note: this error has many possible causes, so please don't comment on
     an existing issue about this - open a new one instead.

Original error was: /opt/python/numpy/core/_multiarray_umath.so: undefined symbol: _Py_ZeroStruct


END RequestId: 7cf66e49-c9f4-48d3-8212-3b9279a8ee02
REPORT RequestId: 7cf66e49-c9f4-48d3-8212-3b9279a8ee02  Duration: 0.51 ms   Billed Duration: 100 ms Memory Size: 128 MB Max Memory Used: 73 MB  Init Duration: 423.73 ms    

対処① AmazonLinux2ではなくてAmazonLinuxを使う

ここを見るとLambda関数はAmazonLinuxで動いているらしい。なのでzipファイルはAmazonLinuxのインスタンス上で用意しないといけない。

対処② Pythonのバージョンをlambda関数のランタイムと合わせる

最近はSageMakerで全て済ましてしまうのでうっかりしていたが、Linuxはpython2.7がデフォルトだ。
コンテナで環境構築すると最初からPython3になっていることが多いからね。

pyenvを導入してLambda関数側のpythonのバージョン(3.6)と合わせることで解決

参考

【サーバレス機械学習入門】AWS Lambda レイヤーの使い方 - Qiita

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1