我有一些数据集和标签,它们基本上是带有.npy扩展名的numpy保存文件。
我已经将train.npy和train_labels.npy保存到了我的Google Drive中。
在使用Google Colab时,我需要使用这些数据。我能够在我的驱动器中找到文件夹和数据文件的ID。我如何将这些数据文件加载到Google Colab使用的虚拟机的内存中?
回答:
已经解决了。
首先按照文档中说明的进行简单的认证
from pydrive.auth import GoogleAuthfrom pydrive.drive import GoogleDrivefrom google.colab import authfrom 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.npy')upload_data_system()
瞧!你的文件已经上传到文件系统中,并且可以像在本地一样使用简单的Python加载到内存中。为了验证,在Colab上运行这个代码。你应该能看到你的文件
import osfrom os import listdirfor f in os.listdir('.'): if os.path.isfile(f): print(f)
现在加载你的numpy文件,使用np.load(文件系统中的路径)