Google ML Engine中的环境配置

在使用ML Engine进行神经网络的训练时,需要先要对云服务器的环境进行配置。配置的方法总体有两种,一种是手动上传打包文件(tarballs),并将其路径作为训练输入添加;另外一种是将PyPI包添加进训练的包中,详细可以查看官方文档。ML Engine默认使用pip install安装所有依赖,因此首先需要确认需要添加的依赖是否在PyPI库里面。

手动添加包

将预先准备好的包放在项目(project)路径下,在提交训练任务时,使用–packages参数指明需要安装的包。

gcloud ml-engine jobs submit training my_job \
    --staging-bucket gs://my-bucket \
    --package-path /path/to/my/project/trainer \
    --module-name trainer.task \
    --packages dep1.tar.gz,dep2.whl

安装PyPI依赖

在训练项目的顶级目录下建立setup.py文件,调用setuptools.setup函数并声明所需的包及其版本,即可实现对ML Engine环境中包的安装和更新。setup.py文件的内容例如:

from setuptools import find_packages
from setuptools import setup

REQUIRED_PACKAGES = ['some_PyPI_package>=1.5',
                     'another_package==2.6']


setup(
    name='trainer',
    version='0.1',
    install_requires=REQUIRED_PACKAGES,
    packages=find_packages(),
    include_package_data=True,
    description='Generic example trainer package with dependencies.')

PyPI库中没有的包的安装

有时候,PyPI库中没有我们所需的包,例如在python3.5中,使用matplotlib时缺少python3-tk,而这个包在PyPI中是没有的,可以通过apt-get install来安装。这时就需要对setup.py文件进行修改,通过subprocess创建子进程进行安装。

# -*- coding: utf-8 -*-
"""
Created on Mon Jun 11 14:39:14 2018
@author: wz
"""

from setuptools import find_packages
from setuptools import setup
import logging
import subprocess
from setuptools.command.install import install

class CustomCommands(install):
  """A setuptools Command class able to run arbitrary commands."""

  def RunCustomCommand(self, command_list):
    print ('Running command: %s' % command_list)
    p = subprocess.Popen(
        command_list,
        stdin=subprocess.PIPE,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT)
    stdout_data, _ = p.communicate()
    print ('Command output: %s' % stdout_data)
    logging.info('Log command output: %s', stdout_data)
    if p.returncode != 0:
      raise RuntimeError('Command %s failed: exit code: %s' %
                         (command_list, p.returncode))

  def run(self):
    self.RunCustomCommand(['apt-get', 'update'])
    self.RunCustomCommand(
          ['apt-get', 'install', '-y', 'python3-tk'])

    install.run(self)

setup(
    name='trainer',
    version='0.1',
    packages=find_packages(),
    include_package_data=True,
    description='My trainer application package.',
    install_requires=[
      'keras',
      'h5py',
      'pandas',
      'numpy',
      'opencv-python',
      'matplotlib',
      'tqdm',
      'sklearn'
  ],
    cmdclass={
        # Command class instantiated and run during install scenarios.
        'install': CustomCommands,
    }
)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值