jokodm 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
jokodm-0.1.0/LICENSE ADDED
@@ -0,0 +1,13 @@
1
+ Hak Cipta (c) 2026 Joko Suntoro
2
+
3
+ Library jokodm boleh dipasang dan dipakai secara gratis untuk belajar, mengajar, penelitian,
4
+ dan pekerjaan, termasuk di dalam kode atau tugas milik Anda sendiri.
5
+
6
+ Tanpa izin tertulis dari pemegang hak cipta, Anda tidak boleh:
7
+ 1. menjual ulang library ini, baik utuh maupun sebagian;
8
+ 2. menerbitkan ulang kode library ini atas nama orang lain atau mengakuinya sebagai karya sendiri.
9
+
10
+ Library ini diberikan "apa adanya", tanpa jaminan apa pun. Pemegang hak cipta tidak bertanggung jawab
11
+ atas kerugian yang timbul dari pemakaiannya.
12
+
13
+ Kontak: jokosuntoro@gmail.com
jokodm-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,124 @@
1
+ Metadata-Version: 2.4
2
+ Name: jokodm
3
+ Version: 0.1.0
4
+ Summary: Algoritma data mining yang ditulis dari nol (SVM, Decision Tree) lengkap dengan visualisasi, bergaya scikit-learn.
5
+ Author-email: Joko Suntoro <jokosuntoro@gmail.com>
6
+ License-Expression: LicenseRef-Jokodm
7
+ Keywords: data mining,machine learning,svm,decision tree,pembelajaran,visualisasi
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Operating System :: OS Independent
10
+ Classifier: Intended Audience :: Education
11
+ Classifier: Intended Audience :: Science/Research
12
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
13
+ Classifier: Natural Language :: Indonesian
14
+ Requires-Python: >=3.8
15
+ Description-Content-Type: text/markdown
16
+ License-File: LICENSE
17
+ Requires-Dist: matplotlib>=3.3
18
+ Provides-Extra: uji
19
+ Requires-Dist: pytest; extra == "uji"
20
+ Requires-Dist: scikit-learn>=1.3; extra == "uji"
21
+ Requires-Dist: numpy; extra == "uji"
22
+ Requires-Dist: pandas; extra == "uji"
23
+ Dynamic: license-file
24
+
25
+ # jokodm
26
+
27
+ Algoritma data mining yang **ditulis dari nol** (tanpa scikit-learn dan tanpa numpy), lengkap dengan
28
+ **visualisasi** untuk memahami cara kerjanya. Cara pakainya mengikuti gaya scikit-learn (`fit`, `predict`),
29
+ jadi pembagian data dan evaluasi tetap bisa memakai scikit-learn.
30
+
31
+ Versi ini berisi:
32
+
33
+ | Algoritma | Visualisasi | Informasi lain |
34
+ |---|---|---|
35
+ | `SVM` (klasifikasi 2 kelas, kernel linear / rbf / poly) | data, hyperplane, garis margin, support vector, titik baru | `ringkasan()`: persamaan f(x), lebar margin, daftar support vector |
36
+ | `DecisionTree` (Gini, information gain, gain ratio) | pohon keputusan berwarna per kelas | `teks()`, `aturan()` (JIKA ... MAKA ...), `feature_importances_` |
37
+
38
+ ## Pemasangan
39
+
40
+ ```python
41
+ !pip install jokodm # di Google Colab / Jupyter
42
+ ```
43
+
44
+ atau di terminal: `pip install jokodm`
45
+
46
+ ## SVM
47
+
48
+ ```python
49
+ import pandas as pd
50
+ from jokodm import SVM
51
+
52
+ df = pd.DataFrame({
53
+ "skor_omzet": [4, 0, 5, 2, 4, 1, 5, 0, 3, 1],
54
+ "skor_bayar": [2, 2, 2, 1, 4, 0, 3, 4, 5, 2],
55
+ "kelayakan": ["Layak", "Tidak Layak", "Layak", "Tidak Layak", "Layak",
56
+ "Tidak Layak", "Layak", "Tidak Layak", "Layak", "Tidak Layak"],
57
+ })
58
+ X, y = df[["skor_omzet", "skor_bayar"]], df["kelayakan"]
59
+
60
+ model = SVM(C=1e6, kelas_positif="Layak") # C sangat besar = hard margin
61
+ model.fit(X, y)
62
+ model.ringkasan() # f(x) = 0.8000*skor_omzet + 0.4000*skor_bayar - 3.0000, margin 2.2361
63
+ model.plot(baru=[[3, 3]]) # hyperplane, margin, support vector, dan titik baru
64
+ model.predict([[3, 3]]) # ['Layak']
65
+ ```
66
+
67
+ Atribut setelah `fit`: `coef_`, `intercept_`, `margin_`, `support_`, `support_vectors_`, `n_support_`,
68
+ `alpha_`, `persamaan_`. Untuk data yang tidak lurus, pakai `SVM(kernel="rbf", C=5)`; `plot()` menggambar
69
+ batas keputusan yang melengkung.
70
+
71
+ Parameter: `C` (bawaan 1.0), `kernel` (`"linear"`, `"rbf"`, `"poly"`), `gamma` (`"scale"`, `"auto"`, angka),
72
+ `degree`, `coef0`, `tol`, `max_iter`, `kelas_positif`.
73
+
74
+ ## Decision Tree
75
+
76
+ ```python
77
+ import pandas as pd
78
+ from jokodm import DecisionTree
79
+
80
+ df = pd.read_csv("play-tennis.csv") # outlook, temperature, humidity, windy, play
81
+ X, y = df.drop(columns=["play"]), df["play"]
82
+
83
+ pohon = DecisionTree(criterion="entropy") # "gini", "entropy" (ID3), "gain_ratio" (C4.5)
84
+ pohon.fit(X, y) # atribut teks dipakai langsung, tanpa one-hot
85
+ pohon.plot() # gambar pohon keputusan
86
+ pohon.aturan() # JIKA outlook = sunny DAN humidity = high MAKA play = no ...
87
+ pohon.teks()
88
+ pohon.feature_importances_
89
+ ```
90
+
91
+ Atribut kategorik (teks) dipecah menjadi satu cabang per nilai; atribut numerik dipecah menjadi
92
+ `<= ambang` dan `> ambang`. Parameter: `criterion`, `max_depth`, `min_samples_split`, `min_samples_leaf`,
93
+ `min_gain`, `atribut_kategorik`.
94
+
95
+ ## Bersama scikit-learn
96
+
97
+ ```python
98
+ from sklearn.model_selection import train_test_split, cross_val_score
99
+ from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
100
+ from jokodm import DecisionTree
101
+
102
+ X_latih, X_uji, y_latih, y_uji = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)
103
+ model = DecisionTree(max_depth=3).fit(X_latih, y_latih)
104
+ y_pred = model.predict(X_uji)
105
+
106
+ print(accuracy_score(y_uji, y_pred))
107
+ print(confusion_matrix(y_uji, y_pred))
108
+ print(classification_report(y_uji, y_pred))
109
+ print(cross_val_score(DecisionTree(max_depth=3), X, y, cv=5))
110
+ ```
111
+
112
+ Model jokodm juga bisa dipakai di `GridSearchCV`. Untuk normalisasi data sebelum SVM, pakai
113
+ `MinMaxScaler` atau `StandardScaler` dari scikit-learn.
114
+
115
+ ## Ketepatan
116
+
117
+ Hasil jokodm diuji terhadap scikit-learn: SVM menghasilkan prediksi yang sama dengan `sklearn.svm.SVC`
118
+ (kernel linear, rbf, poly), dan Decision Tree menghasilkan pohon dengan jumlah daun dan akurasi yang sama
119
+ dengan `DecisionTreeClassifier` pada data iris, wine, dan breast cancer.
120
+
121
+ ## Lisensi
122
+
123
+ Hak Cipta (c) 2026 Joko Suntoro. Gratis dipakai untuk belajar, mengajar, penelitian, dan pekerjaan;
124
+ tidak boleh dijual ulang. Lihat berkas LICENSE. Kontak: jokosuntoro@gmail.com
jokodm-0.1.0/README.md ADDED
@@ -0,0 +1,100 @@
1
+ # jokodm
2
+
3
+ Algoritma data mining yang **ditulis dari nol** (tanpa scikit-learn dan tanpa numpy), lengkap dengan
4
+ **visualisasi** untuk memahami cara kerjanya. Cara pakainya mengikuti gaya scikit-learn (`fit`, `predict`),
5
+ jadi pembagian data dan evaluasi tetap bisa memakai scikit-learn.
6
+
7
+ Versi ini berisi:
8
+
9
+ | Algoritma | Visualisasi | Informasi lain |
10
+ |---|---|---|
11
+ | `SVM` (klasifikasi 2 kelas, kernel linear / rbf / poly) | data, hyperplane, garis margin, support vector, titik baru | `ringkasan()`: persamaan f(x), lebar margin, daftar support vector |
12
+ | `DecisionTree` (Gini, information gain, gain ratio) | pohon keputusan berwarna per kelas | `teks()`, `aturan()` (JIKA ... MAKA ...), `feature_importances_` |
13
+
14
+ ## Pemasangan
15
+
16
+ ```python
17
+ !pip install jokodm # di Google Colab / Jupyter
18
+ ```
19
+
20
+ atau di terminal: `pip install jokodm`
21
+
22
+ ## SVM
23
+
24
+ ```python
25
+ import pandas as pd
26
+ from jokodm import SVM
27
+
28
+ df = pd.DataFrame({
29
+ "skor_omzet": [4, 0, 5, 2, 4, 1, 5, 0, 3, 1],
30
+ "skor_bayar": [2, 2, 2, 1, 4, 0, 3, 4, 5, 2],
31
+ "kelayakan": ["Layak", "Tidak Layak", "Layak", "Tidak Layak", "Layak",
32
+ "Tidak Layak", "Layak", "Tidak Layak", "Layak", "Tidak Layak"],
33
+ })
34
+ X, y = df[["skor_omzet", "skor_bayar"]], df["kelayakan"]
35
+
36
+ model = SVM(C=1e6, kelas_positif="Layak") # C sangat besar = hard margin
37
+ model.fit(X, y)
38
+ model.ringkasan() # f(x) = 0.8000*skor_omzet + 0.4000*skor_bayar - 3.0000, margin 2.2361
39
+ model.plot(baru=[[3, 3]]) # hyperplane, margin, support vector, dan titik baru
40
+ model.predict([[3, 3]]) # ['Layak']
41
+ ```
42
+
43
+ Atribut setelah `fit`: `coef_`, `intercept_`, `margin_`, `support_`, `support_vectors_`, `n_support_`,
44
+ `alpha_`, `persamaan_`. Untuk data yang tidak lurus, pakai `SVM(kernel="rbf", C=5)`; `plot()` menggambar
45
+ batas keputusan yang melengkung.
46
+
47
+ Parameter: `C` (bawaan 1.0), `kernel` (`"linear"`, `"rbf"`, `"poly"`), `gamma` (`"scale"`, `"auto"`, angka),
48
+ `degree`, `coef0`, `tol`, `max_iter`, `kelas_positif`.
49
+
50
+ ## Decision Tree
51
+
52
+ ```python
53
+ import pandas as pd
54
+ from jokodm import DecisionTree
55
+
56
+ df = pd.read_csv("play-tennis.csv") # outlook, temperature, humidity, windy, play
57
+ X, y = df.drop(columns=["play"]), df["play"]
58
+
59
+ pohon = DecisionTree(criterion="entropy") # "gini", "entropy" (ID3), "gain_ratio" (C4.5)
60
+ pohon.fit(X, y) # atribut teks dipakai langsung, tanpa one-hot
61
+ pohon.plot() # gambar pohon keputusan
62
+ pohon.aturan() # JIKA outlook = sunny DAN humidity = high MAKA play = no ...
63
+ pohon.teks()
64
+ pohon.feature_importances_
65
+ ```
66
+
67
+ Atribut kategorik (teks) dipecah menjadi satu cabang per nilai; atribut numerik dipecah menjadi
68
+ `<= ambang` dan `> ambang`. Parameter: `criterion`, `max_depth`, `min_samples_split`, `min_samples_leaf`,
69
+ `min_gain`, `atribut_kategorik`.
70
+
71
+ ## Bersama scikit-learn
72
+
73
+ ```python
74
+ from sklearn.model_selection import train_test_split, cross_val_score
75
+ from sklearn.metrics import accuracy_score, confusion_matrix, classification_report
76
+ from jokodm import DecisionTree
77
+
78
+ X_latih, X_uji, y_latih, y_uji = train_test_split(X, y, test_size=0.2, random_state=42, stratify=y)
79
+ model = DecisionTree(max_depth=3).fit(X_latih, y_latih)
80
+ y_pred = model.predict(X_uji)
81
+
82
+ print(accuracy_score(y_uji, y_pred))
83
+ print(confusion_matrix(y_uji, y_pred))
84
+ print(classification_report(y_uji, y_pred))
85
+ print(cross_val_score(DecisionTree(max_depth=3), X, y, cv=5))
86
+ ```
87
+
88
+ Model jokodm juga bisa dipakai di `GridSearchCV`. Untuk normalisasi data sebelum SVM, pakai
89
+ `MinMaxScaler` atau `StandardScaler` dari scikit-learn.
90
+
91
+ ## Ketepatan
92
+
93
+ Hasil jokodm diuji terhadap scikit-learn: SVM menghasilkan prediksi yang sama dengan `sklearn.svm.SVC`
94
+ (kernel linear, rbf, poly), dan Decision Tree menghasilkan pohon dengan jumlah daun dan akurasi yang sama
95
+ dengan `DecisionTreeClassifier` pada data iris, wine, dan breast cancer.
96
+
97
+ ## Lisensi
98
+
99
+ Hak Cipta (c) 2026 Joko Suntoro. Gratis dipakai untuk belajar, mengajar, penelitian, dan pekerjaan;
100
+ tidak boleh dijual ulang. Lihat berkas LICENSE. Kontak: jokosuntoro@gmail.com
@@ -0,0 +1,35 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "jokodm"
7
+ dynamic = ["version"]
8
+ description = "Algoritma data mining yang ditulis dari nol (SVM, Decision Tree) lengkap dengan visualisasi, bergaya scikit-learn."
9
+ readme = "README.md"
10
+ requires-python = ">=3.8"
11
+ license = "LicenseRef-Jokodm"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "Joko Suntoro", email = "jokosuntoro@gmail.com" }]
14
+ keywords = ["data mining", "machine learning", "svm", "decision tree", "pembelajaran", "visualisasi"]
15
+ dependencies = ["matplotlib>=3.3"]
16
+ classifiers = [
17
+ "Programming Language :: Python :: 3",
18
+ "Operating System :: OS Independent",
19
+ "Intended Audience :: Education",
20
+ "Intended Audience :: Science/Research",
21
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
22
+ "Natural Language :: Indonesian",
23
+ ]
24
+
25
+ [project.optional-dependencies]
26
+ uji = ["pytest", "scikit-learn>=1.3", "numpy", "pandas"]
27
+
28
+ [tool.setuptools.dynamic]
29
+ version = { attr = "jokodm.__version__" }
30
+
31
+ [tool.setuptools.packages.find]
32
+ where = ["src"]
33
+
34
+ [tool.pytest.ini_options]
35
+ testpaths = ["tests"]
jokodm-0.1.0/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,12 @@
1
+ """jokodm: algoritma data mining yang ditulis dari nol, lengkap dengan visualisasinya.
2
+
3
+ from jokodm import SVM, DecisionTree
4
+
5
+ Pembagian data dan evaluasi bisa memakai scikit-learn (train_test_split, accuracy_score, dan lain-lain).
6
+ """
7
+
8
+ from .svm import SVM
9
+ from .tree import DecisionTree
10
+
11
+ __version__ = "0.1.0"
12
+ __all__ = ["SVM", "DecisionTree"]
@@ -0,0 +1,117 @@
1
+ """Bagian bersama: konversi data masukan dan kelas dasar model bergaya scikit-learn.
2
+
3
+ Masukan boleh berupa list, array numpy, atau DataFrame/Series pandas. Di dalam library semua data
4
+ disimpan sebagai list Python biasa, jadi jokodm tidak bergantung pada numpy maupun scikit-learn.
5
+ """
6
+
7
+ import inspect
8
+ import numbers
9
+
10
+
11
+ def ke_tabel(X):
12
+ """Ubah X menjadi (baris, nama_kolom). baris = list of list; nama_kolom = list atau None."""
13
+ nama = None
14
+ if hasattr(X, "columns") and hasattr(X, "values"): # DataFrame pandas
15
+ nama = [str(c) for c in X.columns]
16
+ baris = X.values.tolist()
17
+ elif hasattr(X, "tolist"): # array numpy
18
+ baris = X.tolist()
19
+ else:
20
+ baris = [list(r) if isinstance(r, (list, tuple)) else r for r in X]
21
+ if not baris:
22
+ raise ValueError("Data X kosong.")
23
+ if not isinstance(baris[0], (list, tuple)):
24
+ raise ValueError("X harus 2 dimensi (baris x atribut). Untuk satu atribut pakai X = df[['nama_kolom']] "
25
+ "atau [[nilai], [nilai], ...].")
26
+ lebar = len(baris[0])
27
+ for i, r in enumerate(baris):
28
+ if len(r) != lebar:
29
+ raise ValueError(f"Baris ke-{i} punya {len(r)} nilai, padahal baris pertama punya {lebar}.")
30
+ return [list(r) for r in baris], nama
31
+
32
+
33
+ def ke_list(y):
34
+ """Ubah y (list/array/Series) menjadi list 1 dimensi."""
35
+ if hasattr(y, "values") and hasattr(y, "index"): # Series pandas
36
+ y = y.values
37
+ if hasattr(y, "tolist"):
38
+ y = y.tolist()
39
+ y = list(y)
40
+ if y and isinstance(y[0], (list, tuple)):
41
+ if all(len(v) == 1 for v in y):
42
+ return [v[0] for v in y]
43
+ raise ValueError("y harus 1 dimensi (satu label per baris).")
44
+ return y
45
+
46
+
47
+ def angka(v):
48
+ """True bila v angka (bukan bool)."""
49
+ return isinstance(v, numbers.Number) and not isinstance(v, bool)
50
+
51
+
52
+ def ke_float(baris):
53
+ out = []
54
+ for i, r in enumerate(baris):
55
+ try:
56
+ out.append([float(v) for v in r])
57
+ except (TypeError, ValueError):
58
+ raise ValueError(f"Baris ke-{i} berisi nilai bukan angka: {r}. Algoritma ini butuh atribut numerik.")
59
+ return out
60
+
61
+
62
+ def bersih(v):
63
+ """Nilai numpy (misal numpy.int64) menjadi nilai Python biasa agar tampilan rapi."""
64
+ if hasattr(v, "item") and not isinstance(v, (str, bytes)):
65
+ try:
66
+ return v.item()
67
+ except (ValueError, AttributeError):
68
+ return v
69
+ return v
70
+
71
+
72
+ class ModelDasar:
73
+ """Kelas dasar: get_params / set_params / __repr__ seperti estimator scikit-learn,
74
+ sehingga model jokodm bisa dipakai di cross_val_score dan GridSearchCV."""
75
+
76
+ _estimator_type = "classifier"
77
+
78
+ @classmethod
79
+ def _nama_param(cls):
80
+ sig = inspect.signature(cls.__init__)
81
+ return [p.name for p in sig.parameters.values() if p.name != "self" and p.kind != p.VAR_KEYWORD]
82
+
83
+ def get_params(self, deep=True):
84
+ return {k: getattr(self, k) for k in self._nama_param()}
85
+
86
+ def set_params(self, **params):
87
+ sah = self._nama_param()
88
+ for k, v in params.items():
89
+ if k not in sah:
90
+ raise ValueError(f"Parameter '{k}' tidak dikenal. Parameter yang ada: {', '.join(sah)}.")
91
+ setattr(self, k, v)
92
+ return self
93
+
94
+ def __sklearn_tags__(self):
95
+ """Label model untuk scikit-learn >= 1.6 (dipanggil oleh cross_val_score, GridSearchCV, dan sejenisnya).
96
+ scikit-learn hanya di-import saat fungsi ini dipanggil, jadi jokodm tetap bisa dipakai tanpa scikit-learn."""
97
+ from sklearn.utils import ClassifierTags, InputTags, Tags, TargetTags
98
+
99
+ return Tags(estimator_type="classifier", target_tags=TargetTags(required=True),
100
+ classifier_tags=ClassifierTags(), input_tags=InputTags(string=self._terima_teks))
101
+
102
+ _terima_teks = False
103
+
104
+ def __repr__(self):
105
+ bawaan = {p.name: p.default for p in inspect.signature(type(self).__init__).parameters.values() if p.name != "self"}
106
+ isi = [f"{k}={v!r}" for k, v in self.get_params().items() if bawaan.get(k, object()) != v]
107
+ return f"{type(self).__name__}({', '.join(isi)})"
108
+
109
+ def _cek_terlatih(self):
110
+ if not getattr(self, "terlatih_", False):
111
+ raise RuntimeError(f"Model {type(self).__name__} belum dilatih. Jalankan .fit(X, y) dulu.")
112
+
113
+ def score(self, X, y):
114
+ """Akurasi pada data (X, y)."""
115
+ y = ke_list(y)
116
+ p = self.predict(X)
117
+ return sum(1 for a, b in zip(y, p) if a == b) / len(y)
@@ -0,0 +1,20 @@
1
+ """Palet warna grafik jokodm (tetradic, biru dominan)."""
2
+
3
+ KELAS = ["#1F7AE0", "#F0882A", "#7B57D1", "#4E9A2E", "#155BB0", "#C2621A", "#5A3BA8", "#36721D"]
4
+ MUDA = ["#D6E7FB", "#FCE3CC", "#E4DBF6", "#DCEED3", "#CFDDF0", "#F3D8C2", "#DCD3EF", "#D3E3CA"]
5
+ PENANDA = ["o", "s", "^", "D", "v", "P", "X", "h"]
6
+ TINTA = "#10233F"
7
+ REDUP = "#5B6B82"
8
+ GARIS = "#DCE5F0"
9
+
10
+
11
+ def warna(i):
12
+ return KELAS[i % len(KELAS)]
13
+
14
+
15
+ def muda(i):
16
+ return MUDA[i % len(MUDA)]
17
+
18
+
19
+ def penanda(i):
20
+ return PENANDA[i % len(PENANDA)]