Spaceship_Titanic_Model

Spaceship Titanic Prediction Challenge

Model for Spaceship Titanic Prediction Challenge

MIT
Tabular Classification
PyTorch
English
by @AIOZAI
81
0

Last updated: 2 months ago


Spaceship Titanic Prediction Model

License Python System

Challenge participants: Build robust models to predict passenger transport during the Spaceship Titanic anomaly.

Table of Contents

Model Details

NameSpaceship Titanic Baseline
TypeBinary classification scaffold
DeveloperAIOZ AI
LicenseMIT
StatusUntrained template (ships as a stub that returns True)

Intended use. Starter scaffold for packaging a Spaceship Titanic submission against AIOZ-AI-Node. Not a production classifier.

Goal. Predict whether a passenger was transported to an alternate dimension.

Quick Start

Clone the repository:

git clone [email protected]:AIOZAI/Spaceship_Titanic_Model.git

Or download directly: Spaceship Titanic Baseline.

The dataset lives separately: Spaceship Titanic Dataset.

Then, from the project directory:

# 1. Install dependencies (do not add other libraries to requirements.txt)
pip install -r requirements.txt

# 2. Implement your model following the tutorial below

# 3. Run the demo
python demo.py

# 4. Verify your submission
python -m my_ai_lib.predict_submission

Requirements

System Requirements

  • Python 3.10+

Dependencies

Install all required packages:

pip install -r requirements.txt

Project Structure

Your AI library should follow this structure:

repository/
├── my_ai_lib/                   # Your AI library
│   ├── __init__.py              # Required: Library initialization
│   ├── run.py                   # Required: Main workflow function
│   ├── predict_submission.py    # Required: Submission function
│   └── [your_modules]/          # Your custom modules
├── models/                      # Model weights directory
├── demo.py                      # Demo script
├── requirements.txt             # Dependencies
└── README.md                    # Documentation

Key Components

ComponentDescriptionStatus
my_ai_lib/Core AI library directoryRequired
my_ai_lib/__init__.pyLibrary initializationRequired
my_ai_lib/predict_submission.pyGenerate predictions for challenge submission.Required
my_ai_lib/run.pyMain AI workflowRequired
demo.pyDemo and testing scriptRequired

Detailed Tutorial

Step 1: Initialize Your AI Library

1.1 Define my_ai_lib/__init__.py

from .run import run

This file exposes the run() function from run.py as an attribute of my_ai_lib, so you can call it as my_ai_lib.run().

1.2 Define Input/Output Objects in my_ai_lib/run.py

Create your custom input and output classes:

from pathlib import Path
from typing import Any, Union, Literal
from aioz_ainode_adapter.schemas import InputObject, OutputObject, FileObject

class SpaceshipInput(InputObject):
    # input_text is a comma-separated string representation of passenger features
    # (e.g., "0001_01,Europa,False,B/0/P,TRAPPIST-1e,39.0,False,0.0,0.0,0.0,0.0,0.0,Maham Ofracculy")
    input_text: str
    
class SpaceshipOutput(OutputObject):
    # transported is the prediction (True or False)
    transported: bool

Step 2: AIOZ Schema Objects

aioz_ainode_adapter exposes three pydantic.BaseModel types:

ObjectPurposeKey fields
InputObjectFormat AIOZ-AI-Node sends to your librarydevice (cuda/cpu/gpu), model_storage_directory (string)
OutputObjectFormat your library returns to AIOZ-AI-NodeUser-defined
FileObjectWrapper for file outputsdata (BufferedReader, Path, or URL), name (string)

Always read model weights from model_storage_directory, since AIOZ-AI-Node sets this path at runtime. Input files must be local paths or URLs; output files must be FileObject instances.

output_file = FileObject(data=open("file/path.csv", "rb"), name="output.csv")

Step 3: Implement the Main Workflow

3.1 Define Your AI Task Function

def do_ai_task(
        input_text: str,
        model_storage_directory: Union[str, Path],
        device: Literal["cpu", "cuda", "gpu"] = "cpu",
        *args, **kwargs) -> bool:
    """Predict if a passenger was transported based on their details."""
    # 1. Parse features from input string
    # features = input_text.split(",")

    # 2. Run prediction using your trained model
    # transported = model.predict([features])[0]
    transported = True
    return transported

3.2 Implement the Required run() Function

def run(input_obj: InputObject) -> OutputObject:
    """Main entry point for the Spaceship Titanic Prediction library."""
    try:
        spaceship_input = SpaceshipInput.model_validate(input_obj.model_dump())
        transported = do_ai_task(
            input_text=spaceship_input.input_text,
            model_storage_directory=spaceship_input.model_storage_directory,
            device=spaceship_input.device,
        )
        output_obj = SpaceshipOutput(transported=transported)
    except Exception as e:
        raise Exception(e)

    return output_obj

The run() name is mandatory. do_ai_task() can be renamed and customized.

Step 4: Create Demo Script

Create demo.py to test your implementation:

import my_ai_lib
from aioz_ainode_adapter.schemas import InputObject

def main():
    """Demo function to test the Spaceship Titanic library."""
    # Example features:
    # PassengerId,HomePlanet,CryoSleep,Cabin,Destination,Age,VIP,RoomService,FoodCourt,ShoppingMall,Spa,VRDeck,Name
    features = "0001_01,Europa,False,B/0/P,TRAPPIST-1e,39.0,False,0.0,0.0,0.0,0.0,0.0,Maham Ofracculy"

    input_obj = InputObject(
        input_text=features
    )
    output_obj = my_ai_lib.run(input_obj)
    print(f"Output: {output_obj}")

if __name__ == '__main__':
    main()

The my_ai_lib.run() function receives an InputObject and returns an OutputObject.

Run this command to test your implementation:

python demo.py

Expected console output:

Input: device='cpu' model_storage_directory='models' input_text='0001_01,Europa,False,B/0/P,TRAPPIST-1e,39.0,False,0.0,0.0,0.0,0.0,0.0,Maham Ofracculy'
Output: transported=True

Step 5: Add Model Weights

Place your trained model files in the models/ directory:

models/
├── model.pth          # Your trained model
├── config.json        # Model configuration
└── etc.

Step 6: Create Prediction Script (For Submission)

Implement the predict_submission() function in my_ai_lib/predict_submission.py

Requirements

  • Function accepting test data folder path (string)
  • Load your trained model
  • Process test dataset (test.csv in test data folder)
  • Generate predictions
  • Save results as ./result.csv

Implementation Template

from aioz_ainode_adapter.schemas import InputObject
import my_ai_lib
import os
import csv

def predict_submission(test_data_folder: str):    
    """
    Generate predictions for challenge submission.
    
    Args:
        test_data_folder: Path to test data directory
    """
    # TODO: Implement your prediction logic here
    # Example:
    # 1. Find test data (test.csv) in test data folder (using os.walk)
    test_csv_path = os.path.join(test_data_folder, "test.csv")
    if not os.path.exists(test_csv_path):
        for root, _, files in os.walk(test_data_folder):
            if "test.csv" in files:
                test_csv_path = os.path.join(root, "test.csv")
                break

    results = []

    # 2. Load model and predict on test dataset
    with open(test_csv_path, "r") as f:
        reader = csv.DictReader(f)
        for row in reader:
            # Prepare feature string from row columns
            feature_cols = ['PassengerId', 'HomePlanet', 'CryoSleep', 'Cabin', 'Destination', 'Age', 'VIP', 'RoomService', 'FoodCourt', 'ShoppingMall', 'Spa', 'VRDeck', 'Name']
            features = ",".join([str(row.get(col, "")) for col in feature_cols])
            
            output_obj = my_ai_lib.run(InputObject(input_text=features))
            results.append({"PassengerId": row["PassengerId"], "Transported": output_obj.transported})

    # 3. Save to ./result.csv
    with open("./result.csv", "w", newline="") as f:
        writer = csv.DictWriter(f, fieldnames=["PassengerId", "Transported"])
        writer.writeheader()
        writer.writerows(results)

    print(f"Saved {len(results)} predictions to ./result.csv")

def main():
    """Main function for testing submission."""
    predict_submission("path/to/test/data")

if __name__ == '__main__':
    main()

Important: The result.csv must match the challenge's sample submission format.

Verify Your Submission

python -m my_ai_lib.predict_submission

Submission Guidelines

Submission Format

The submission file has two fields:

  • PassengerId: The unique identifier for each passenger in the test set.
  • Transported: The target, whether the passenger was transported to another dimension (True or False).

Example:

PassengerId,Transported
0013_01,False
0018_01,False
0019_01,True

License

This repository is licensed under the MIT License.