如何使用kaggle免费30个小时的TPU

该博客围绕TPU花卉识别展开,介绍了使用步骤,包括比赛官网及notebook使用教程,还说明了在页面点create的操作。详细阐述了TPU花卉识别过程,如导入包、检测TPU等。此外,给出了FC Ensemble External Data (EffNet+DenseNet)相关的高分代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.说明

觊觎kaggle上TPU已久,今天正好试一下。。。

2.使用步骤

  1. 比赛官网
    在这里插入图片描述
  2. notebook使用教程
    在这里插入图片描述
    然后下个页面直接点create
    在这里插入图片描述
    在这里插入图片描述

3.TPU花卉识别

官网示例-A Simple TF 2.2 notebook
导入包:

import tensorflow as tf
from kaggle_datasets import KaggleDatasets
import numpy as np

print("Tensorflow version " + tf.__version__)
Tensorflow version 2.2.0

检测TPU:

# Detect hardware, return appropriate distribution strategy
try:
    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()  # TPU detection. No parameters necessary if TPU_NAME environment variable is set. On Kaggle this is always the case.
    print('Running on TPU ', tpu.master())
except ValueError:
    tpu = None

if tpu:
    tf.config.experimental_connect_to_cluster(tpu)
    tf.tpu.experimental.initialize_tpu_system(tpu)
    strategy = tf.distribute.experimental.TPUStrategy(tpu)
else:
    strategy = tf.distribute.get_strategy() # default distribution strategy in Tensorflow. Works on CPU and single GPU.

print("REPLICAS: ", strategy.num_replicas_in_sync)
Running on TPU  grpc://10.0.0.2:8470
REPLICAS:  8
#Get my data path
GCS_DS_PATH = KaggleDatasets().get_gcs_path()

设置参数:

#参数
IMAGE_SIZE = [192, 192] # at this size, a GPU will run out of memory. Use the TPU
EPOCHS = 100
BATCH_SIZE = 32 * strategy.num_replicas_in_sync

NUM_TRAINING_IMAGES = 12753
NUM_TEST_IMAGES = 7382
STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE

加载数据:

def decode_image(image_data):
    image = tf.image.decode_jpeg(image_data, channels=3)
    image = tf.cast(image, tf.float32) / 255.0  # convert image to floats in [0, 1] range
    image = tf.reshape(image, [*IMAGE_SIZE, 3]) # explicit size needed for TPU
    return image

def read_labeled_tfrecord(example):
    LABELED_TFREC_FORMAT = {
        "image": tf.io.FixedLenFeature([], tf.string), # tf.string means bytestring
        "class": tf.io.FixedLenFeature([], tf.int64),  # shape [] means single element
    }
    example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)
    image = decode_image(example['image'])
    label = tf.cast(example['class'], tf.int32)
    return image, label # returns a dataset of (image, label) pairs

def read_unlabeled_tfrecord(example):
    UNLABELED_TFREC_FORMAT = {
        "image": tf.io.FixedLenFeature([], tf.string), # tf.string means bytestring
        "id": tf.io.FixedLenFeature([], tf.string),  # shape [] means single element
        # class is missing, this competitions's challenge is to predict flower classes for the test dataset
    }
    example = tf.io.parse_single_example(example, UNLABELED_TFREC_FORMAT)
    image = decode_image(example['image'])
    idnum = example['id']
    return image, idnum # returns a dataset of image(s)

def load_dataset(filenames, labeled=True, ordered=False):
    # Read from TFRecords. For optimal performance, reading from multiple files at once and
    # disregarding data order. Order does not matter since we will be shuffling the data anyway.

    ignore_order = tf.data.Options()
    if not ordered:
        ignore_order.experimental_deterministic = False # disable order, increase speed

    dataset = tf.data.TFRecordDataset(filenames) # automatically interleaves reads from multiple files
    dataset = dataset.with_options(ignore_order) # uses data as soon as it streams in, rather than in its original order
    dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord)
    # returns a dataset of (image, label) pairs if labeled=True or (image, id) pairs if labeled=False
    return dataset

def get_training_dataset():
    dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-192x192/train/*.tfrec'), labeled=True)
    dataset = dataset.repeat() # the training dataset must repeat for several epochs
    dataset = dataset.shuffle(2048)
    dataset = dataset.batch(BATCH_SIZE)
    return dataset

def get_validation_dataset():
    dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-192x192/val/*.tfrec'), labeled=True, ordered=False)
    dataset = dataset.batch(BATCH_SIZE)
    dataset = dataset.cache()
    return dataset

def get_test_dataset(ordered=False):
    dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-192x192/test/*.tfrec'), labeled=False, ordered=ordered)
    dataset = dataset.batch(BATCH_SIZE)
    return dataset

training_dataset = get_training_dataset()
validation_dataset = get_validation_dataset()

建立模型:

with strategy.scope():    
    pretrained_model = tf.keras.applications.VGG16(weights='imagenet', include_top=False ,input_shape=[*IMAGE_SIZE, 3])
    pretrained_model.trainable = False # tramsfer learning
    
    model = tf.keras.Sequential([
        pretrained_model,
        tf.keras.layers.GlobalAveragePooling2D(),
        tf.keras.layers.Dense(104, activation='softmax')
    ])
        
model.compile(
    optimizer='adam',
    loss = 'sparse_categorical_crossentropy',
    metrics=['sparse_categorical_accuracy']
)

historical = model.fit(training_dataset, 
          steps_per_epoch=STEPS_PER_EPOCH, 
          epochs=EPOCHS, 
          validation_data=validation_dataset)
Epoch 91/100
26/49 [==============>...............] - ETA: 4s - sparse_categorical_accuracy: 0.7459 - loss: 1.0801

测试递交

test_ds = get_test_dataset(ordered=True) # since we are splitting the dataset and iterating separately on images and ids, order matters.

print('Computing predictions...')
test_images_ds = test_ds.map(lambda image, idnum: image)
probabilities = model.predict(test_images_ds)
predictions = np.argmax(probabilities, axis=-1)
print(predictions)

print('Generating submission.csv file...')
test_ids_ds = test_ds.map(lambda image, idnum: idnum).unbatch()
test_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES))).numpy().astype('U') # all in one batch
np.savetxt('submission.csv', np.rec.fromarrays([test_ids, predictions]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='')

在这里插入图片描述

在这里插入图片描述

4.高分代码

  1. FC Ensemble External Data (EffNet+DenseNet)-1
  2. FC Ensemble External Data (EffNet+DenseNet)-2
<think>嗯,用户想知道如何将Kaggle用作云服务器进行数据科学和机器学习任务。首先,我需要回忆一下Kaggle的功能。Kaggle主要是一个数据科学竞赛平台,但也提供一些计算资源,比如Notebook环境和数据集存储。 用户可能没有本地的高性能计算机,或者希望有一个方便的环境来协作和运行代码。Kaggle的云服务器功能可能指的是利用其提供的免费GPU和TPU资源,以及预装的环境来执行任务。需要分步骤说明如何操作。 首先,可能需要指导用户注册Kaggle账号,然后创建Notebook。接着,在Notebook里上传数据或者使用现有的数据集。然后,配置GPU/TPU加速,安装必要的库,运行代码,保存结果,导出模型等。 还要注意Kaggle使用限制,比如每周的GPU使用时间,存储空间限制,以及网络访问的限制。可能需要提到如何绕过这些限制,或者优化使用策略。 另外,用户可能关心如何与团队协作,分享Notebook,或者使用版本控制。Kaggle支持公开和私有Notebook,但私有协作可能需要团队功能,可能需要订阅Kaggle Pro? 还需要提到Kaggle API的使用,通过命令行上传下载数据集和提交结果,这对自动化流程可能有帮助。 可能的注意事项包括数据隐私问题,长时间运行的任务如何处理,以及资源不足时的替代方案,比如Google Colab。 需要确保回答结构清晰,分步骤说明,同时引用提供的参考资料。例如,引用中提到的Applied Machine Learning课程可能涉及scikit-learn的使用,可以在Kaggle环境中应用。而Parkinson语音数据集可能作为示例数据集使用。 最后,生成相关问题,帮助用户深入理解,比如优化资源使用、协作方法、替代平台比较等。</think>### 如何将Kaggle用作云服务器进行数据科学与机器学习任务 Kaggle虽然主要定位为数据科学竞赛平台,但其提供的免费计算资源和预配置环境可临时替代轻量级云服务器。以下是具体操作步骤: #### 1. **环境配置** - **注册与创建Notebook** 登录Kaggle账号后,点击`Code`标签页,选择`New Notebook`创建基于Jupyter的云环境,预装Python、R、TensorFlow、PyTorch等工具包[^1]。 - **硬件加速设置** 在Notebook设置中启用GPU/TPU(每周免费30小时),适合训练深度学习模型。 #### 2. **数据管理** - **挂载数据集** 通过`Add Data`按钮关联Kaggle公开数据集或上传私有数据(单文件上限20GB)。 - **外部数据接入** 使用`!kaggle datasets download -d [数据集ID]`命令下载其他平台数据,或通过Python库(如`requests`)直接获取网络数据。 ```python # 示例:从UCI下载Parkinson语音数据集[^2] !wget https://archive.ics.uci.edu/ml/machine-learning-databases/00496/Parkinson_Disease_Detection.zip !unzip Parkinson_Disease_Detection.zip ``` #### 3. **代码开发与运行** - **依赖库扩展** 在Notebook中使用`!pip install [库名]`安装额外包(如`optuna`用于超参数优化)。 - **持久化存储** 输出文件需保存至`/kaggle/working`目录,支持临时存储(会话结束后保留7天)。 #### 4. **协作与部署** - **版本控制** 通过`Save Version`保存代码快照,支持公开分享或团队协作(需订阅Pro版)。 - **模型部署** 导出训练好的模型至Kaggle Outputs,或通过API集成到外部应用。 --- ### 注意事项 - **资源限制**:免费版GPU时长有限,大型任务建议分阶段执行 - **网络隔离**:Notebook默认无法访问外部数据库,需通过数据集上传或API交互 - **替代方案**:若需更高配置,可结合Google Colab(免费GPU)或AWS SageMaker(付费) ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值