如何在Google Colab的虚拟机中将.npy文件加载为numpy数组

我有一些数据集和标签,它们基本上是带有.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(文件系统中的路径)

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注