kimura-koya commited on
Commit
a0baaca
·
verified ·
1 Parent(s): 8e59b73

Add files using upload-large-folder tool

Browse files
.DS_Store ADDED
Binary file (6.15 kB). View file
 
.gitignore ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+ *.so
6
+ .Python
7
+ build/
8
+ develop-eggs/
9
+ dist/
10
+ downloads/
11
+ eggs/
12
+ .eggs/
13
+ lib/
14
+ lib64/
15
+ parts/
16
+ sdist/
17
+ var/
18
+ wheels/
19
+ *.egg-info/
20
+ .installed.cfg
21
+ *.egg
22
+
23
+ # Virtual environments
24
+ .env
25
+ .venv
26
+ env/
27
+ venv/
28
+ ENV/
29
+
30
+ # IDE
31
+ .idea/
32
+ .vscode/
33
+ *.swp
34
+ *.swo
35
+ *~
36
+
37
+ # Jupyter Notebook
38
+ .ipynb_checkpoints
39
+
40
+ # Generated files
41
+ samples_visualization.png
42
+ shape_types.png
43
+ color_distribution.png
44
+
45
+ # OS
46
+ .DS_Store
47
+ Thumbs.db
48
+
49
+ # Logs
50
+ *.log
51
+
52
+ # Agent instructions (internal use only)
53
+ AGENT_INSTRUCTIONS.md
AGENT_INSTRUCTIONS.md ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Shape Polygons Dataset - コード書き換え指示書
2
+
3
+ このドキュメントは、既存のコードをShape Polygons Datasetを使用するように書き換えるための指示書です。
4
+
5
+ ---
6
+
7
+ ## データセット概要
8
+
9
+ | 項目 | 内容 |
10
+ |------|------|
11
+ | 名前 | Shape Polygons Dataset |
12
+ | 総画像数 | 70,000枚(train: 60,000 / test: 10,000) |
13
+ | 画像形式 | PNG |
14
+ | 画像サイズ | 小さい正方形画像(黒背景に色付きポリゴン) |
15
+ | クラス数 | 6(3〜8角形) |
16
+ | メタデータ | CSV形式 |
17
+
18
+ ---
19
+
20
+ ## ディレクトリ構造
21
+
22
+ ```
23
+ shape-polygons-dataset/
24
+ ├── train/
25
+ │ ├── images/
26
+ │ │ ├── 00001.png
27
+ │ │ ├── 00002.png
28
+ │ │ └── ... (60,000 images)
29
+ │ └── metadata.csv
30
+ ├── test/
31
+ │ ├── images/
32
+ │ │ ├── 00001.png
33
+ │ │ └── ... (10,000 images)
34
+ │ └── metadata.csv
35
+ └── example.py
36
+ ```
37
+
38
+ ---
39
+
40
+ ## メタデータ (metadata.csv) のカラム
41
+
42
+ | カラム名 | 型 | 説明 | 範囲 |
43
+ |----------|------|------|------|
44
+ | `filename` | string | 画像ファイル名 | "00001.png" 形式 |
45
+ | `size` | float | ポリゴンの相対サイズ | 0.0 〜 1.0 |
46
+ | `angle` | float | 回転角度(度) | 0.0 〜 360.0 |
47
+ | `vertices` | int | **頂点数(クラスラベル)** | 3, 4, 5, 6, 7, 8 |
48
+ | `center_x` | float | 中心X座標(正規化) | 0.0 〜 1.0 |
49
+ | `center_y` | float | 中心Y座標(正規化) | 0.0 〜 1.0 |
50
+ | `color_r` | float | 赤色成分 | 0.0 〜 1.0 |
51
+ | `color_g` | float | 緑色成分 | 0.0 〜 1.0 |
52
+ | `color_b` | float | 青色成分 | 0.0 〜 1.0 |
53
+
54
+ ---
55
+
56
+ ## タスク別の使い方
57
+
58
+ ### 1. 画像分類(Classification)
59
+
60
+ **目的**: 画像から頂点数(3〜8)を予測する
61
+
62
+ ```python
63
+ # クラスラベルの変換
64
+ # vertices: 3, 4, 5, 6, 7, 8 → label: 0, 1, 2, 3, 4, 5
65
+ label = row["vertices"] - 3
66
+
67
+ # クラス数
68
+ num_classes = 6
69
+
70
+ # クラス名
71
+ class_names = ["Triangle", "Quadrilateral", "Pentagon", "Hexagon", "Heptagon", "Octagon"]
72
+ ```
73
+
74
+ ### 2. 回帰(Regression)
75
+
76
+ **目的**: サイズ、角度、位置などの連続値を予測
77
+
78
+ ```python
79
+ # 単一値回帰
80
+ target = row["size"] # または row["angle"]
81
+
82
+ # 複数値回帰
83
+ target = [row["center_x"], row["center_y"]]
84
+
85
+ # 色の回帰
86
+ target = [row["color_r"], row["color_g"], row["color_b"]]
87
+ ```
88
+
89
+ ### 3. マルチタスク学習
90
+
91
+ ```python
92
+ targets = {
93
+ "vertices": row["vertices"] - 3, # 分類
94
+ "size": row["size"], # 回帰
95
+ "angle": row["angle"], # 回帰
96
+ "center": [row["center_x"], row["center_y"]], # 回帰
97
+ "color": [row["color_r"], row["color_g"], row["color_b"]] # 回帰
98
+ }
99
+ ```
100
+
101
+ ---
102
+
103
+ ## コード書き換えパターン
104
+
105
+ ### パターン A: 既存のImageFolderベースのコードを変換
106
+
107
+ **変換前(ImageFolder):**
108
+ ```python
109
+ from torchvision.datasets import ImageFolder
110
+ dataset = ImageFolder("data/train", transform=transform)
111
+ ```
112
+
113
+ **変換後:**
114
+ ```python
115
+ import pandas as pd
116
+ from torch.utils.data import Dataset
117
+ from PIL import Image
118
+ import os
119
+
120
+ class ShapePolygonsDataset(Dataset):
121
+ def __init__(self, root_dir, split="train", transform=None):
122
+ self.root_dir = root_dir
123
+ self.split = split
124
+ self.transform = transform
125
+ self.metadata = pd.read_csv(os.path.join(root_dir, split, "metadata.csv"))
126
+
127
+ def __len__(self):
128
+ return len(self.metadata)
129
+
130
+ def __getitem__(self, idx):
131
+ row = self.metadata.iloc[idx]
132
+ img_path = os.path.join(self.root_dir, self.split, "images", row["filename"])
133
+ image = Image.open(img_path).convert("RGB")
134
+
135
+ if self.transform:
136
+ image = self.transform(image)
137
+
138
+ label = row["vertices"] - 3 # 0-5 for 3-8 vertices
139
+ return image, label
140
+
141
+ dataset = ShapePolygonsDataset("path/to/dataset", split="train", transform=transform)
142
+ ```
143
+
144
+ ### パターン B: Hugging Face Datasetsを使用
145
+
146
+ ```python
147
+ from datasets import load_dataset
148
+
149
+ # Hugging Face Hubからロード
150
+ dataset = load_dataset("kimura-koya/shape-polygons-dataset")
151
+
152
+ # ローカルからロード(ImageFolder形式として)
153
+ dataset = load_dataset("imagefolder", data_dir="path/to/dataset")
154
+
155
+ # アクセス
156
+ train_data = dataset["train"]
157
+ test_data = dataset["test"]
158
+ ```
159
+
160
+ ### パターン C: シンプルなPandas + PILでのロード
161
+
162
+ ```python
163
+ import pandas as pd
164
+ from PIL import Image
165
+ import os
166
+
167
+ # メタデータ読み込み
168
+ train_df = pd.read_csv("train/metadata.csv")
169
+ test_df = pd.read_csv("test/metadata.csv")
170
+
171
+ # 画像読み込み関数
172
+ def load_image(split, filename):
173
+ return Image.open(os.path.join(split, "images", filename))
174
+
175
+ # 使用例
176
+ for idx, row in train_df.iterrows():
177
+ img = load_image("train", row["filename"])
178
+ label = row["vertices"]
179
+ # 処理...
180
+ ```
181
+
182
+ ---
183
+
184
+ ## よくある変換パターン
185
+
186
+ ### MNIST/CIFAR → Shape Polygons
187
+
188
+ | MNIST/CIFAR | Shape Polygons |
189
+ |-------------|----------------|
190
+ | `torchvision.datasets.MNIST(...)` | `ShapePolygonsDataset(root, split="train")` |
191
+ | `dataset.classes` | `["Triangle", "Quadrilateral", "Pentagon", "Hexagon", "Heptagon", "Octagon"]` |
192
+ | `len(dataset.classes)` = 10 | `num_classes = 6` |
193
+ | グレースケール/RGB | RGB(黒背景にカラーポリゴン) |
194
+
195
+ ### 設定変更のチェックリスト
196
+
197
+ 書き換え時に確認すべき項目:
198
+
199
+ - [ ] `num_classes` を 6 に変更
200
+ - [ ] データセットのパスを変更
201
+ - [ ] 画像の前処理(Normalize等)を確認
202
+ - [ ] train/test/validation の分割方法を確認
203
+ - [ ] クラス名のリストを更新
204
+ - [ ] 評価指標が分類タスクに適切か確認
205
+
206
+ ---
207
+
208
+ ## データセット統計
209
+
210
+ 参考情報として、各クラスの分布:
211
+
212
+ ```
213
+ Train Set (60,000 images):
214
+ 3 vertices (Triangle): 約10,000枚
215
+ 4 vertices (Quadrilateral): 約10,000枚
216
+ 5 vertices (Pentagon): 約10,000枚
217
+ 6 vertices (Hexagon): 約10,000枚
218
+ 7 vertices (Heptagon): 約10,000枚
219
+ 8 vertices (Octagon): 約10,000枚
220
+ ```
221
+
222
+ ※ ほぼ均等に分布
223
+
224
+ ---
225
+
226
+ ## 注意事項
227
+
228
+ 1. **画像サイズ**: 小さい画像なので、大きなモデルではリサイズが必要な場合あり
229
+ 2. **背景**: 黒背景(RGB: 0, 0, 0)にカラーポリゴン
230
+ 3. **合成データ**: すべてプログラムで生成された合成データ
231
+ 4. **ファイル名**: 5桁のゼロパディング(00001.png 〜 60000.png)
232
+
233
+ ---
234
+
235
+ ## サンプルコード(そのまま使用可能)
236
+
237
+ `example.py` に以下の機能があります:
238
+
239
+ - `ShapePolygonsDataset` クラス(PyTorch Dataset)
240
+ - `load_dataset()` 関数(Pandas DataFrame返却)
241
+ - `load_image()` 関数(PIL Image返却)
242
+ - 可視化関数各種
243
+
244
+ ```python
245
+ # example.py をインポートして使用
246
+ from example import ShapePolygonsDataset, load_dataset, load_image
247
+ ```
248
+
LICENSE ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2024
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
README.md CHANGED
@@ -1,3 +1,209 @@
1
- ---
2
- license: mit
3
- ---
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ task_categories:
4
+ - image-classification
5
+ - object-detection
6
+ language:
7
+ - en
8
+ tags:
9
+ - computer-vision
10
+ - polygons
11
+ - shapes
12
+ - synthetic-data
13
+ - image-generation
14
+ pretty_name: Shape Polygons Dataset
15
+ size_categories:
16
+ - 10K<n<100K
17
+ ---
18
+
19
+ # Shape Polygons Dataset
20
+
21
+ A synthetic dataset containing 70,000 images of various colored polygons (triangles to octagons) rendered on black backgrounds.
22
+
23
+ ## Dataset Description
24
+
25
+ This dataset consists of programmatically generated polygon images with full metadata about each shape's properties. It's designed for tasks such as:
26
+
27
+ - **Shape Classification**: Classify polygons by number of vertices (3-8)
28
+ - **Regression Tasks**: Predict shape properties (size, angle, position, color)
29
+ - **Object Detection**: Locate and identify shapes within images
30
+ - **Generative Models**: Train models to generate geometric shapes
31
+
32
+ ### Dataset Statistics
33
+
34
+ | Split | Number of Images |
35
+ |-------|------------------|
36
+ | Train | 60,000 |
37
+ | Test | 10,000 |
38
+ | **Total** | **70,000** |
39
+
40
+ ### Shape Types
41
+
42
+ The dataset includes 6 different polygon types:
43
+ - **Triangle** (3 vertices)
44
+ - **Quadrilateral** (4 vertices)
45
+ - **Pentagon** (5 vertices)
46
+ - **Hexagon** (6 vertices)
47
+ - **Heptagon** (7 vertices)
48
+ - **Octagon** (8 vertices)
49
+
50
+ ## Dataset Structure
51
+
52
+ ```
53
+ shape-polygons-dataset/
54
+ ├── train/
55
+ │ ├── images/
56
+ │ │ ├── 00001.png
57
+ │ │ ├── 00002.png
58
+ │ │ └── ... (60,000 images)
59
+ │ └── metadata.csv
60
+ ├── test/
61
+ │ ├── images/
62
+ │ │ ├── 00001.png
63
+ │ │ ├── 00002.png
64
+ │ │ └── ... (10,000 images)
65
+ │ └── metadata.csv
66
+ └── README.md
67
+ ```
68
+
69
+ ### Metadata Fields
70
+
71
+ Each `metadata.csv` contains the following columns:
72
+
73
+ | Column | Type | Description |
74
+ |--------|------|-------------|
75
+ | `filename` | string | Image filename (e.g., "00001.png") |
76
+ | `size` | float | Relative size of the polygon (0.0 - 1.0) |
77
+ | `angle` | float | Rotation angle in degrees (0.0 - 360.0) |
78
+ | `vertices` | int | Number of vertices (3-8) |
79
+ | `center_x` | float | X-coordinate of center (0.0 - 1.0, normalized) |
80
+ | `center_y` | float | Y-coordinate of center (0.0 - 1.0, normalized) |
81
+ | `color_r` | float | Red color component (0.0 - 1.0) |
82
+ | `color_g` | float | Green color component (0.0 - 1.0) |
83
+ | `color_b` | float | Blue color component (0.0 - 1.0) |
84
+
85
+ ## Sample Images
86
+
87
+ Here are some example images from the dataset:
88
+
89
+ <div style="display: flex; gap: 10px; flex-wrap: wrap;">
90
+ <img src="train/images/00001.png" width="64" height="64" alt="Sample 1">
91
+ <img src="train/images/00003.png" width="64" height="64" alt="Sample 2">
92
+ <img src="train/images/00005.png" width="64" height="64" alt="Sample 3">
93
+ <img src="train/images/00016.png" width="64" height="64" alt="Sample 4">
94
+ </div>
95
+
96
+ ## Usage
97
+
98
+ ### Loading with Hugging Face Datasets
99
+
100
+ ```python
101
+ from datasets import load_dataset
102
+
103
+ # Load the dataset
104
+ dataset = load_dataset("your-username/shape-polygons-dataset")
105
+
106
+ # Access train and test splits
107
+ train_data = dataset["train"]
108
+ test_data = dataset["test"]
109
+
110
+ # Get a sample
111
+ sample = train_data[0]
112
+ print(f"Vertices: {sample['vertices']}, Size: {sample['size']:.2f}")
113
+ ```
114
+
115
+ ### Loading with Pandas
116
+
117
+ ```python
118
+ import pandas as pd
119
+ from PIL import Image
120
+ import os
121
+
122
+ # Load metadata
123
+ train_metadata = pd.read_csv("train/metadata.csv")
124
+ test_metadata = pd.read_csv("test/metadata.csv")
125
+
126
+ # Load an image
127
+ img_path = os.path.join("train/images", train_metadata.iloc[0]["filename"])
128
+ image = Image.open(img_path)
129
+ image.show()
130
+
131
+ # Filter by number of vertices (e.g., triangles only)
132
+ triangles = train_metadata[train_metadata["vertices"] == 3]
133
+ print(f"Number of triangles: {len(triangles)}")
134
+ ```
135
+
136
+ ### PyTorch DataLoader Example
137
+
138
+ ```python
139
+ import torch
140
+ from torch.utils.data import Dataset, DataLoader
141
+ from PIL import Image
142
+ import pandas as pd
143
+ import os
144
+
145
+ class PolygonDataset(Dataset):
146
+ def __init__(self, root_dir, split="train", transform=None):
147
+ self.root_dir = root_dir
148
+ self.split = split
149
+ self.transform = transform
150
+ self.metadata = pd.read_csv(os.path.join(root_dir, split, "metadata.csv"))
151
+
152
+ def __len__(self):
153
+ return len(self.metadata)
154
+
155
+ def __getitem__(self, idx):
156
+ row = self.metadata.iloc[idx]
157
+ img_path = os.path.join(self.root_dir, self.split, "images", row["filename"])
158
+ image = Image.open(img_path).convert("RGB")
159
+
160
+ if self.transform:
161
+ image = self.transform(image)
162
+
163
+ # Number of vertices as classification label (0-5 for 3-8 vertices)
164
+ label = row["vertices"] - 3
165
+
166
+ return image, label
167
+
168
+ # Create dataset and dataloader
169
+ dataset = PolygonDataset("path/to/dataset", split="train")
170
+ dataloader = DataLoader(dataset, batch_size=32, shuffle=True)
171
+ ```
172
+
173
+ ## Use Cases
174
+
175
+ 1. **Beginner-Friendly ML Projects**: Simple dataset for learning image classification
176
+ 2. **Shape Recognition Systems**: Training models to identify geometric shapes
177
+ 3. **Property Regression**: Predicting continuous values (size, angle, position)
178
+ 4. **Multi-Task Learning**: Combining classification and regression objectives
179
+ 5. **Data Augmentation Research**: Studying effects of synthetic data on model performance
180
+ 6. **Benchmark Dataset**: Evaluating new architectures on a controlled, balanced dataset
181
+
182
+ ## License
183
+
184
+ This dataset is released under the [MIT License](LICENSE).
185
+
186
+ ## Citation
187
+
188
+ If you use this dataset in your research, please cite it as:
189
+
190
+ ```bibtex
191
+ @dataset{shape_polygons_dataset,
192
+ title={Shape Polygons Dataset},
193
+ year={2024},
194
+ url={https://huggingface.co/datasets/your-username/shape-polygons-dataset},
195
+ note={A synthetic dataset of 70,000 polygon images for computer vision tasks}
196
+ }
197
+ ```
198
+
199
+ ## Contributing
200
+
201
+ Contributions are welcome! Feel free to:
202
+ - Report issues
203
+ - Suggest improvements
204
+ - Submit pull requests
205
+
206
+ ## Contact
207
+
208
+ For questions or feedback, please open an issue on the repository.
209
+
example.py ADDED
@@ -0,0 +1,272 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Shape Polygons Dataset - Usage Examples
3
+
4
+ This script demonstrates various ways to load and use the Shape Polygons Dataset.
5
+ """
6
+
7
+ import os
8
+ import pandas as pd
9
+ import matplotlib.pyplot as plt
10
+ from PIL import Image
11
+
12
+ # =============================================================================
13
+ # Basic Usage: Loading Metadata and Images
14
+ # =============================================================================
15
+
16
+ def load_dataset(data_dir=".", split="train"):
17
+ """Load metadata and return as pandas DataFrame."""
18
+ metadata_path = os.path.join(data_dir, split, "metadata.csv")
19
+ return pd.read_csv(metadata_path)
20
+
21
+
22
+ def load_image(data_dir, split, filename):
23
+ """Load a single image from the dataset."""
24
+ img_path = os.path.join(data_dir, split, "images", filename)
25
+ return Image.open(img_path)
26
+
27
+
28
+ # =============================================================================
29
+ # Example 1: Explore Dataset Statistics
30
+ # =============================================================================
31
+
32
+ def explore_statistics(data_dir="."):
33
+ """Print dataset statistics."""
34
+ print("=" * 50)
35
+ print("Shape Polygons Dataset Statistics")
36
+ print("=" * 50)
37
+
38
+ for split in ["train", "test"]:
39
+ df = load_dataset(data_dir, split)
40
+ print(f"\n{split.upper()} Split:")
41
+ print(f" Total images: {len(df)}")
42
+ print(f"\n Vertices distribution:")
43
+ for v in range(3, 9):
44
+ count = len(df[df["vertices"] == v])
45
+ print(f" {v} vertices: {count} ({count/len(df)*100:.1f}%)")
46
+
47
+ print(f"\n Size statistics:")
48
+ print(f" Min: {df['size'].min():.4f}")
49
+ print(f" Max: {df['size'].max():.4f}")
50
+ print(f" Mean: {df['size'].mean():.4f}")
51
+
52
+
53
+ # =============================================================================
54
+ # Example 2: Visualize Sample Images
55
+ # =============================================================================
56
+
57
+ def visualize_samples(data_dir=".", n_samples=12, split="train"):
58
+ """Visualize random samples from the dataset."""
59
+ df = load_dataset(data_dir, split)
60
+ samples = df.sample(n=min(n_samples, len(df)))
61
+
62
+ n_cols = 4
63
+ n_rows = (len(samples) + n_cols - 1) // n_cols
64
+
65
+ fig, axes = plt.subplots(n_rows, n_cols, figsize=(12, 3 * n_rows))
66
+ axes = axes.flatten() if n_samples > 1 else [axes]
67
+
68
+ for idx, (_, row) in enumerate(samples.iterrows()):
69
+ img = load_image(data_dir, split, row["filename"])
70
+ axes[idx].imshow(img)
71
+ axes[idx].set_title(f"{row['vertices']} vertices\nsize={row['size']:.2f}")
72
+ axes[idx].axis("off")
73
+
74
+ # Hide empty subplots
75
+ for idx in range(len(samples), len(axes)):
76
+ axes[idx].axis("off")
77
+
78
+ plt.tight_layout()
79
+ plt.savefig("samples_visualization.png", dpi=150, bbox_inches="tight")
80
+ print(f"Saved visualization to 'samples_visualization.png'")
81
+ plt.show()
82
+
83
+
84
+ # =============================================================================
85
+ # Example 3: Visualize by Shape Type
86
+ # =============================================================================
87
+
88
+ def visualize_by_shape_type(data_dir=".", split="train"):
89
+ """Show one example of each shape type."""
90
+ df = load_dataset(data_dir, split)
91
+ shape_names = {
92
+ 3: "Triangle",
93
+ 4: "Quadrilateral",
94
+ 5: "Pentagon",
95
+ 6: "Hexagon",
96
+ 7: "Heptagon",
97
+ 8: "Octagon"
98
+ }
99
+
100
+ fig, axes = plt.subplots(2, 3, figsize=(12, 8))
101
+ axes = axes.flatten()
102
+
103
+ for idx, vertices in enumerate(range(3, 9)):
104
+ sample = df[df["vertices"] == vertices].iloc[0]
105
+ img = load_image(data_dir, split, sample["filename"])
106
+ axes[idx].imshow(img)
107
+ axes[idx].set_title(f"{shape_names[vertices]}\n({vertices} vertices)")
108
+ axes[idx].axis("off")
109
+
110
+ plt.suptitle("Shape Types in Dataset", fontsize=14, fontweight="bold")
111
+ plt.tight_layout()
112
+ plt.savefig("shape_types.png", dpi=150, bbox_inches="tight")
113
+ print(f"Saved visualization to 'shape_types.png'")
114
+ plt.show()
115
+
116
+
117
+ # =============================================================================
118
+ # Example 4: PyTorch Dataset Class
119
+ # =============================================================================
120
+
121
+ # Optional imports for PyTorch functionality
122
+ try:
123
+ import torch
124
+ from torch.utils.data import Dataset, DataLoader
125
+ from torchvision import transforms
126
+ PYTORCH_AVAILABLE = True
127
+ except ImportError:
128
+ PYTORCH_AVAILABLE = False
129
+
130
+
131
+ class ShapePolygonsDataset:
132
+ """PyTorch Dataset for Shape Polygons.
133
+
134
+ Requires: torch, torchvision
135
+ """
136
+
137
+ def __init__(self, root_dir, split="train", transform=None, task="classification"):
138
+ """
139
+ Args:
140
+ root_dir: Root directory of the dataset
141
+ split: "train" or "test"
142
+ transform: Optional torchvision transforms
143
+ task: "classification" for vertex count, "regression" for size prediction, "multi" for all properties
144
+ """
145
+ if not PYTORCH_AVAILABLE:
146
+ raise ImportError("PyTorch is required. Install with: pip install torch torchvision")
147
+
148
+ self.root_dir = root_dir
149
+ self.split = split
150
+ self.transform = transform
151
+ self.task = task
152
+ self.metadata = pd.read_csv(os.path.join(root_dir, split, "metadata.csv"))
153
+
154
+ if self.transform is None:
155
+ self.transform = transforms.Compose([
156
+ transforms.ToTensor(),
157
+ transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5])
158
+ ])
159
+
160
+ def __len__(self):
161
+ return len(self.metadata)
162
+
163
+ def __getitem__(self, idx):
164
+ row = self.metadata.iloc[idx]
165
+ img_path = os.path.join(self.root_dir, self.split, "images", row["filename"])
166
+ image = Image.open(img_path).convert("RGB")
167
+
168
+ if self.transform:
169
+ image = self.transform(image)
170
+
171
+ if self.task == "classification":
172
+ # Class label: 0-5 for 3-8 vertices
173
+ label = torch.tensor(row["vertices"] - 3, dtype=torch.long)
174
+ elif self.task == "regression":
175
+ # Predict size
176
+ label = torch.tensor(row["size"], dtype=torch.float32)
177
+ elif self.task == "multi":
178
+ # Multi-task: return all properties
179
+ label = {
180
+ "vertices": torch.tensor(row["vertices"] - 3, dtype=torch.long),
181
+ "size": torch.tensor(row["size"], dtype=torch.float32),
182
+ "angle": torch.tensor(row["angle"], dtype=torch.float32),
183
+ "center": torch.tensor([row["center_x"], row["center_y"]], dtype=torch.float32),
184
+ "color": torch.tensor([row["color_r"], row["color_g"], row["color_b"]], dtype=torch.float32)
185
+ }
186
+ else:
187
+ raise ValueError(f"Unknown task: {self.task}")
188
+
189
+ return image, label
190
+
191
+
192
+ def demo_pytorch_dataloader(data_dir="."):
193
+ """Demonstrate PyTorch DataLoader usage."""
194
+ if not PYTORCH_AVAILABLE:
195
+ print("PyTorch is not installed. Install with: pip install torch torchvision")
196
+ return
197
+
198
+ print("Creating PyTorch Dataset and DataLoader...")
199
+ dataset = ShapePolygonsDataset(data_dir, split="train", task="classification")
200
+ dataloader = DataLoader(dataset, batch_size=32, shuffle=True, num_workers=0)
201
+
202
+ # Get one batch
203
+ images, labels = next(iter(dataloader))
204
+ print(f"Batch shape: {images.shape}")
205
+ print(f"Labels shape: {labels.shape}")
206
+ print(f"Label values (vertices - 3): {labels[:10].tolist()}")
207
+ print(f"Actual vertex counts: {[l + 3 for l in labels[:10].tolist()]}")
208
+
209
+
210
+ # =============================================================================
211
+ # Example 5: Color Analysis
212
+ # =============================================================================
213
+
214
+ def analyze_colors(data_dir=".", split="train"):
215
+ """Analyze color distribution in the dataset."""
216
+ df = load_dataset(data_dir, split)
217
+
218
+ fig, axes = plt.subplots(1, 3, figsize=(15, 4))
219
+ colors = ["red", "green", "blue"]
220
+ columns = ["color_r", "color_g", "color_b"]
221
+
222
+ for idx, (color, col) in enumerate(zip(colors, columns)):
223
+ axes[idx].hist(df[col], bins=50, color=color, alpha=0.7, edgecolor="black")
224
+ axes[idx].set_xlabel(f"{color.capitalize()} Value")
225
+ axes[idx].set_ylabel("Frequency")
226
+ axes[idx].set_title(f"{color.capitalize()} Channel Distribution")
227
+
228
+ plt.suptitle(f"Color Distribution in {split.capitalize()} Set", fontsize=14, fontweight="bold")
229
+ plt.tight_layout()
230
+ plt.savefig("color_distribution.png", dpi=150, bbox_inches="tight")
231
+ print(f"Saved visualization to 'color_distribution.png'")
232
+ plt.show()
233
+
234
+
235
+ # =============================================================================
236
+ # Main
237
+ # =============================================================================
238
+
239
+ if __name__ == "__main__":
240
+ import argparse
241
+
242
+ parser = argparse.ArgumentParser(description="Shape Polygons Dataset Examples")
243
+ parser.add_argument("--data-dir", type=str, default=".", help="Path to dataset root")
244
+ parser.add_argument(
245
+ "--example",
246
+ type=str,
247
+ choices=["stats", "samples", "shapes", "pytorch", "colors", "all"],
248
+ default="all",
249
+ help="Which example to run"
250
+ )
251
+ args = parser.parse_args()
252
+
253
+ examples = {
254
+ "stats": ("Dataset Statistics", lambda: explore_statistics(args.data_dir)),
255
+ "samples": ("Sample Visualization", lambda: visualize_samples(args.data_dir)),
256
+ "shapes": ("Shape Types", lambda: visualize_by_shape_type(args.data_dir)),
257
+ "pytorch": ("PyTorch DataLoader Demo", lambda: demo_pytorch_dataloader(args.data_dir)),
258
+ "colors": ("Color Analysis", lambda: analyze_colors(args.data_dir)),
259
+ }
260
+
261
+ if args.example == "all":
262
+ for name, (desc, func) in examples.items():
263
+ print(f"\n{'=' * 50}")
264
+ print(f"Example: {desc}")
265
+ print("=" * 50)
266
+ func()
267
+ else:
268
+ name = args.example
269
+ desc, func = examples[name]
270
+ print(f"Running Example: {desc}")
271
+ func()
272
+
test/images/00247.png ADDED

Git LFS Details

  • SHA256: d4ad011986f9d57997578da1ae0fd9564c0a8ce7e2d43d47dd1e10e92adb976b
  • Pointer size: 128 Bytes
  • Size of remote file: 301 Bytes
test/images/00253.png ADDED

Git LFS Details

  • SHA256: afc5ff718cb97b87b025f1ba9130347d51eed003a1821e37057cd41ee299f7c7
  • Pointer size: 128 Bytes
  • Size of remote file: 281 Bytes
test/images/00521.png ADDED

Git LFS Details

  • SHA256: c5be4eb348fc5e38701889cd9787fa797096300a01dc442bb123c298b8f2439b
  • Pointer size: 128 Bytes
  • Size of remote file: 243 Bytes
test/images/00535.png ADDED

Git LFS Details

  • SHA256: 9941442099753ff9156a3586f1b874351c5273497908a00678f0c3ac4bc59e3e
  • Pointer size: 128 Bytes
  • Size of remote file: 366 Bytes
test/images/01159.png ADDED

Git LFS Details

  • SHA256: 73a5e3a248d3df8c0cae5fdc8b8a82f64f4b9922284eba3c1a61bcb6230664ad
  • Pointer size: 128 Bytes
  • Size of remote file: 376 Bytes
test/images/01818.png ADDED

Git LFS Details

  • SHA256: 9bb6c252e6586e3428ddf5f26f23b5d258401afd57f5f196b07bfb8458531009
  • Pointer size: 128 Bytes
  • Size of remote file: 237 Bytes
test/images/02322.png ADDED

Git LFS Details

  • SHA256: 80e8c1c29107d9aaa9b212227460a5202e40ad8572009dbcd799a847346ae0f5
  • Pointer size: 128 Bytes
  • Size of remote file: 374 Bytes
test/images/02336.png ADDED

Git LFS Details

  • SHA256: a6d753568a3d0062b020083f92042c069532e676b2bdd6874b289d601430e6b1
  • Pointer size: 128 Bytes
  • Size of remote file: 272 Bytes
test/images/02444.png ADDED

Git LFS Details

  • SHA256: 857cc557c873c10f2adae0fd95a52ee7bc89c54ad67475c8e3c32a8052e24c40
  • Pointer size: 128 Bytes
  • Size of remote file: 247 Bytes
test/images/02450.png ADDED

Git LFS Details

  • SHA256: 31899a35d130e2c63de152f94e4e3d36e53eb2998b0ea2ebadd630fa23b63506
  • Pointer size: 128 Bytes
  • Size of remote file: 277 Bytes
test/images/03028.png ADDED

Git LFS Details

  • SHA256: d65244a195a2ecdddf69b4972787d3edac425428e2a5f98df618b8a745103659
  • Pointer size: 128 Bytes
  • Size of remote file: 357 Bytes
test/images/03772.png ADDED

Git LFS Details

  • SHA256: 112fec527d157404d2abd30c748516e4e0426f9b21c8f0257971022b56409bbc
  • Pointer size: 128 Bytes
  • Size of remote file: 321 Bytes
test/images/03969.png ADDED

Git LFS Details

  • SHA256: 29e8ac988d9c6a2231cbcab4fc1cd8f86d48b5b5cb060d671eeeb55d46f44cf5
  • Pointer size: 128 Bytes
  • Size of remote file: 276 Bytes
test/images/03982.png ADDED

Git LFS Details

  • SHA256: 60474c51155e96fe972b24bb3af67bdb1036048c3b8a1e4fecd0e73974dfdf0a
  • Pointer size: 128 Bytes
  • Size of remote file: 285 Bytes
test/images/03996.png ADDED

Git LFS Details

  • SHA256: 318c4d37792d607d050addac93518bad631b2fb5c80d61e965813c19c4c1df03
  • Pointer size: 128 Bytes
  • Size of remote file: 359 Bytes
test/images/04021.png ADDED

Git LFS Details

  • SHA256: e818d476b4ecdd9f86b06efa30b3ee0da0e270a3c86a75620dd3e06aeb54db38
  • Pointer size: 128 Bytes
  • Size of remote file: 288 Bytes
test/images/04035.png ADDED

Git LFS Details

  • SHA256: 46c44d15fcb56f28bc5b35b2ea0169b90649f1fad3b28b6efef13fcad0fd1877
  • Pointer size: 128 Bytes
  • Size of remote file: 304 Bytes
test/images/04747.png ADDED

Git LFS Details

  • SHA256: 9c7c99002d8dee888d81376b24a4722d382ab11d1e6e62eb4eabecf7fcd7df3a
  • Pointer size: 128 Bytes
  • Size of remote file: 331 Bytes
test/images/04753.png ADDED

Git LFS Details

  • SHA256: a481594d2efc78f7e96705d6c13d285419901d0baa82430d5d8037ab3cefbddf
  • Pointer size: 128 Bytes
  • Size of remote file: 323 Bytes
test/images/04960.png ADDED

Git LFS Details

  • SHA256: 876bf1f859f5b4638018cdc5f709cb74fc46f2ca39d7a7025b4ac040b9d2563b
  • Pointer size: 128 Bytes
  • Size of remote file: 269 Bytes
test/images/04974.png ADDED

Git LFS Details

  • SHA256: ac52ca515b35fe71a492868e60ab85a09c32f16617aa130639926a3a5f2ca874
  • Pointer size: 128 Bytes
  • Size of remote file: 323 Bytes
test/images/05303.png ADDED

Git LFS Details

  • SHA256: f149a73b15a089ad5724f88f96ca66d6646d55d5ee15bec7d6cf20af59816e06
  • Pointer size: 128 Bytes
  • Size of remote file: 286 Bytes
test/images/05459.png ADDED

Git LFS Details

  • SHA256: e3860d5c986641458e804080318683f99ba1854cdb982444b541367ad8de9d2d
  • Pointer size: 128 Bytes
  • Size of remote file: 290 Bytes
test/images/06144.png ADDED

Git LFS Details

  • SHA256: b5aac0222495c01e7df1fa77085c44a7263028aa3061821a2d574048052ab5b6
  • Pointer size: 128 Bytes
  • Size of remote file: 382 Bytes
test/images/06150.png ADDED

Git LFS Details

  • SHA256: a7d81854ec62bb9204e543422624773b4a778148c747f96700d8fc5a97a00c36
  • Pointer size: 128 Bytes
  • Size of remote file: 245 Bytes
test/images/06622.png ADDED

Git LFS Details

  • SHA256: e719ac09c0423085aa103ca4d1aa3f5feb18d47e2bff2085706c143e6c2e33f1
  • Pointer size: 128 Bytes
  • Size of remote file: 314 Bytes
test/images/06636.png ADDED

Git LFS Details

  • SHA256: 6485fd910cd251fef558031afa1dd2f4398a136f2cbd2aa1872abc8d966553e5
  • Pointer size: 128 Bytes
  • Size of remote file: 333 Bytes
test/images/06805.png ADDED

Git LFS Details

  • SHA256: b5ef99ede3cd23654fd70c28e1a6f17ed418b6fb4698a01315a548b90ca55d8f
  • Pointer size: 128 Bytes
  • Size of remote file: 299 Bytes
test/images/06811.png ADDED

Git LFS Details

  • SHA256: 30114815d1b254ab7026d37b805447167bb25535727d73b80ef0b58912fbe66b
  • Pointer size: 128 Bytes
  • Size of remote file: 288 Bytes
test/images/07514.png ADDED

Git LFS Details

  • SHA256: 5ea624335dd51988791007ba2e8b7ed151d94db68593c50ca5a341867394cea0
  • Pointer size: 128 Bytes
  • Size of remote file: 310 Bytes
test/images/07528.png ADDED

Git LFS Details

  • SHA256: 6eca30d737b38bff5443e1311c0f3ad896512526bfb6aba859c4ca7e5e56a613
  • Pointer size: 128 Bytes
  • Size of remote file: 329 Bytes
test/images/08169.png ADDED

Git LFS Details

  • SHA256: 4f955d94e6b32a78ed7858e7e2226d802144ea42c86443a03cacb1341329680d
  • Pointer size: 128 Bytes
  • Size of remote file: 277 Bytes
test/images/08182.png ADDED

Git LFS Details

  • SHA256: 6938e57c12cc60b8d940d9aa51adc2c594fa77e730acf589bedecef0250180a0
  • Pointer size: 128 Bytes
  • Size of remote file: 254 Bytes
test/images/08196.png ADDED

Git LFS Details

  • SHA256: be06d151b84fa6a4da09a5eaf6153c645602e02c5c1ccddda5cfc4841d9d9156
  • Pointer size: 128 Bytes
  • Size of remote file: 349 Bytes
test/images/08627.png ADDED

Git LFS Details

  • SHA256: ae393fee3432f9b78efd69b72e5e9d0c02e0320310cac5c250d96d75fbbc3fba
  • Pointer size: 128 Bytes
  • Size of remote file: 309 Bytes
test/images/08828.png ADDED

Git LFS Details

  • SHA256: 977bc2cdeb8183a6a7698d3f463833458a14dc3c4c5c592445e8979ad9862eb6
  • Pointer size: 128 Bytes
  • Size of remote file: 365 Bytes
test/images/09263.png ADDED

Git LFS Details

  • SHA256: 53eef0731a2c100b6422e7a52fa5bdf53d7ce87a704086d280c971e7516757de
  • Pointer size: 128 Bytes
  • Size of remote file: 275 Bytes
test/images/09277.png ADDED

Git LFS Details

  • SHA256: 416111bfac58b401204dc1903bb180f8db54d39ecce01a49079eca3786977c38
  • Pointer size: 128 Bytes
  • Size of remote file: 347 Bytes
test/images/09288.png ADDED

Git LFS Details

  • SHA256: 1917496f7f8bf1bd1320d32d20375945a4bfdfdd7a5426ff6765b294f5ffcfdd
  • Pointer size: 128 Bytes
  • Size of remote file: 271 Bytes
test/images/09505.png ADDED

Git LFS Details

  • SHA256: af70f620a81b3508c86d04e6f6e703688360ac6a38e8364d599d671237c087cf
  • Pointer size: 128 Bytes
  • Size of remote file: 323 Bytes
test/images/09511.png ADDED

Git LFS Details

  • SHA256: b62505f7af9a451e3c215108c432e419763a14bfe6b0a34f8b23a1441937e25f
  • Pointer size: 128 Bytes
  • Size of remote file: 281 Bytes
test/metadata.csv ADDED
The diff for this file is too large to render. See raw diff
 
train/.DS_Store ADDED
Binary file (6.15 kB). View file
 
train/metadata.csv ADDED
The diff for this file is too large to render. See raw diff