file - 如何将 .npy 文件作为 numpy 数组加载到 Google Colab 上的虚拟机中

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

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

我已将 train.npy 和 train_labels.npy 保存在我的 Google 云端硬盘中。

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

最佳答案

解决了。

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

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)

关于file - 如何将 .npy 文件作为 numpy 数组加载到 Google Colab 上的虚拟机中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48801379/

相关文章:

performance - 为什么 numpy.dot 与矩阵乘法的这些 GPU 实现一样快?

image - Keras 实时增强添加噪声和对比度

java - 使用与该平面文件的多个连接将 30GB 的平面文本文件通过 Internet 导入本地文件系统?

file - 创建新的文件类型

Python,如何删除文件中的工作?

python - 在 Python 中更改文件头的有效方法

python - 如何将数据框拆分为 x 和 y

python - 将 pandas 字符串数据帧转换为 numpy int 数组

java - 如何在 Java 中创建模糊逻辑规则或模型

perl - 了解元素的顺序