snippetcards 0.1.0__py3-none-any.whl
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.
- snippetcards/__init__.py +25 -0
- snippetcards/snippets/gradient_descent.txt +31 -0
- snippetcards/snippets/gradient_descent_short.txt +26 -0
- snippetcards/snippets/neural_network.txt +80 -0
- snippetcards/snippets/perceptron_svm.txt +51 -0
- snippetcards/snippets/tf_idf.txt +43 -0
- snippetcards/snippets/tf_idf_alt.txt +41 -0
- snippetcards-0.1.0.dist-info/METADATA +5 -0
- snippetcards-0.1.0.dist-info/RECORD +11 -0
- snippetcards-0.1.0.dist-info/WHEEL +5 -0
- snippetcards-0.1.0.dist-info/top_level.txt +1 -0
snippetcards/__init__.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Show Python examples on demand."""
|
|
2
|
+
|
|
3
|
+
from importlib.resources import files as _files
|
|
4
|
+
|
|
5
|
+
__all__ = ["topics", "code", "show"]
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def topics() -> tuple[str, ...]:
|
|
9
|
+
"""Return the available example names."""
|
|
10
|
+
snippets = _files(__package__).joinpath("snippets")
|
|
11
|
+
return tuple(sorted(file.name.removesuffix(".txt") for file in snippets.iterdir()))
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def code(topic: str) -> str:
|
|
15
|
+
"""Return the source for one example as a string."""
|
|
16
|
+
available = topics()
|
|
17
|
+
if topic not in available:
|
|
18
|
+
raise ValueError(f"Unknown topic {topic!r}. Choose from: {', '.join(available)}")
|
|
19
|
+
return _files(__package__).joinpath("snippets", f"{topic}.txt").read_text(encoding="utf-8")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def show(topic: str) -> None:
|
|
23
|
+
"""Print the source for one example."""
|
|
24
|
+
print(code(topic), end="")
|
|
25
|
+
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
|
|
3
|
+
x = np.array([1,2,3,4,5])
|
|
4
|
+
y = 2 * x
|
|
5
|
+
|
|
6
|
+
m = 0
|
|
7
|
+
b = 0
|
|
8
|
+
|
|
9
|
+
n = len(x)
|
|
10
|
+
lr = 0.01
|
|
11
|
+
epoch = 2000
|
|
12
|
+
|
|
13
|
+
for i in range(epoch):
|
|
14
|
+
|
|
15
|
+
y_pred = m*x + b
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
error = y_pred - y
|
|
19
|
+
mse = np.mean(error ** 2)
|
|
20
|
+
|
|
21
|
+
dm = (2/n) * np.sum(error * x)
|
|
22
|
+
db = (2/n) * np.sum(error)
|
|
23
|
+
|
|
24
|
+
m = m - lr * dm
|
|
25
|
+
b = b - lr * db
|
|
26
|
+
|
|
27
|
+
if i % 100 == 0:
|
|
28
|
+
print(f"Iterations: {i}, Slope: {m}, Y-Intercept: {b} and MSE: {mse}")
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
print(f"the slope is: {m}, Y-Intercept: {b}")
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import numpy as np
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
x = np.array([1,2,3,4,5])
|
|
5
|
+
y = 2*x
|
|
6
|
+
|
|
7
|
+
m = 0
|
|
8
|
+
b = 0
|
|
9
|
+
|
|
10
|
+
n = len(x)
|
|
11
|
+
iterations = 2000
|
|
12
|
+
lr = 0.01
|
|
13
|
+
|
|
14
|
+
for i in range(iterations):
|
|
15
|
+
y_pred = m * x + b
|
|
16
|
+
|
|
17
|
+
error = y_pred - y
|
|
18
|
+
mse = np.mean(error ** 2)
|
|
19
|
+
|
|
20
|
+
dm = (2/n) * np.sum(x * error)
|
|
21
|
+
db = (2/n) * np.sum(error)
|
|
22
|
+
|
|
23
|
+
m = m - lr * dm
|
|
24
|
+
b = b - lr * db
|
|
25
|
+
|
|
26
|
+
print(f"slope: {m}, y-intercept: {b}")
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
# paremeters
|
|
2
|
+
import math
|
|
3
|
+
|
|
4
|
+
import numpy as np
|
|
5
|
+
|
|
6
|
+
input_size = 2
|
|
7
|
+
hidden_size = 4
|
|
8
|
+
output_size = 1
|
|
9
|
+
lr = 0.1
|
|
10
|
+
iterations = 1000
|
|
11
|
+
n_samples = 500
|
|
12
|
+
n_test = 100
|
|
13
|
+
radius = 0.7
|
|
14
|
+
|
|
15
|
+
np.random.seed(42)
|
|
16
|
+
#dataset gen(outside/inside circle)
|
|
17
|
+
|
|
18
|
+
def make_data(n):
|
|
19
|
+
X = np.random.uniform(-1,1, size=(n,2))
|
|
20
|
+
Y = (X[:,0] ** 2 + X[:,1] ** 2 < radius ** 2).astype(float).reshape(-1,1)
|
|
21
|
+
return X, Y
|
|
22
|
+
|
|
23
|
+
X_train, Y_train = make_data(n_samples)
|
|
24
|
+
X_test, Y_test = make_data(n_test)
|
|
25
|
+
#weight/bias initiation
|
|
26
|
+
w1 = np.random.randn(input_size, hidden_size) * 0.5
|
|
27
|
+
b1 = np.zeros((1,hidden_size))
|
|
28
|
+
w2 = np.random.randn(hidden_size, output_size) * 0.5
|
|
29
|
+
b2 = np.zeros((1, output_size))
|
|
30
|
+
|
|
31
|
+
#activation function
|
|
32
|
+
def sigmoid(z):
|
|
33
|
+
return 1.0/(1.0 + math.e**(-z))
|
|
34
|
+
|
|
35
|
+
def sigmoid_derivative(a): #a = sigmoid(z)
|
|
36
|
+
return a * (1.0 - a)
|
|
37
|
+
|
|
38
|
+
#forward pass
|
|
39
|
+
def forward(X):
|
|
40
|
+
z1 = X @ w1 + b1
|
|
41
|
+
a1 = sigmoid(z1)
|
|
42
|
+
z2 = a1 @ w2 + b2
|
|
43
|
+
a2 = sigmoid(z2)
|
|
44
|
+
return a1, a2
|
|
45
|
+
|
|
46
|
+
#training loop(back propagation + gradient descent)
|
|
47
|
+
for i in range(iterations):
|
|
48
|
+
a1, a2 = forward(X_train)
|
|
49
|
+
|
|
50
|
+
MSE = np.mean((a2 - Y_train)**2)
|
|
51
|
+
|
|
52
|
+
d_a2 = (a2 - Y_train)
|
|
53
|
+
d_z2 = d_a2 * sigmoid_derivative(a2)
|
|
54
|
+
dw2 = a1.T @ d_z2
|
|
55
|
+
db2 = np.sum(d_z2, axis=0, keepdims=True)
|
|
56
|
+
|
|
57
|
+
d_a1 = d_z2 @ w2.T
|
|
58
|
+
d_z1 = d_a1 * sigmoid_derivative(a1)
|
|
59
|
+
dw1 = X_train.T @ d_z1
|
|
60
|
+
db1 = np.sum(d_z1, axis=0, keepdims=True)
|
|
61
|
+
|
|
62
|
+
#gradient descent update
|
|
63
|
+
w1 -= lr * dw1
|
|
64
|
+
b1 -= lr * db1
|
|
65
|
+
w2 -= lr * dw2
|
|
66
|
+
b2 -= lr * db2
|
|
67
|
+
|
|
68
|
+
if i % 100 == 0 or i == iterations - 1:
|
|
69
|
+
print(f"Iteration {i:4d} MSE: {MSE:.4f}")
|
|
70
|
+
|
|
71
|
+
#prediction and accuract validation
|
|
72
|
+
def predict(X):
|
|
73
|
+
_, out = forward(X)
|
|
74
|
+
return (out >= 0.5).astype(float)
|
|
75
|
+
|
|
76
|
+
train_acc = np.mean(predict(X_train) == Y_train) * 100
|
|
77
|
+
test_acc = np.mean(predict(X_test) == Y_test) * 100
|
|
78
|
+
|
|
79
|
+
print(f"\nTraining accuracy: {train_acc:.2f}%")
|
|
80
|
+
print(f"Test accuracy: {test_acc:.2f}%")
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import pandas as pd
|
|
2
|
+
import numpy as np
|
|
3
|
+
import matplotlib.pyplot as plt
|
|
4
|
+
from sklearn.linear_model import Perceptron
|
|
5
|
+
from sklearn.model_selection import train_test_split
|
|
6
|
+
from sklearn.svm import SVC
|
|
7
|
+
from sklearn.metrics import accuracy_score
|
|
8
|
+
|
|
9
|
+
df = pd.read_csv('fake_news_perceptron.csv')
|
|
10
|
+
y = df.iloc[:,0].values
|
|
11
|
+
y = np.where(y == 'fake', -1, 1)
|
|
12
|
+
x = df.iloc[:,[1,2]].values
|
|
13
|
+
|
|
14
|
+
X_train, X_test, Y_train, Y_test = train_test_split(x, y, test_size=0.3, random_state=0)
|
|
15
|
+
|
|
16
|
+
#perceptron
|
|
17
|
+
p = Perceptron(max_iter=50, eta0=0.1, random_state=2)
|
|
18
|
+
p.fit(X_train, Y_train)
|
|
19
|
+
|
|
20
|
+
Y_pred = p.predict(X_test)
|
|
21
|
+
|
|
22
|
+
print("Perceptron results: ")
|
|
23
|
+
print(f"Misclassified Samples: {(Y_test != Y_pred).sum()}")
|
|
24
|
+
print(f"Accuracy Score: {accuracy_score(Y_test,Y_pred)}")
|
|
25
|
+
print()
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
df = pd.read_csv('fake_news_svm.csv')
|
|
29
|
+
y = df.iloc[:,0].values
|
|
30
|
+
y = np.where(y == 'fake', -1, 1)
|
|
31
|
+
x = df.iloc[:,[1,2]].values
|
|
32
|
+
|
|
33
|
+
X_train, X_test, Y_train, Y_test = train_test_split(x, y, test_size=0.3, random_state=0)
|
|
34
|
+
|
|
35
|
+
#SVM
|
|
36
|
+
svc_lin = SVC(kernel='linear', C=1.0, random_state=1)
|
|
37
|
+
svc_rbf = SVC(kernel='rbf', C=1.0, random_state=1)
|
|
38
|
+
svc_lin.fit(X_train,Y_train)
|
|
39
|
+
svc_rbf.fit(X_train,Y_train)
|
|
40
|
+
|
|
41
|
+
Y_pred_lin = svc_lin.predict(X_test)
|
|
42
|
+
Y_pred_rbf = svc_rbf.predict(X_test)
|
|
43
|
+
|
|
44
|
+
print("SVC Linear Kernel results: ")
|
|
45
|
+
print(f"Misclassified Samples: {(Y_test != Y_pred_lin).sum()}")
|
|
46
|
+
print(f"Accuracy Score: {accuracy_score(Y_test,Y_pred_lin)}")
|
|
47
|
+
print()
|
|
48
|
+
print("SVC RBF Kernel results: ")
|
|
49
|
+
print(f"Misclassified Samples: {(Y_test != Y_pred_rbf).sum()}")
|
|
50
|
+
print(f"Accuracy Score: {accuracy_score(Y_test,Y_pred_rbf)}")
|
|
51
|
+
print()
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
from collections import Counter
|
|
2
|
+
import itertools
|
|
3
|
+
from math import log
|
|
4
|
+
import numpy as np
|
|
5
|
+
|
|
6
|
+
doc_list = ["Julie loves me more than Linda loves me",
|
|
7
|
+
"Jane likes me more than Julie loves me",
|
|
8
|
+
"He likes basketball more than baseball"]
|
|
9
|
+
bags = []
|
|
10
|
+
bags = [Counter(doc.lower().split()) for doc in doc_list] #bags
|
|
11
|
+
|
|
12
|
+
vocabulary = sorted(list(set(itertools.chain(*[list(bag) for bag in bags])))) #vocabulary
|
|
13
|
+
#vectorize bags
|
|
14
|
+
vec_list = []
|
|
15
|
+
for bag in bags:
|
|
16
|
+
vector = [bag[word] for word in vocabulary]
|
|
17
|
+
vec_list.append(vector)
|
|
18
|
+
|
|
19
|
+
#normalized term formula
|
|
20
|
+
def normalize_tf(tf):
|
|
21
|
+
if tf == 0:
|
|
22
|
+
return 0.0
|
|
23
|
+
else:
|
|
24
|
+
return 1.0 + log(tf)
|
|
25
|
+
|
|
26
|
+
tf_vec_list = []
|
|
27
|
+
for vec in vec_list:
|
|
28
|
+
tf_vec_list.append([normalize_tf(tf) for tf in vec])
|
|
29
|
+
|
|
30
|
+
ndocs = len(doc_list)
|
|
31
|
+
vec_df = [(v,sum([b[v] for b in bags])) for v in vocabulary]
|
|
32
|
+
#IDF formula
|
|
33
|
+
def idf(df,ndocs):
|
|
34
|
+
return 1.0 + log(ndocs / (df + 1))
|
|
35
|
+
|
|
36
|
+
idf_vocab = [(word, idf(df, ndocs)) for word, df in vec_df]
|
|
37
|
+
idf_vector = np.array([value for word, value in idf_vocab])
|
|
38
|
+
|
|
39
|
+
matrix_tfidf = np.array(tf_vec_list) * idf_vector
|
|
40
|
+
#after normalization
|
|
41
|
+
matrix_tfidf_l2 = matrix_tfidf / np.linalg.norm(matrix_tfidf, axis=1, keepdims=True)
|
|
42
|
+
np.set_printoptions(linewidth=200)
|
|
43
|
+
print(matrix_tfidf_l2)
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
from collections import Counter
|
|
2
|
+
from math import log
|
|
3
|
+
import numpy as np
|
|
4
|
+
import itertools
|
|
5
|
+
|
|
6
|
+
docs = ["Julie loves me more than Linda loves me",
|
|
7
|
+
"Jane likes me more than Julie loves me",
|
|
8
|
+
"He likes basketball more than baseball"]
|
|
9
|
+
bags = []
|
|
10
|
+
bags = [Counter(doc.lower().split()) for doc in docs]
|
|
11
|
+
|
|
12
|
+
vocabulary = sorted(list(set(itertools.chain(*[list(bag) for bag in bags]))))
|
|
13
|
+
|
|
14
|
+
vec_list = []
|
|
15
|
+
for bag in bags:
|
|
16
|
+
vec_list.append([bag[word] for word in vocabulary])
|
|
17
|
+
|
|
18
|
+
def normalize_tf(tf):
|
|
19
|
+
if tf == 0:
|
|
20
|
+
return 0.0
|
|
21
|
+
else:
|
|
22
|
+
return 1.0 + log(tf)
|
|
23
|
+
|
|
24
|
+
tf_vec_list = []
|
|
25
|
+
for vec in vec_list:
|
|
26
|
+
tf_vec_list.append([normalize_tf(term) for term in vec])
|
|
27
|
+
|
|
28
|
+
ndocs = len(docs)
|
|
29
|
+
vec_df = [(v, sum([b[v] for b in bags])) for v in vocabulary]
|
|
30
|
+
|
|
31
|
+
def idf(df, ndocs):
|
|
32
|
+
return 1.0 + log(ndocs/(df + 1))
|
|
33
|
+
|
|
34
|
+
idf_vocab = [(word, idf(df, ndocs)) for word, df in vec_df]
|
|
35
|
+
idf_vector = np.array([value for word, value in idf_vocab])
|
|
36
|
+
|
|
37
|
+
matrix_tfidf = np.array(tf_vec_list) * idf_vector
|
|
38
|
+
|
|
39
|
+
matrix_tfidf_l2 = matrix_tfidf / np.linalg.norm(matrix_tfidf, axis=1, keepdims=True)
|
|
40
|
+
np.set_printoptions(linewidth=200)
|
|
41
|
+
print(matrix_tfidf_l2)
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
snippetcards/__init__.py,sha256=qLC7fP-ZfwM3KG7ask3BxhzqUqyyzmfncuiEncUxJz4,790
|
|
2
|
+
snippetcards/snippets/gradient_descent.txt,sha256=--NGlejBwLLo0Hr7JdA5qpWFC7brXUzchwEXF2S_mZQ,493
|
|
3
|
+
snippetcards/snippets/gradient_descent_short.txt,sha256=SXsXh8MiobfeUq9thLukCX_jPp-BABHR5URv2LtQLxA,388
|
|
4
|
+
snippetcards/snippets/neural_network.txt,sha256=km6tnIJxvS0J4UmBObmumx6z7_ETCThzAZKZxgQta4Q,1943
|
|
5
|
+
snippetcards/snippets/perceptron_svm.txt,sha256=aCj7HRw5aNQhPFklAq5lniPakJjcBG618wQ-Iv2aUXI,1587
|
|
6
|
+
snippetcards/snippets/tf_idf.txt,sha256=WCKupv8wibkNHn-nqzDq3Hm4_wf7ktncbzHd121mNUk,1293
|
|
7
|
+
snippetcards/snippets/tf_idf_alt.txt,sha256=gjYE2maLrWLkrp9tdURPDazLJtpJSYrcQyWs2oZpcUw,1165
|
|
8
|
+
snippetcards-0.1.0.dist-info/METADATA,sha256=aoC4V50XRn8Xi2uA35PhmHNKNG2dyIwwgQXEfHLeTYI,133
|
|
9
|
+
snippetcards-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
10
|
+
snippetcards-0.1.0.dist-info/top_level.txt,sha256=xPkW7ZWZaBAt3lkKnOd4MiSjf44d0GKvDNDIw9SAMwU,13
|
|
11
|
+
snippetcards-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
snippetcards
|