【问题标题】:How to load a .npy file as a numpy array into the Virtual machine on Google Colab如何将 .npy 文件作为 numpy 数组加载到 Google Colab 上的虚拟机中
【发布时间】:2018-07-25 20:44:01
【问题描述】:

我有一些数据集和标签,它们基本上是 numpy 保存的文件,扩展名为 .npy。

我已将 train.npy 和 train_labels.npy 保存在我的谷歌驱动器中。

在使用 Google Colab 时,我必须使用这些数据。我能够在我的驱动器中找到文件夹和数据文件的 ID。如何将这些数据文件加载到 Google Colab 使用的虚拟机的内存中?

【问题讨论】:

    标签: file numpy machine-learning deep-learning google-colaboratory


    【解决方案1】:

    解决了。

    首先按照文档中的说明进行简单的身份验证

    from pydrive.auth import GoogleAuth
    from pydrive.drive import GoogleDrive
    from google.colab import auth
    from oauth2client.client import GoogleCredentials
    
    # 1. Authenticate and create the PyDrive client.
    auth.authenticate_user()
    gauth = GoogleAuth()
    gauth.credentials = GoogleCredentials.get_application_default()
    drive = GoogleDrive(gauth)
    

    如果您知道文件在驱动器上的文件名和文件夹 ID,我创建了一些帮助函数来获取文件 ID。文件夹 ID 是 drive.google.com/../../folders/ 中链接的最后一部分

    def get_file_from_drive(folder_id, file_name):
      file_list = drive.ListFile({'q': "'" + folder_id + "' in parents and 
    trashed=false"}).GetList()
      for file in file_list:
        if file['title'] == file_name:
          return file['id']
    
    def upload_file_to_drive(file_name, file_data):
      uploaded = drive.CreateFile({'title': file_name})
      uploaded.SetContentString(file_data)
      uploaded.Upload()
      print('Uploaded file with ID {}'.format(uploaded.get('id')))
    
    drive_folder_id = '<Folder ID>'
    

    此功能将文件从google drive上传到colab允许您使用的虚拟系统中。

    def upload_data_system():
      downloaded = drive.CreateFile({'id': get_file_from_drive(drive_folder_id, 'train.npy')})
      downloaded.GetContentFile('train.npy') 
    
      downloaded = drive.CreateFile({'id': get_file_from_drive(drive_folder_id, 'train_labels.npy')})
      downloaded.GetContentFile('train_labels.
    
    upload_data_system()
    

    维奥拉!您的文件已上传到文件系统,并且可以使用简单的 python 加载到内存中,就像在本地完成一样。要验证,请在 colab 上运行它。你应该看到你的文件

    import os
    from os import listdir
    
    for f in os.listdir('.'):
      if os.path.isfile(f):
        print(f)
    

    现在将您的 numpy 文件加载为 np.load(path_to_file_in_filesystem)

    【讨论】:

    • 感谢您的 sn-p。如果我使用的数据集不在我的本地机器上怎么办。我可以在安装了我的驱动器的情况下使用 colab 来下载数据集并将其保存在驱动器上的文件夹中吗?
    • 是的,您只需要一个简单的界面来与安装的外部驱动器进行交互。
    猜你喜欢
    • 2020-10-11
    • 2020-11-30
    • 2019-09-10
    • 1970-01-01
    • 2018-04-13
    • 1970-01-01
    • 1970-01-01
    • 2016-08-14
    • 2021-05-18
    相关资源
    最近更新 更多