uncle 1.2.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.
- uncle-1.2.0/PKG-INFO +5 -0
- uncle-1.2.0/pyproject.toml +12 -0
- uncle-1.2.0/setup.cfg +4 -0
- uncle-1.2.0/uncle/__init__.py +151 -0
- uncle-1.2.0/uncle/snip.py +147 -0
- uncle-1.2.0/uncle/snippai.py +198 -0
- uncle-1.2.0/uncle.egg-info/PKG-INFO +5 -0
- uncle-1.2.0/uncle.egg-info/SOURCES.txt +8 -0
- uncle-1.2.0/uncle.egg-info/dependency_links.txt +1 -0
- uncle-1.2.0/uncle.egg-info/top_level.txt +1 -0
uncle-1.2.0/PKG-INFO
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "uncle"
|
|
7
|
+
version = "1.2.0"
|
|
8
|
+
description = "uncle.show('hmac') -> the exact codes from your CIS Practical Exam Revision Sheet"
|
|
9
|
+
requires-python = ">=3.8"
|
|
10
|
+
|
|
11
|
+
[tool.setuptools.packages.find]
|
|
12
|
+
include = ["uncle*"]
|
uncle-1.2.0/setup.cfg
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
"""uncle — CIS & AI Practical Exam Revision Sheets, one `import` away.
|
|
2
|
+
|
|
3
|
+
import uncle
|
|
4
|
+
uncle.show("hmac") # CIS sheet, by name (like the original, still works)
|
|
5
|
+
uncle.show("ai", "svm") # AI sheet, by name
|
|
6
|
+
uncle.show("cis") # list all CIS practicals
|
|
7
|
+
uncle.show("ai") # list all AI practicals
|
|
8
|
+
uncle.topics() # everything, everywhere, all at once
|
|
9
|
+
|
|
10
|
+
Every snippet is exactly what's on the sheet, so you can copy-paste it in the exam.
|
|
11
|
+
"""
|
|
12
|
+
__version__ = "1.2.0"
|
|
13
|
+
|
|
14
|
+
from uncle.snip import SNIPPETS, ALIASES
|
|
15
|
+
from uncle.snippai import AISNIPPETS, AIALIASES
|
|
16
|
+
|
|
17
|
+
_SHEETS = {
|
|
18
|
+
"cis": {"dict": SNIPPETS, "aliases": ALIASES, "title": "CIS (Crypto & Network Security) revision sheet"},
|
|
19
|
+
"ai": {"dict": AISNIPPETS, "aliases": AIALIASES, "title": "AI (Artificial Intelligence) revision sheet"},
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
# flat alias -> (sheet, key)
|
|
23
|
+
_FLAT_ALIASES = {}
|
|
24
|
+
for _sheet_name, _cfg in _SHEETS.items():
|
|
25
|
+
for _key, _names in _cfg["aliases"].items():
|
|
26
|
+
for _n in _names:
|
|
27
|
+
_ESC = _FLAT_ALIASES.get(_n)
|
|
28
|
+
_FLAT_ALIASES.setdefault(_n, (_sheet_name, _key))
|
|
29
|
+
# if an alias collides (e.g. bare name in both sheets), prefer the sheet
|
|
30
|
+
# the user explicitly asked for via show(sheet, name) -- dict order already
|
|
31
|
+
# prefers 'cis' for the flat lookup, which matches the original behaviour
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _list_sheet(sheet: str, header: str):
|
|
35
|
+
cfg = _SHEETS[sheet]
|
|
36
|
+
lines = [header, ""]
|
|
37
|
+
for key, (title, _code) in cfg["dict"].items():
|
|
38
|
+
lines.append(f" {key:<10} -> {title}")
|
|
39
|
+
lines += ["", f"Use: uncle.show(\"{sheet}\", \"<name>\")"]
|
|
40
|
+
out = "\n".join(lines)
|
|
41
|
+
print(out)
|
|
42
|
+
return out
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _list_all():
|
|
46
|
+
out_parts = ["╔═ EVERYTHING in uncle:"]
|
|
47
|
+
for sheet in ("cis", "ai"):
|
|
48
|
+
out_parts.append(f"│")
|
|
49
|
+
out_parts.append(f"│ {sheet.upper()} — {_SHEETS[sheet]['title']}")
|
|
50
|
+
for key, (title, _c) in _SHEETS[sheet]["dict"].items():
|
|
51
|
+
out_parts.append(f"│ {key:<10} -> {title}")
|
|
52
|
+
out_parts.append("")
|
|
53
|
+
out_parts.append(" uncle.show(\"<name>\") # CIS direct, e.g. uncle.show(\"hmac\")")
|
|
54
|
+
out_parts.append(" uncle.show(\"ai\", \"<name>\") # AI direct, e.g. uncle.show(\"ai\", \"svm\")")
|
|
55
|
+
out = "\n".join(out_parts)
|
|
56
|
+
print(out)
|
|
57
|
+
return out
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def topics():
|
|
61
|
+
"""Return all snippet names grouped by sheet."""
|
|
62
|
+
return {sheet: list(cfg["dict"].keys()) for sheet, cfg in _SHEETS.items()}
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def show(topic: str = "", sheet: str = None):
|
|
66
|
+
"""Print a snippet from a revision sheet and return its code.
|
|
67
|
+
|
|
68
|
+
How to talk to uncle:
|
|
69
|
+
uncle.show() -- list everything
|
|
70
|
+
uncle.show("hmac") -- CIS sheet by topic name
|
|
71
|
+
uncle.show("ai", "svm") -- AI sheet by topic name
|
|
72
|
+
uncle.show("cis") -- list the CIS sheet
|
|
73
|
+
uncle.show("ai") -- list the AI sheet
|
|
74
|
+
|
|
75
|
+
Returns:
|
|
76
|
+
The snippet code (also printed), or None if no match / list is empty.
|
|
77
|
+
"""
|
|
78
|
+
t = (topic or "").strip().lower()
|
|
79
|
+
s = (sheet or "").strip().lower()
|
|
80
|
+
|
|
81
|
+
# swap mode: uncle.show("ai", "svm") arrives as topic="ai", sheet="svm"
|
|
82
|
+
if s and s not in _SHEETS and t in _SHEETS:
|
|
83
|
+
t, s = s, t
|
|
84
|
+
|
|
85
|
+
if not t and not s: # nothing asked -> list everything
|
|
86
|
+
return _list_all()
|
|
87
|
+
if s and s not in _SHEETS: # sheet name misspelled
|
|
88
|
+
print(f"no sheet called '{s}' (sheets: cis, ai)")
|
|
89
|
+
return None
|
|
90
|
+
if s: # sheet-scoped fetch: uncle.show("ai", "svm")
|
|
91
|
+
return _show_from(t, s)
|
|
92
|
+
if t in _SHEETS: # bare sheet word -> list that sheet
|
|
93
|
+
return _list_sheet(t, f"── {_SHEETS[t]['title']}:")
|
|
94
|
+
return _show_from(t, None) # flat lookup across both sheets
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _show_from(t: str, sheet_key):
|
|
98
|
+
if sheet_key is None:
|
|
99
|
+
hit = _FLAT_ALIASES.get(t)
|
|
100
|
+
if hit is None: # substring fallback on titles+names
|
|
101
|
+
for s_name, cfg in _SHEETS.items():
|
|
102
|
+
for name, (title, _c) in cfg["dict"].items():
|
|
103
|
+
if t in name or t in title.lower():
|
|
104
|
+
hit = (s_name, name)
|
|
105
|
+
break
|
|
106
|
+
if hit:
|
|
107
|
+
break
|
|
108
|
+
if not hit:
|
|
109
|
+
print(f"no snippet called '{t}' on any sheet")
|
|
110
|
+
return None
|
|
111
|
+
s_name, key = hit
|
|
112
|
+
else:
|
|
113
|
+
cfg = _SHEETS[sheet_key]
|
|
114
|
+
aliases = cfg["aliases"]
|
|
115
|
+
key = None
|
|
116
|
+
for name, names in aliases.items():
|
|
117
|
+
if t in names or t == name:
|
|
118
|
+
key = name
|
|
119
|
+
break
|
|
120
|
+
if key is None: # substring fallback, sheet-scoped
|
|
121
|
+
for name, (title, _c) in cfg["dict"].items():
|
|
122
|
+
if t in name or t in title.lower():
|
|
123
|
+
key = name
|
|
124
|
+
break
|
|
125
|
+
if key is None:
|
|
126
|
+
print(f"no snippet called '{t}' on the {sheet_key} sheet")
|
|
127
|
+
_list_sheet(sheet_key, f"── {_SHEETS[sheet_key]['title']}:")
|
|
128
|
+
return None
|
|
129
|
+
s_name = sheet_key
|
|
130
|
+
|
|
131
|
+
title, code = _SHEETS[s_name]["dict"][key]
|
|
132
|
+
print(f"── [{s_name.upper()}] {title} " + "─" * max(3, 54 - len(title)))
|
|
133
|
+
print(code)
|
|
134
|
+
print("─" * 64)
|
|
135
|
+
return code
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def all_to_file(path: str = ""):
|
|
140
|
+
"""Dump every snippet into one .py file for offline notes. Returns the path."""
|
|
141
|
+
if not path:
|
|
142
|
+
path = "uncle_all_pracs.py"
|
|
143
|
+
with open(path, "w", encoding="utf-8") as f:
|
|
144
|
+
f.write("# CIS + AI revision manual -- generated by uncle\n\n")
|
|
145
|
+
for sheet in ("cis", "ai"):
|
|
146
|
+
f.write(f"# ================= {sheet.upper()} =================\n")
|
|
147
|
+
for name, (title, code) in _SHEETS[sheet]["dict"].items():
|
|
148
|
+
f.write(f"\n# ----------------------------\n# {title}\n# ----------------------------\n")
|
|
149
|
+
f.write(code + "\n")
|
|
150
|
+
print("written:", path)
|
|
151
|
+
return path
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
"""All snippets from the CIS Practical Exam Revision Sheet (single-page summary)."""
|
|
2
|
+
|
|
3
|
+
# (title, code_and_steps) per topic, in sheet order
|
|
4
|
+
SNIPPETS = {}
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def _s(name, title, code):
|
|
8
|
+
SNIPPETS[name] = (title, code)
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
_s("caesar", "1A. CAESAR CIPHER", '''def encrypt(msg, k):
|
|
12
|
+
result = ""
|
|
13
|
+
for ch in msg:
|
|
14
|
+
if ch.isalpha():
|
|
15
|
+
result += chr((ord(ch)-65+k)%26+65)
|
|
16
|
+
else: result += ch
|
|
17
|
+
return result
|
|
18
|
+
|
|
19
|
+
msg = input("Enter Message: ").upper()
|
|
20
|
+
k = int(input("Enter Shift: "))
|
|
21
|
+
e = encrypt(msg, k)
|
|
22
|
+
print("Encrypted:", e)
|
|
23
|
+
print("Decrypted:", encrypt(e, -k))''')
|
|
24
|
+
|
|
25
|
+
_s("railfence", "1B. RAIL FENCE CIPHER", '''def encrypt(msg, rails):
|
|
26
|
+
fence = [""] * rails
|
|
27
|
+
row, step = 0, 1
|
|
28
|
+
for ch in msg:
|
|
29
|
+
fence[row] += ch
|
|
30
|
+
if row == 0: step = 1
|
|
31
|
+
elif row == rails - 1: step = -1
|
|
32
|
+
row += step
|
|
33
|
+
return "".join(fence)
|
|
34
|
+
|
|
35
|
+
msg = input("Enter Message: ")
|
|
36
|
+
rails = int(input("Enter Rails: "))
|
|
37
|
+
print("Encrypted:", encrypt(msg, rails))''')
|
|
38
|
+
|
|
39
|
+
_s("hmac", "2. HMAC AUTHENTICATION", '''import hmac, hashlib
|
|
40
|
+
msg = input("Enter Message: ")
|
|
41
|
+
key = input("Enter Secret Key: ")
|
|
42
|
+
|
|
43
|
+
mac = hmac.new(key.encode(), msg.encode(), hashlib.sha256).hexdigest()
|
|
44
|
+
print("Generated HMAC:", mac)
|
|
45
|
+
|
|
46
|
+
check = hmac.new(key.encode(), msg.encode(), hashlib.sha256).hexdigest()
|
|
47
|
+
if hmac.compare_digest(mac, check):
|
|
48
|
+
print("Message is Authentic")
|
|
49
|
+
else:
|
|
50
|
+
print("Authentication Failed")''')
|
|
51
|
+
|
|
52
|
+
_s("signature", "3. DIGITAL SIGNATURE (RSA)", '''from cryptography.hazmat.primitives.asymmetric import rsa, padding
|
|
53
|
+
from cryptography.hazmat.primitives import hashes
|
|
54
|
+
|
|
55
|
+
key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
|
56
|
+
msg = b"Hello"
|
|
57
|
+
|
|
58
|
+
sig = key.sign(msg, padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
|
|
59
|
+
salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256())
|
|
60
|
+
|
|
61
|
+
key.public_key().verify(sig, msg, padding.PSS(mgf=padding.MGF1(hashes.SHA256()),
|
|
62
|
+
salt_length=padding.PSS.MAX_LENGTH), hashes.SHA256())
|
|
63
|
+
|
|
64
|
+
print("Signature Verified Successfully")''')
|
|
65
|
+
|
|
66
|
+
_s("rsa", "4. RSA ENCRYPTION", '''p = 11; q = 13
|
|
67
|
+
n = p * q
|
|
68
|
+
phi = (p-1) * (q-1)
|
|
69
|
+
e = 7; d = 103
|
|
70
|
+
|
|
71
|
+
msg = input("Enter Message: ")
|
|
72
|
+
cipher = [pow(ord(c), e, n) for c in msg]
|
|
73
|
+
print("Encrypted:", cipher)
|
|
74
|
+
plain = "".join(chr(pow(c, d, n)) for c in cipher)
|
|
75
|
+
print("Decrypted:", plain)''')
|
|
76
|
+
|
|
77
|
+
_s("dh", "5. DIFFIE-HELLMAN KEY EXCHANGE", '''p = 23; g = 5
|
|
78
|
+
a = 6; b = 15
|
|
79
|
+
|
|
80
|
+
A = pow(g, a, p)
|
|
81
|
+
B = pow(g, b, p)
|
|
82
|
+
|
|
83
|
+
key1 = pow(B, a, p)
|
|
84
|
+
key2 = pow(A, b, p)
|
|
85
|
+
|
|
86
|
+
print("Sender Public Key:", A)
|
|
87
|
+
print("Receiver Public Key:", B)
|
|
88
|
+
print("Sender Secret Key:", key1)
|
|
89
|
+
print("Receiver Secret Key:", key2)''')
|
|
90
|
+
|
|
91
|
+
_s("malware", "6. MALWARE DETECTION (VIRUSTOTAL)", '''Steps:
|
|
92
|
+
1. Open VirusTotal website.
|
|
93
|
+
2. Click 'Choose File' & upload sample file.
|
|
94
|
+
3. Wait for scanning to complete.
|
|
95
|
+
4. Check detection ratio & SHA-256 hash report.''')
|
|
96
|
+
|
|
97
|
+
_s("firewall", "7. FIREWALL CONFIGURATION", '''Steps:
|
|
98
|
+
1. Control Panel > Windows Defender Firewall.
|
|
99
|
+
2. Click Advanced Settings > Inbound Rules > New Rule.
|
|
100
|
+
3. Select Port > Choose TCP > Enter Port number.
|
|
101
|
+
4. Select 'Block the Connection' > Next > Finish.''')
|
|
102
|
+
|
|
103
|
+
_s("ssl", "8. SSL/TLS CLIENT-SERVER", '''# Server.py
|
|
104
|
+
import socket, ssl
|
|
105
|
+
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
|
106
|
+
ctx.load_cert_chain("server.crt", "server.key")
|
|
107
|
+
s = socket.socket(); s.bind(("localhost", 5000)); s.listen(1)
|
|
108
|
+
c, addr = s.accept()
|
|
109
|
+
with ctx.wrap_socket(c, server_side=True) as conn:
|
|
110
|
+
print("Client:", conn.recv(1024).decode())
|
|
111
|
+
conn.sendall(b"Message Received")
|
|
112
|
+
|
|
113
|
+
# Client.py
|
|
114
|
+
import socket, ssl
|
|
115
|
+
ctx = ssl.create_default_context(); ctx.check_hostname = False; ctx.verify_mode = ssl.CERT_NONE
|
|
116
|
+
with socket.create_connection(("localhost", 5000)) as s:
|
|
117
|
+
with ctx.wrap_socket(s, server_hostname="localhost") as c:
|
|
118
|
+
c.sendall(b"Hello Server")
|
|
119
|
+
print(c.recv(1024).decode())''')
|
|
120
|
+
|
|
121
|
+
_s("ids", "9. INTRUSION DETECTION SYSTEM (IDS)", '''from scapy.all import sniff, IP, TCP
|
|
122
|
+
ports = {}
|
|
123
|
+
def detect(pkt):
|
|
124
|
+
if IP in pkt and TCP in pkt:
|
|
125
|
+
if pkt[TCP].flags == "S":
|
|
126
|
+
ip = pkt[IP].src
|
|
127
|
+
ports[ip] = ports.get(ip, set())
|
|
128
|
+
ports[ip].add(pkt[TCP].dport)
|
|
129
|
+
if len(ports[ip]) >= 5:
|
|
130
|
+
print("Alert! Port Scanning Detected:", ip)
|
|
131
|
+
|
|
132
|
+
print("IDS Started...")
|
|
133
|
+
sniff(filter="tcp", prn=detect)''')
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
ALIASES = {
|
|
137
|
+
"caesar": ["caesar", "ceaser", "shift cipher", "1", "1a", "caesar cipher"],
|
|
138
|
+
"railfence": ["rail", "rail fence", "railfence", "zigzag", "rail fence cipher", "1b"],
|
|
139
|
+
"hmac": ["hmac", "hash", "auth", "authentication", "2", "hmac authentication"],
|
|
140
|
+
"signature": ["signature", "digital signature", "sign", "dsa", "3", "digital"],
|
|
141
|
+
"rsa": ["rsa", "rsa encryption", "4"],
|
|
142
|
+
"dh": ["dh", "diffie", "key exchange", "diffie-hellman", "diffiehellman", "5"],
|
|
143
|
+
"malware": ["malware", "virustotal", "virus total", "vt", "6", "malware detection"],
|
|
144
|
+
"firewall": ["firewall", "7", "firewall configuration"],
|
|
145
|
+
"ssl": ["ssl", "tls", "8", "ssl tls", "ssltls"],
|
|
146
|
+
"ids": ["ids", "intrusion", "intrusion detection", "port scan", "sniff", "sniffer", "9", "ids system"],
|
|
147
|
+
}
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
"""AI practicals — snippets from the AI Practical Exam Revision Sheet."""
|
|
2
|
+
|
|
3
|
+
AISNIPPETS = {}
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def _add(name, title, code):
|
|
7
|
+
AISNIPPETS[name] = (title, code)
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
_add("bfs", "1. BFS & IDDFS", '''from collections import deque
|
|
11
|
+
G = {'A':['B','C'], 'B':['D','E'], 'C':['F'], 'E':['G','H'], 'F':['I']}
|
|
12
|
+
|
|
13
|
+
def bfs(s, goal):
|
|
14
|
+
q = deque([[s]]); seen = set()
|
|
15
|
+
while q:
|
|
16
|
+
p = q.popleft(); n = p[-1]
|
|
17
|
+
if n == goal: return p
|
|
18
|
+
if n not in seen:
|
|
19
|
+
seen.add(n)
|
|
20
|
+
for x in G.get(n, []): q.append(p + [x])
|
|
21
|
+
|
|
22
|
+
def dfs(n, goal, limit, path):
|
|
23
|
+
if n == goal: return path
|
|
24
|
+
if limit == 0: return None
|
|
25
|
+
for x in G.get(n, []):
|
|
26
|
+
if x not in path:
|
|
27
|
+
r = dfs(x, goal, limit-1, path+[x])
|
|
28
|
+
if r: return r
|
|
29
|
+
|
|
30
|
+
print("BFS:", bfs('A','I'))
|
|
31
|
+
for d in range(10):
|
|
32
|
+
r = dfs('A','I',d,['A'])
|
|
33
|
+
if r: print("IDDFS:", r); break''')
|
|
34
|
+
|
|
35
|
+
_add("astar", "2-A. A* SEARCH", '''import heapq
|
|
36
|
+
G = {'A':[('B',4),('C',5)], 'B':[('D',7)], 'C':[('D',2)], 'D':[('E',9)], 'E':[]}
|
|
37
|
+
H = {'A':7,'B':6,'C':2,'D':1,'E':0}
|
|
38
|
+
|
|
39
|
+
q = [(H['A'], 0, 'A')]; cost = {'A':0}; parent = {}
|
|
40
|
+
while q:
|
|
41
|
+
f, g, n = heapq.heappop(q)
|
|
42
|
+
if n == 'E': break
|
|
43
|
+
for x, w in G[n]:
|
|
44
|
+
new = g + w
|
|
45
|
+
if new < cost.get(x, float('inf')):
|
|
46
|
+
cost[x] = new; parent[x] = n
|
|
47
|
+
heapq.heappush(q, (new+H[x], new, x))
|
|
48
|
+
|
|
49
|
+
p = ['E']
|
|
50
|
+
while p[-1] != 'A': p.append(parent[p[-1]])
|
|
51
|
+
p.reverse()
|
|
52
|
+
print("Path:", " -> ".join(p), "| Cost:", cost['E'])''')
|
|
53
|
+
|
|
54
|
+
_add("rbfs", "2-B. RECURSIVE BEST FIRST SEARCH (RBFS)", '''G = {'A':[('B',1),('C',4)], 'B':[('C',2),('D',5)], 'C':[('D',1)], 'D':[('E',3)], 'E':[]}
|
|
55
|
+
H = {'A':7,'B':6,'C':2,'D':1,'E':0}
|
|
56
|
+
|
|
57
|
+
def rbfs(n, g, limit, path):
|
|
58
|
+
if n == 'E': return path, g
|
|
59
|
+
s = [(max(g+w+H[x], H[n]), x, g+w) for x,w in G[n]]
|
|
60
|
+
while s:
|
|
61
|
+
s.sort()
|
|
62
|
+
f, x, ng = s[0]
|
|
63
|
+
if f > limit: return None, f
|
|
64
|
+
alt = s[1][0] if len(s) > 1 else float('inf')
|
|
65
|
+
r, nf = rbfs(x, ng, min(limit, alt), path+[x])
|
|
66
|
+
if r: return r, nf
|
|
67
|
+
s[0] = (nf, x, ng)
|
|
68
|
+
return None, float('inf')
|
|
69
|
+
|
|
70
|
+
p, c = rbfs('A', 0, float('inf'), ['A'])
|
|
71
|
+
print("Path:", " -> ".join(p), "| Cost:", c)''')
|
|
72
|
+
|
|
73
|
+
_add("tree", "3. DECISION TREE", '''from sklearn.datasets import load_iris
|
|
74
|
+
from sklearn.model_selection import train_test_split
|
|
75
|
+
from sklearn.tree import DecisionTreeClassifier, export_text
|
|
76
|
+
from sklearn.metrics import accuracy_score, confusion_matrix
|
|
77
|
+
|
|
78
|
+
X, y = load_iris(return_X_y=True)
|
|
79
|
+
a, b, c, d = train_test_split(X, y, test_size=.25, random_state=42)
|
|
80
|
+
m = DecisionTreeClassifier(random_state=42)
|
|
81
|
+
m.fit(a, c)
|
|
82
|
+
p = m.predict(b)
|
|
83
|
+
print("Accuracy:", accuracy_score(d,p))
|
|
84
|
+
print("Confusion Matrix:\\n", confusion_matrix(d,p))
|
|
85
|
+
print(export_text(m))''')
|
|
86
|
+
|
|
87
|
+
_add("nn", "4. FEED FORWARD BACKPROPAGATION NN", '''from sklearn.datasets import load_iris
|
|
88
|
+
from sklearn.model_selection import train_test_split
|
|
89
|
+
from sklearn.preprocessing import StandardScaler
|
|
90
|
+
from sklearn.neural_network import MLPClassifier
|
|
91
|
+
from sklearn.metrics import accuracy_score
|
|
92
|
+
|
|
93
|
+
X, y = load_iris(return_X_y=True)
|
|
94
|
+
a, b, c, d = train_test_split(X, y, test_size=.25, random_state=42)
|
|
95
|
+
s = StandardScaler()
|
|
96
|
+
a = s.fit_transform(a); b = s.transform(b)
|
|
97
|
+
m = MLPClassifier(hidden_layer_sizes=(10,), max_iter=1000, random_state=42)
|
|
98
|
+
m.fit(a, c); p = m.predict(b)
|
|
99
|
+
print("Actual:", d); print("Predicted:", p)
|
|
100
|
+
print("Accuracy:", accuracy_score(d,p))''')
|
|
101
|
+
|
|
102
|
+
_add("svm", "5. SUPPORT VECTOR MACHINE (SVM)", '''from sklearn.datasets import load_iris
|
|
103
|
+
from sklearn.model_selection import train_test_split
|
|
104
|
+
from sklearn.svm import SVC
|
|
105
|
+
from sklearn.metrics import accuracy_score, confusion_matrix
|
|
106
|
+
|
|
107
|
+
X, y = load_iris(return_X_y=True)
|
|
108
|
+
X, y = X[:100], y[:100]
|
|
109
|
+
a, b, c, d = train_test_split(X, y, test_size=.2, random_state=4)
|
|
110
|
+
m = SVC(kernel='linear', C=1)
|
|
111
|
+
m.fit(a, c); p = m.predict(b)
|
|
112
|
+
print("Accuracy:", accuracy_score(d,p))
|
|
113
|
+
print(confusion_matrix(d,p))''')
|
|
114
|
+
|
|
115
|
+
_add("adaboost", "6. ADABOOST", '''from sklearn.datasets import load_breast_cancer
|
|
116
|
+
from sklearn.model_selection import train_test_split
|
|
117
|
+
from sklearn.tree import DecisionTreeClassifier
|
|
118
|
+
from sklearn.ensemble import AdaBoostClassifier
|
|
119
|
+
from sklearn.metrics import accuracy_score
|
|
120
|
+
|
|
121
|
+
X, y = load_breast_cancer(return_X_y=True)
|
|
122
|
+
a, b, c, d = train_test_split(X, y, test_size=.3, random_state=4)
|
|
123
|
+
m1 = DecisionTreeClassifier(max_depth=1, random_state=4)
|
|
124
|
+
m1.fit(a, c)
|
|
125
|
+
print("Weak stump:", accuracy_score(d, m1.predict(b)))
|
|
126
|
+
m2 = AdaBoostClassifier(n_estimators=50, random_state=4)
|
|
127
|
+
m2.fit(a, c)
|
|
128
|
+
print("AdaBoost:", accuracy_score(d, m2.predict(b)))''')
|
|
129
|
+
|
|
130
|
+
_add("bayes", "7. NAIVE BAYES", '''from sklearn.datasets import load_iris
|
|
131
|
+
from sklearn.model_selection import train_test_split
|
|
132
|
+
from sklearn.naive_bayes import GaussianNB
|
|
133
|
+
from sklearn.metrics import accuracy_score, confusion_matrix
|
|
134
|
+
import numpy as np
|
|
135
|
+
|
|
136
|
+
X, y = load_iris(return_X_y=True)
|
|
137
|
+
a, b, c, d = train_test_split(X, y, test_size=.2, random_state=42)
|
|
138
|
+
m = GaussianNB(); m.fit(a, c); p = m.predict(b)
|
|
139
|
+
print("Accuracy:", accuracy_score(d,p)*100, "%")
|
|
140
|
+
print("Probabilities:\\n", np.round(m.predict_proba(b[:3]),3))
|
|
141
|
+
print("Confusion Matrix:\\n", confusion_matrix(d,p))''')
|
|
142
|
+
|
|
143
|
+
_add("knn", "8. K-NEAREST NEIGHBOUR (KNN)", '''from sklearn.datasets import load_iris
|
|
144
|
+
from sklearn.model_selection import train_test_split
|
|
145
|
+
from sklearn.neighbors import KNeighborsClassifier
|
|
146
|
+
from sklearn.metrics import accuracy_score
|
|
147
|
+
|
|
148
|
+
iris = load_iris()
|
|
149
|
+
X, y = iris.data[:,:2], iris.target
|
|
150
|
+
a, b, c, d = train_test_split(X, y, test_size=.3, random_state=43)
|
|
151
|
+
m = KNeighborsClassifier(n_neighbors=3)
|
|
152
|
+
m.fit(a, c); p = m.predict(b)
|
|
153
|
+
print("Accuracy:", accuracy_score(d,p)*100, "%")
|
|
154
|
+
new = [[5.0,3.5]]
|
|
155
|
+
print("New data:", iris.target_names[m.predict(new)[0]])''')
|
|
156
|
+
|
|
157
|
+
_add("apriori", "9. APRIORI ALGORITHM", '''import pandas as pd
|
|
158
|
+
from mlxtend.preprocessing import TransactionEncoder
|
|
159
|
+
from mlxtend.frequent_patterns import apriori
|
|
160
|
+
|
|
161
|
+
T = [['Milk','Bread'], ['Bread','Butter'],
|
|
162
|
+
['Milk','Bread','Butter'], ['Milk','Butter'],
|
|
163
|
+
['Bread','Butter']]
|
|
164
|
+
te = TransactionEncoder()
|
|
165
|
+
df = pd.DataFrame(te.fit(T).transform(T), columns=te.columns_)
|
|
166
|
+
print(df.astype(int))
|
|
167
|
+
print(apriori(df, min_support=.4, use_colnames=True))''')
|
|
168
|
+
|
|
169
|
+
_add("tf", "10. TENSORFLOW - FASHION MNIST", '''import tensorflow as tf
|
|
170
|
+
from tensorflow.keras import layers, models
|
|
171
|
+
|
|
172
|
+
(X,y), (A,B) = tf.keras.datasets.fashion_mnist.load_data()
|
|
173
|
+
X, A = X/255.0, A/255.0
|
|
174
|
+
m = models.Sequential([
|
|
175
|
+
layers.Input(shape=(28,28)),
|
|
176
|
+
layers.Flatten(),
|
|
177
|
+
layers.Dense(128, activation='relu'),
|
|
178
|
+
layers.Dense(10, activation='softmax')
|
|
179
|
+
])
|
|
180
|
+
m.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
|
|
181
|
+
m.fit(X, y, epochs=3, batch_size=64, validation_split=.1)
|
|
182
|
+
loss, acc = m.evaluate(A, B)
|
|
183
|
+
print("Test Accuracy:", acc)''')
|
|
184
|
+
|
|
185
|
+
|
|
186
|
+
AIALIASES = {
|
|
187
|
+
"bfs": ["bfs", "iddfs", "idf", "breadth", "1", "bfs iddfs", "search"],
|
|
188
|
+
"astar": ["astar", "a*", "a star", "star", "heuristic", "2a", "a* search"],
|
|
189
|
+
"rbfs": ["rbfs", "recursive best", "best first", "2b"],
|
|
190
|
+
"tree": ["tree", "decision", "dt", "3", "decision tree"],
|
|
191
|
+
"nn": ["nn", "neural", "neural network", "nnetwork", "backprop", "ann", "4", "mlp", "nnetwork"],
|
|
192
|
+
"svm": ["svm", "support vector", "5", "support vector machine"],
|
|
193
|
+
"adaboost": ["adaboost", "boost", "boosting", "6", "ensemble"],
|
|
194
|
+
"bayes": ["bayes", "naive", "naivebayes", "nb", "gaussian", "7", "naive bayes"],
|
|
195
|
+
"knn": ["knn", "nearest", "8", "k-nearest", "k nearest"],
|
|
196
|
+
"apriori": ["apriori", "apriori algorithm", "9", "frequent", "market basket"],
|
|
197
|
+
"tf": ["tf", "tensorflow", "mnist", "fashion", "fashion mnist", "10", "cnn"],
|
|
198
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
uncle
|