Skip to content

Commit a9d7000

Browse files
committed
Merge branch 'main' of https://github.com/WecoAI/weco-cli
2 parents 7954c40 + 8242f6d commit a9d7000

File tree

8 files changed

+182
-192
lines changed

8 files changed

+182
-192
lines changed
Lines changed: 28 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
11
# Example: Optimizing a Kaggle Classification Model (Spaceship Titanic)
22

3-
This example demonstrates using Weco to optimize a Python script designed for the [Spaceship Titanic Kaggle competition](https://www.kaggle.com/competitions/spaceship-titanic/overview). The goal is to improve the model's `accuracy` metric by modifying the feature engineering and modeling steps within the `optimize.py` script.
4-
5-
This example uses the `README.md` file (this file) to provide additional instructions to the LLM.
3+
This example demonstrates using Weco to optimize a Python script designed for the [Spaceship Titanic Kaggle competition](https://www.kaggle.com/competitions/spaceship-titanic/overview). The goal is to improve the model's `accuracy` metric by directly optimizing the evaluate.py
64

75
## Setup
86

@@ -12,51 +10,58 @@ This example uses the `README.md` file (this file) to provide additional instruc
1210
```bash
1311
pip install -r requirements-test.txt
1412
```
15-
4. **Prepare Data:** Run the utility script once to download the dataset from Kaggle and place it in the expected `public/` and `private/` subdirectories:
13+
4. **Prepare Data:** Run the utility script once to download the dataset from Kaggle and place it in the expected `./data/` subdirectories:
1614
```bash
17-
python utils.py
15+
python get_data.py
1816
```
19-
After running `utils.py`, your directory structure should look like this:
17+
After running `get_data.py`, your directory structure should look like this:
2018
```
2119
.
22-
├── baseline.py
23-
├── evaluate.py
24-
├── optimize.py
25-
├── private
26-
│ └── test.csv
27-
├── public
20+
├── competition_description.md
21+
├── data
2822
│ ├── sample_submission.csv
2923
│ ├── test.csv
3024
│ └── train.csv
31-
├── README.md # This file
25+
├── evaluate.py
26+
├── get_data.py
27+
├── README.md # This file
3228
├── requirements-test.txt
33-
└── utils.py
29+
└── submit.py
3430
```
3531

3632
## Optimization Command
3733

3834
Run the following command to start optimizing the model:
3935

4036
```bash
41-
weco run --source optimize.py \
42-
--eval-command "python optimize.py && python evaluate.py" \
37+
weco run --source evaluate.py \
38+
--eval-command "python evaluate.py --data-dir ./data" \
4339
--metric accuracy \
4440
--maximize true \
4541
--steps 10 \
4642
--model gemini-2.5-pro-exp-03-25 \
47-
--additional-instructions README.md
43+
--additional-instructions "Improve feature engineering, model choice and hyper-parameters."
44+
--log-dir .runs/spaceship-titanic
45+
```
46+
47+
## Submit the solution
48+
49+
Once the optimization finished, you can submit your predictions to kaggle to see the results. Make sure `submission.csv` is present and then simply run the following command.
50+
51+
```bash
52+
python submit.py
4853
```
4954

5055
### Explanation
5156

52-
* `--source optimize.py`: The script containing the model training and prediction logic to be optimized. It starts identical to `baseline.py`.
53-
* `--eval-command "python optimize.py && python evaluate.py"`: This is a multi-step evaluation.
54-
* `python optimize.py`: Runs the modified script to generate predictions (`submission.csv`).
55-
* `python evaluate.py`: Compares the generated `submission.csv` against the ground truth (using the training data as a proxy evaluation set in this example) and prints the `accuracy` metric.
57+
* `--source evaluate.py`: The script provides a baseline as root node and directly optimize the evaluate.py
58+
* `--eval-command "python evaluate.py --data-dir ./data/"`: The weco agent will run the `evaluate.py` and update it.
59+
* [optional] `--data-dir`: path to the train and test data.
60+
* [optional] `--seed`: Seed for reproduce the experiment.
5661
* `--metric accuracy`: The target metric Weco should optimize.
5762
* `--maximize true`: Weco aims to increase the accuracy.
5863
* `--steps 10`: The number of optimization iterations.
5964
* `--model gemini-2.5-pro-exp-03-25`: The LLM driving the optimization.
60-
* `--additional-instructions README.md`: Provides this file as context to the LLM, which might include hints about feature engineering techniques, model types to try, or specific data columns to focus on (you can add such instructions to this file if desired).
65+
* `--additional-instructions "Improve feature engineering, model choice and hyper-parameters."`: A simple instruction for model improvement or you can put the path to [`comptition_description.md`](./competition_description.md) within the repo to feed the agent more detailed information.
6166

62-
Weco will iteratively modify the feature engineering or modeling code within `optimize.py`, run the evaluation pipeline, and use the resulting `accuracy` to guide further improvements. The `baseline.py` file is provided as a reference starting point.
67+
Weco will iteratively modify the feature engineering or modeling code within `evaluate.py`, run the evaluation pipeline, and use the resulting `accuracy` to guide further improvements.

examples/spaceship-titanic/baseline.py

Lines changed: 0 additions & 27 deletions
This file was deleted.
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
# Overview
2+
3+
## Description
4+
Welcome to the year 2912, where your data science skills are needed to solve a cosmic mystery. We've received a transmission from four lightyears away and things aren't looking good.
5+
6+
The *Spaceship Titanic* was an interstellar passenger liner launched a month ago. With almost 13,000 passengers on board, the vessel set out on its maiden voyage transporting emigrants from our solar system to three newly habitable exoplanets orbiting nearby stars.
7+
8+
While rounding Alpha Centauri en route to its first destination—the torrid 55 Cancri E—the unwary *Spaceship Titanic* collided with a spacetime anomaly hidden within a dust cloud. Sadly, it met a similar fate as its namesake from 1000 years before. Though the ship stayed intact, almost half of the passengers were transported to an alternate dimension!
9+
10+
![joel-filipe-QwoNAhbmLLo-unsplash.jpg](https://storage.googleapis.com/kaggle-media/competitions/Spaceship%20Titanic/joel-filipe-QwoNAhbmLLo-unsplash.jpg)
11+
12+
To help rescue crews and retrieve the lost passengers, you are challenged to predict which passengers were transported by the anomaly using records recovered from the spaceship’s damaged computer system.
13+
14+
Help save them and change history!
15+
16+
### Acknowledgments
17+
18+
Photos by [Joel Filipe](https://unsplash.com/@joelfilip?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText)[Richard Gatley](https://unsplash.com/@uncle_rickie?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) and [ActionVance](https://unsplash.com/@actionvance?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on Unsplash.
19+
20+
## Evaluation
21+
22+
### Metric
23+
24+
Submissions are evaluated based on their [classification accuracy](https://developers.google.com/machine-learning/crash-course/classification/accuracy), the percentage of predicted labels that are correct.
25+
26+
### Submission Format
27+
28+
The submission format for the competition is a csv file with the following format:
29+
30+
```
31+
PassengerId,Transported
32+
0013_01,False
33+
0018_01,False
34+
0019_01,False
35+
0021_01,False
36+
etc.
37+
```
38+
39+
## Frequently Asked Questions
40+
41+
### What is a Getting Started competition?
42+
43+
Getting Started competitions were created by Kaggle data scientists for people who have little to no machine learning background. They are a great place to begin if you are new to data science or just finished a MOOC and want to get involved in Kaggle.
44+
45+
Getting Started competitions are a non-competitive way to get familiar with Kaggle’s platform, learn basic machine learning concepts, and start meeting people in the community. They have no cash prize and are on a rolling timeline.
46+
47+
### How do I create and manage a team?
48+
49+
When you accept the competition rules, a team will be created for you. You can invite others to your team, accept a merger with another team, and update basic information like team name by going to the [Team](https://www.kaggle.com/c/spaceship-titanic/team) page.
50+
51+
We've heard from many Kagglers that teaming up is the best way to learn new skills AND have fun. If you don't have a teammate already, consider asking if anyone wants to team up in the [discussion forum](https://www.kaggle.com/c/spaceship-titanic/discussion).
52+
53+
### What are Notebooks?
54+
55+
Kaggle Notebooks is a cloud computational environment that enables reproducible and collaborative analysis. Notebooks support scripts in Python and R, Jupyter Notebooks, and RMarkdown reports. You can visit the [Notebooks](https://www.kaggle.com/c/spaceship-titanic/notebooks) tab to view all of the publicly shared code for the Spaceship Titanic competition. For more on how to use Notebooks to learn data science, check out our [Courses](https://www.kaggle.com/learn/overview)!
56+
57+
### Why did my team disappear from the leaderboard?
58+
59+
To keep with the spirit of getting-started competitions, we have implemented a two month rolling window on submissions. Once a submission is more than two months old, it will be invalidated and no longer count towards the leaderboard.
60+
61+
If your team has no submissions in the previous two months, the team will also drop from the leaderboard. This will keep the leaderboard at a manageable size, freshen it up, and prevent newcomers from getting lost in a sea of abandoned scores.
62+
63+
*"I worked so hard to get that score! Give it back!"* Read more about our decision to implement a rolling leaderboard [here](https://www.kaggle.com/c/titanic/discussion/6240).
64+
65+
### How do I contact Support?
66+
67+
Kaggle does not have a dedicated support team so you’ll typically find that you receive a response more quickly by asking your question in the appropriate forum. (For this competition, you’ll want to use the [Spaceship Titanic discussion forum](https://www.kaggle.com/c/spaceship-titanic/discussion)).
68+
69+
Support is only able to help with issues that are being experienced by all participants. Before contacting support, please check the discussion forum for information on your problem. If you can’t find it, you can post your problem in the forum so a fellow participant or a Kaggle team member can provide help. The forums are full of useful information on the data, metric, and different approaches. We encourage you to use the forums often. If you share your knowledge, you'll find that others will share a lot in turn!
70+
71+
If your problem persists or it seems to be effective all participants then please [contact us](https://www.kaggle.com/contact).
72+
73+
# Dataset Description
74+
75+
In this competition your task is to predict whether a passenger was transported to an alternate dimension during the Spaceship Titanic's collision with the spacetime anomaly. To help you make these predictions, you're given a set of personal records recovered from the ship's damaged computer system.
76+
77+
## File and Data Field Descriptions
78+
79+
- **train.csv** - Personal records for about two-thirds (~8700) of the passengers, to be used as training data.
80+
- `PassengerId` - A unique Id for each passenger. Each Id takes the form `gggg_pp` where `gggg` indicates a group the passenger is travelling with and `pp` is their number within the group. People in a group are often family members, but not always.
81+
- `HomePlanet` - The planet the passenger departed from, typically their planet of permanent residence.
82+
- `CryoSleep` - Indicates whether the passenger elected to be put into suspended animation for the duration of the voyage. Passengers in cryosleep are confined to their cabins.
83+
- `Cabin` - The cabin number where the passenger is staying. Takes the form `deck/num/side`, where `side` can be either `P` for *Port* or `S` for *Starboard*.
84+
- `Destination` - The planet the passenger will be debarking to.
85+
- `Age` - The age of the passenger.
86+
- `VIP` - Whether the passenger has paid for special VIP service during the voyage.
87+
- `RoomService``FoodCourt``ShoppingMall``Spa``VRDeck` - Amount the passenger has billed at each of the *Spaceship Titanic*'s many luxury amenities.
88+
- `Name` - The first and last names of the passenger.
89+
- `Transported` - Whether the passenger was transported to another dimension. This is the target, the column you are trying to predict.
90+
- **test.csv** - Personal records for the remaining one-third (~4300) of the passengers, to be used as test data. Your task is to predict the value of `Transported` for the passengers in this set.
91+
- **sample_submission.csv** - A submission file in the correct format.
92+
- `PassengerId` - Id for each passenger in the test set.
93+
- `Transported` - The target. For each passenger, predict either `True` or `False`.
Lines changed: 31 additions & 59 deletions
Original file line numberDiff line numberDiff line change
@@ -1,71 +1,43 @@
1-
import sys
1+
import argparse
2+
from pathlib import Path
23
import pandas as pd
4+
from sklearn.model_selection import train_test_split
5+
from sklearn.dummy import DummyClassifier
36
from sklearn.metrics import accuracy_score
4-
from pathlib import Path
5-
6-
7-
class InvalidSubmissionError(Exception):
8-
"""
9-
A custom exception for when the agent submission cannot be graded.
10-
"""
11-
12-
pass
13-
7+
import joblib
8+
import warnings
149

15-
def prepare_for_accuracy_metric(submission: pd.DataFrame, answers: pd.DataFrame, target_column: str, id_column: str) -> dict:
16-
# Answers checks
17-
assert target_column in answers.columns, f"Answers must have a `{target_column}` column"
18-
assert id_column in answers.columns, f"Answers must have a `{id_column}` column"
10+
warnings.filterwarnings("ignore", category=UserWarning) # keep Weco's panel tidy
1911

20-
# Submission checks
21-
if len(submission) != len(answers):
22-
raise InvalidSubmissionError("Submission must have the same length as the answers.")
23-
if target_column not in submission.columns:
24-
raise InvalidSubmissionError(f"Submission must have a `{target_column}` column")
25-
if id_column not in submission.columns:
26-
raise InvalidSubmissionError(f"Submission must have a `{id_column}` column")
2712

28-
# sort on id to ensure correct order
29-
submission = submission.sort_values(id_column)
30-
answers = answers.sort_values(id_column)
13+
def train(df: pd.DataFrame, test_df: pd.DataFrame, random_state: int = 0) -> float:
14+
train_df, val_df = train_test_split(df, test_size=0.10, random_state=random_state, stratify=df["Transported"])
3115

32-
if (submission[id_column].values != answers[id_column].values).any():
33-
raise InvalidSubmissionError(f"Submission and Answers `{id_column}`'s do not match")
16+
y_train = train_df.pop("Transported")
17+
y_val = val_df.pop("Transported")
3418

35-
y_pred = submission[target_column].to_numpy()
36-
y_true = answers[target_column].to_numpy()
19+
model = DummyClassifier(strategy="most_frequent", random_state=random_state)
20+
model.fit(train_df, y_train)
21+
preds = model.predict(val_df)
22+
acc = accuracy_score(y_val, preds)
3723

38-
return {"y_true": y_true, "y_pred": y_pred}
24+
# **Important**: Keep this step!!!
25+
# Save the model and generate a submission file on test
26+
joblib.dump(model, "model.joblib")
27+
test_preds = model.predict(test_df)
28+
submission_df = pd.DataFrame({"PassengerId": test_df["PassengerId"], "Transported": test_preds.astype(bool)})
29+
submission_df.to_csv("submission.csv", index=False)
3930

40-
41-
def grade(submission: pd.DataFrame, answers: pd.DataFrame) -> float:
42-
accuracy_inputs = prepare_for_accuracy_metric(
43-
submission=submission, answers=answers, target_column="Transported", id_column="PassengerId"
44-
)
45-
return accuracy_score(**accuracy_inputs)
31+
return acc
4632

4733

4834
if __name__ == "__main__":
49-
# Get the directory where the script is located
50-
script_dir = Path(__file__).resolve().parent
51-
# The ground truth answers are now in private/test.csv
52-
answers_path = script_dir / "private" / "test.csv"
53-
# Assume the agent's submission is saved here
54-
submission_path = script_dir / "submission.csv"
55-
56-
# Check if files exist before proceeding
57-
if not answers_path.exists():
58-
print(f"Error: Answers file not found at {answers_path}") # Updated path in error message
59-
sys.exit(1)
60-
61-
if not submission_path.exists():
62-
print(f"Error: Submission file not found at {submission_path}")
63-
sys.exit(1)
64-
65-
submission = pd.read_csv(submission_path)
66-
# Read answers from the updated path
67-
answers = pd.read_csv(answers_path)
68-
69-
# Calculate and print the grade
70-
score = grade(submission, answers)
71-
print(f"accuracy: {score}")
35+
p = argparse.ArgumentParser()
36+
p.add_argument("--data-dir", type=Path, default=Path("./data/"))
37+
p.add_argument("--seed", type=int, default=0)
38+
args = p.parse_args()
39+
40+
train_df = pd.read_csv(args.data_dir / "train.csv")
41+
test_df = pd.read_csv(args.data_dir / "test.csv")
42+
acc = train(train_df, test_df, random_state=args.seed)
43+
print(f"accuracy: {acc:.6f}")
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import kaggle
2+
import zipfile
3+
import os
4+
5+
6+
def get_data():
7+
kaggle.api.competition_download_files("spaceship-titanic")
8+
# unzip the data
9+
with zipfile.ZipFile("spaceship-titanic.zip", "r") as zip_ref:
10+
zip_ref.extractall("data")
11+
# remove the zip file
12+
os.remove("spaceship-titanic.zip")
13+
14+
15+
if __name__ == "__main__":
16+
get_data()

examples/spaceship-titanic/optimize.py

Lines changed: 0 additions & 27 deletions
This file was deleted.
Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
import argparse
2+
import kaggle
3+
from pathlib import Path
4+
5+
6+
def submit_submission(submission_path: Path):
7+
kaggle.api.competition_submit(submission_path, "My first submission using weco agent", "spaceship-titanic")
8+
9+
10+
if __name__ == "__main__":
11+
parser = argparse.ArgumentParser()
12+
parser.add_argument("--submission-path", "-p", type=Path, default="submission.csv")
13+
args = parser.parse_args()
14+
submit_submission(args.submission_path)

0 commit comments

Comments
 (0)