Using Kaggle Datasets in Google Colab
Is it possible to use any datasets available via the kaggle API in Google Colab? I see the Kaggle API is used in this Colab notebook, but it’s a bit unclear to me what datasets it provides access to.
13 Answers 13
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Create an API key in Kaggle.
To do this, go to kaggle.com/ and open your user settings page.
Next, scroll down to the API access section and click generate to download an API key. This will download a file called kaggle.json to your computer. You’ll use this file in Colab to access Kaggle datasets and competitions.
Navigate to https://colab.research.google.com/.
Upload your kaggle.json file using the following snippet in a code cell:
from google.colab import files files.upload()
Install the kaggle API using !pip install -q kaggle
Move the kaggle.json file into
/.kaggle , which is where the API client expects your token to be located:
/.kaggle !cp kaggle.json
Now you can access datasets using the client, e.g., !kaggle datasets list .
Here’s a complete example notebook of the Colab portion of this process: https://colab.research.google.com/drive/1DofKEdQYaXmDWBzuResXWWvxhLgDeVyl
This example shows uploading the kaggle.json file, the Kaggle API client, and using the Kaggle client to download a dataset.
/.kaggle/kaggle.json ]; then python "from google.colab import files \n files.upload()" && mkdir -p
/.kaggle && cp kaggle.json
You should be able to access any dataset on Kaggle via the API. In this example, only the datasets for competitions are being listed. You can see that datasets you can access with this command:
You can also search for datasets by adding the -s tag and then the search term you’re interested in. So this would give you a list of datasets about dogs:
You can find more information on the API and how to use it in the documentation here.
Hope that helps! 🙂
- Go to my account in your profile
- Scroll down, until you find an option Create new Api Token, this will download a file called kaggle.json
- Go to Colab upload the file kaggle.json
- pip install kaggle
- create a new folder named kaggle, copy kaggle.json into the kaggle folder, and set read-write permissions only for you(user).
6.Go to Kaggle website.For example, you want to download any data, click on the three dots in the right hand side of the screen. Then click copy API command
- Go to colab, paste the API command
8.When you do an !ls , you will see that our download is a zip file.
- To unzip the file use the following command
- Now, when you do !ls you’ll find our csv file is extracted from the zip file.
- To read the file perform a simple pd.read_csv , import pandas
12.As you see, we have successfully read our file into colab.
This downloads the kaggle dataset into google colab, where you can perform analysis and build amazing machine learning models or train neural networks.
Combined the top response to this Github gist as Colab Implementation. You can directly copy the code and use it.
Method:
First a few things you have to do:
- Sign up for Kaggle
- Sign up for a competition you want to access data from (for example LANL-Earthquake-Prediction competition).
- Download your credentials to access Kaggle API as kaggle.json
Now check if it worked!
It uses official kaggle api behind scene, but automates the process so you dont have to re-download manually every time your VM is taken away. Also, another issue i faced with using Kaggle API directly on Colab was the hassle of transferring Kaggle API token via Google Drive. Above method automates that as well.
Disclaimer: I am one of the creators of Clouderizer.
First of all, run this command to find out where this colab file exists, how it executes. !ls -d $PWD/* It will show /content/data /content/gdrive /content/models In other words, your current directory is root/content/. Your working directory(pwd) is /content/. so when you do !ls , it will show data gdrive models . FYI, ! allows you to run linux commands inside colab.
Google Drive keeps cleaning up the /content folder. Therefore, every session you use colab, downloaded data sets, kaggle json file will be gone. That’s why it’s important to automate the process, so you can focus on writing code, not setting up the environment every time.
opokualbert/Downloading-Kaggle-Datasets-into-Google-Colab
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
In this tutorial, I show how to download kaggle datasets into google colab. Kaggle has been and remains the de factor platform to try your hands on data science projects. The platform has huge rich free datasets for machine learning projects. Another product from google, the company behind kaggle is colab, a platform suitable for training machine learning models and deep neural network free of charge without any installation requirement. One key thing that makes colab a game changer, especially for people who do not own GPU laptop is that users have the option to train their models with free GPU. Colab does not have the trove of datasets kaggle host on its platform therefore, it will be nice if you could access the datasets on kaggle from colab. There is in fact a kaggle API which we can use in colab but setting it up to work is not so easy. I would want to show how to use the API in a few simple steps.
Как импортировать наборы данных Kaggle в Google Colab?
Kaggle используется практически всеми, кто занимается наукой о данных. Эта платформа содержит датасеты для всех областей знаний. Вы можете получить набор данных практически для любого случая использования, включая развлечения, медицину, электронную коммерцию и даже астрономию. Пользователи Kaggle могут попрактиковаться на различных наборах, чтобы проверить свои компетенции в науке о данных и машинном обучении.
В этой статье будет показано, как импортировать наборы данных из Kaggle непосредственно в блокноты Google Colab.
Шаг 1: Выбор любого набора данных из Kaggle
Первый и самый важный шаг — выбор набора данных из Kaggle. Можно выбирать датасеты из конкурсов. Для этой статьи было выбрано два набора данных: один случайный, другой — из действующего конкурса.
Шаг 2: Загрузка учетных данных API
Чтобы загрузить данные из Kaggle, необходимо пройти аутентификацию в сервисах Kaggle. Для этого понадобится API-токен. Его можно сгенерировать в разделе профиля учетной записи пользователя Kaggle.
Сначала перейдите в свой профиль Kaggle:
Теперь откройте вкладку “Account” (“Аккаунт”) и опуститесь до раздела “API” (скриншот из профиля Kaggle).
Будет загружен файл с именем “kaggle.json”, который содержит имя пользователя и ключ API.
Это одноразовый шаг, так что вам не придется генерировать учетные данные всякий раз при загрузке набора данных.
Шаг 3: Настройка блокнота Colab
Запустите блокнот Google Colab и подключите его к облачному экземпляру (по сути, это запуск интерфейса блокнота). Затем загрузите файл “kaggle.json”, скачанный с Kaggle.
Теперь все готово к выполнению команд, необходимых для загрузки набора данных.
Примечание: Здесь будут выполнятся команды на Linux и команды установки, начинающиеся с “!”. Поскольку экземпляры Colab работают на базе Linux, можете запускать все команды Linux в ячейках кода.
Следуйте этим командам:
- Установить библиотеку Kaggle:
2. Создать каталог с именем “.kaggle”:
3. Скопировать файл “kaggle.json” в созданный каталог:
4. Назначить необходимое разрешение для этого файла:
Теперь блокнот Golab готов к загрузке наборов данных из Kaggle.
Это все команды, необходимые для настройки блокнота Golab
Шаг 4: Загрузка наборов данных
На Kaggle размещается два типа наборов данных: Competitions (Конкурсы) и Datasets (Датасеты). Процедуры загрузки различных типов данных отличаются незначительными нюансами.
Загрузка набора данных Competitions:
Здесь “name of the competition” — не название жирным шрифтом, отображаемое на заднем плане. Это фрагмент ссылки на competition, который следует после “/c/”. Вот пример ссылки:
“google-smartphone-decimeter-challenge” — имя competition (конкурса), которое нужно передать команде Kaggle. Эта команда загрузит данные в выделенное хранилище в экземпляре:
Загрузка Datasets:
Эти датасеты не являются частью какого-либо конкурса. Их можно загрузить, выполнив следующее действие:
Здесь “name of the dataset” — это “user-name/dataset-name” (“имя пользователя/имя набора данных”). Вам нужно просто скопировать текст после “www.kaggle.com/":
В нашем случае получится: “arenagrenade/the-complete-pokemon-images-data-set”.
При получении набора данных с zip-расширением используйте команду unzip в Linux для извлечения данных:
Бонусные лайфхаки
Лайфхак 1: Загрузка конкретных файлов
Вы уже знаете, как загружать наборы данных из Kaggle в Google Colab. Если же вам нужно загрузить определенный файл, используйте флаг “-f”, за которым следует имя файла. Так вы загрузите только этот конкретный файл. Флаг “-f” работает как для команды competitions, так и для команды datasets.
Можете ознакомиться с официальной документацией Kaggle API для получения дополнительной информации о возможностях и командах.
Лайфхак 2: Загрузка учетных данных Kaggle из Google Drive
В шаге 3 при настройке блокнота вы загрузили файл “kaggle.json”. Однако файлы, загруженные в хранилище, предоставленное во время настройки блокнота, не сохраняются после завершения работы блокнота.
Поэтому вам нужно загружать файл JSON каждый раз, когда блокнот перезагружается или перезапускается. Чтобы избежать этой ручной работы, выполните следующие действия:
1. Загрузите файл “kaggle.json” на свой Google Drive. Для упрощения задачи стоит загрузить его в корневую папку, а не в какую-либо подструктуру папок.
2. Подключите Google Drive к блокноту:
3. Дайте команды для установки библиотеки Kaggle и создания каталога с именем “.kaggle” (они остаются прежними):
4. Скопируйте файл “kaggle.json” из подключенного Google Drive в хранилище текущего экземпляра. Google Drive подключается по пути “./content/drive/MyDrive”. Просто выполните команду copy, используемую в Linux:
Теперь можно использовать команду для Kaggle competitions и datasets для загрузки наборов данных. Преимущество этого метода в том, что не нужно загружать файл учетных данных при каждом повторном запуске блокнота.
Преимущества использования Google Colab
Google Colab — отличный инструмент для различных исследований данных. Бесплатная поддержка GPU — одно из главных преимуществ Colab. На первых порах начинающие специалисты по обработке данных испытывают нехватку вычислительных ресурсов, поэтому использование Google Colab решает их аппаратные проблемы. Поскольку ноутбуки Colab работают на Linux, можно выполнять все стандартные команды Linux и взаимодействовать с ядром.
Для практикования с наборами данных достаточно оперативной памяти и дискового пространства. Если же ваши исследования требуют дополнительных вычислительных мощностей, можете перейти на “Colab pro”.
The Easy Approach to Access a Kaggle Dataset in Google Colab
This tutorial aims to show you a very easy and straightforward approach to import a Kaggle dataset into Google Colaboratory environment. Here, you will learn:
For a detailed visual walkthrough, you can watch the following video:
About Kaggle
Kaggle is one of the most famous platforms to enroll in a competition associated with Machine Learning and Data Science projects. Kaggle is a place that is where Machine Learning experts gather together to shine! On Kaggle, by reading and doing, you will learn:
- Data processing
- Model deployment
- Evaluation
- Interesting ideas about the subject
- Implementation tweaks
Those three elements are the basics of any Machine Learning project. However, you should NOT expect that on Kaggle you learn everything about real-world projects! In fact, in real-world projects, (1) you usually have not the data clean and ready which is the usual case in Kaggle competitions, (2) you may frequently have to define the problem, something others care about the solution, (3) create a customized framework, (4) evaluate in creative ways, not the regular everyday used metrics! You do NOT learn those with Kaggle, most probably!
About Google Colaboratory
Google Colaboratory is a free platform (environment might be a better word though!) for programmers to do coding! Beyond that, it is in essence developed to facilitate the Machine Learning and Deep Learning research by providing free GPU resources! In Google Colab:
- You have access to a free GPU with limited runtime!
- You write your code in a nice ready-to-use notebook.
- Installing new packages is very easy!
Google Colab basically provide descent computation resources for whoever around the world that (1) desire to do Machine Learning and (2) have a Gmail account!