fomltools 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.
- fomltools/__init__.py +10 -0
- fomltools/labs/__init__.py +5 -0
- fomltools/labs/lab01.py +210 -0
- fomltools/labs/lab02.py +233 -0
- fomltools/labs/lab03.py +62 -0
- fomltools/labs/lab04.py +81 -0
- fomltools/labs/lab05.py +171 -0
- fomltools/labs/lab06.py +174 -0
- fomltools/labs/lab07.py +192 -0
- fomltools/labs/lab08.py +202 -0
- fomltools/labs/lab09.py +335 -0
- fomltools/labs/lab10.py +111 -0
- fomltools/labs/lab11.py +103 -0
- fomltools/labs/lab12.py +68 -0
- fomltools/labs/lab14.py +251 -0
- fomltools-0.1.0.dist-info/METADATA +43 -0
- fomltools-0.1.0.dist-info/RECORD +20 -0
- fomltools-0.1.0.dist-info/WHEEL +5 -0
- fomltools-0.1.0.dist-info/licenses/LICENSE +21 -0
- fomltools-0.1.0.dist-info/top_level.txt +1 -0
fomltools/labs/lab05.py
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
1
|
+
"""Lab 5 code imported from the uploaded FOML notebook."""
|
|
2
|
+
|
|
3
|
+
def run():
|
|
4
|
+
"""Run the original lab code in notebook-cell order."""
|
|
5
|
+
import numpy as np
|
|
6
|
+
import pandas as pd
|
|
7
|
+
|
|
8
|
+
def sigmoid(z):
|
|
9
|
+
s = 1/(1+np.exp(-z))
|
|
10
|
+
return s
|
|
11
|
+
|
|
12
|
+
def tan(h):
|
|
13
|
+
s = (np.exp(h)-np.exp(-h))/(np.exp(h)+np.exp(-h))
|
|
14
|
+
return s
|
|
15
|
+
|
|
16
|
+
np.random.seed(42)
|
|
17
|
+
x=np.random.randn(3,3)
|
|
18
|
+
print(x)
|
|
19
|
+
|
|
20
|
+
print(sigmoid(x))
|
|
21
|
+
|
|
22
|
+
print(tan(x))
|
|
23
|
+
|
|
24
|
+
np.random.seed(1)
|
|
25
|
+
X=np.random.randn(2,3)
|
|
26
|
+
Y=(np.random.randn(1,3)>0)
|
|
27
|
+
|
|
28
|
+
print(X)
|
|
29
|
+
print(X.shape)
|
|
30
|
+
print(Y)
|
|
31
|
+
print(Y.shape)
|
|
32
|
+
|
|
33
|
+
def layer_sizes(x,y,no_neurons):
|
|
34
|
+
n_x=X.shape[0]
|
|
35
|
+
n_h=no_neurons #no of neurons in that hidden layer
|
|
36
|
+
n_y=Y.shape[0]
|
|
37
|
+
return(n_x,n_h,n_y)
|
|
38
|
+
|
|
39
|
+
n_x,n_h,n_y=layer_sizes(X,Y,4)
|
|
40
|
+
print(n_x,n_h,n_y)
|
|
41
|
+
|
|
42
|
+
def initialize_parameters(n_x,n_h,n_y):
|
|
43
|
+
np.random.seed(2)
|
|
44
|
+
w1=np.random.randn(n_h,n_x)*0.01
|
|
45
|
+
b1 = np.zeros((n_h,1))
|
|
46
|
+
w2 = np.random.randn(n_y,n_h)*0.01
|
|
47
|
+
b2 = np.zeros((n_y,1))
|
|
48
|
+
parameters={
|
|
49
|
+
"w1":w1,
|
|
50
|
+
"b1":b1,
|
|
51
|
+
"w2":w2,
|
|
52
|
+
"b2":b2
|
|
53
|
+
}
|
|
54
|
+
return parameters
|
|
55
|
+
|
|
56
|
+
p=initialize_parameters(n_x,n_h,n_y)
|
|
57
|
+
|
|
58
|
+
p
|
|
59
|
+
|
|
60
|
+
def forward_propogation(X,p):
|
|
61
|
+
w1=p["w1"]
|
|
62
|
+
b1=p["b1"]
|
|
63
|
+
w2=p['w2']
|
|
64
|
+
b2=p['b2']
|
|
65
|
+
|
|
66
|
+
z1=np.dot(w1,X)+b1
|
|
67
|
+
a1=tan(z1)
|
|
68
|
+
z2=np.dot(w2,a1)+b2
|
|
69
|
+
a2=sigmoid(z2)
|
|
70
|
+
|
|
71
|
+
cache={
|
|
72
|
+
"a1":w1,
|
|
73
|
+
"z1":z1,
|
|
74
|
+
"a2":a2,
|
|
75
|
+
"z2":z2
|
|
76
|
+
}
|
|
77
|
+
return a2,cache
|
|
78
|
+
|
|
79
|
+
a2,cache=forward_propogation(X,p)
|
|
80
|
+
|
|
81
|
+
a2
|
|
82
|
+
|
|
83
|
+
cache
|
|
84
|
+
|
|
85
|
+
def compute_cost(a2,Y,parameters):
|
|
86
|
+
m=Y.shape[1]
|
|
87
|
+
logprobs=np.multiply(np.log(a2),Y)+np.multiply(np.log(1-a2),(1-Y))
|
|
88
|
+
cost=-np.sum(logprobs)/m
|
|
89
|
+
cost=float(np.squeeze(cost))
|
|
90
|
+
return cost
|
|
91
|
+
|
|
92
|
+
compute_cost(a2,Y,p)
|
|
93
|
+
|
|
94
|
+
np.random.seed(1)
|
|
95
|
+
X1 = np.random.randn(5,3)
|
|
96
|
+
Y1 = (np.random.randn(1,3)>0)
|
|
97
|
+
|
|
98
|
+
X1
|
|
99
|
+
|
|
100
|
+
def layer_sizes(X1,Y1,layers1,layers2):
|
|
101
|
+
n_x = X1.shape[0]
|
|
102
|
+
n_h1 = layers1
|
|
103
|
+
n_h2 = layers2
|
|
104
|
+
n_y = Y1.shape[0]
|
|
105
|
+
return(n_x,n_h1,n_h2,n_y)
|
|
106
|
+
|
|
107
|
+
n_x,n_h1,n_h2,n_y = layer_sizes(X1,Y1,4,2)
|
|
108
|
+
|
|
109
|
+
n_x,n_h1,n_h2,n_y
|
|
110
|
+
|
|
111
|
+
def initialize_parameters(n_x,n_h1,n_h2,n_y):
|
|
112
|
+
np.random.seed(2)
|
|
113
|
+
w1 = np.random.randn(n_h1,n_x)*0.01
|
|
114
|
+
b1 = np.zeros((n_h1,1))
|
|
115
|
+
w2 = np.random.randn(n_h2,n_h1)*0.01
|
|
116
|
+
b2 = np.zeros((n_h2,1))
|
|
117
|
+
w3 = np.random.randn(n_y,n_h2)*0.01
|
|
118
|
+
b3 = np.zeros((n_y,1))
|
|
119
|
+
parameters={
|
|
120
|
+
"w1":w1,
|
|
121
|
+
"b1":b1,
|
|
122
|
+
"w2":w2,
|
|
123
|
+
"b2":b2,
|
|
124
|
+
"w3":w3,
|
|
125
|
+
"b3":b3
|
|
126
|
+
}
|
|
127
|
+
return parameters
|
|
128
|
+
|
|
129
|
+
p=initialize_parameters(n_x,n_h1,n_h2,n_y)
|
|
130
|
+
|
|
131
|
+
p
|
|
132
|
+
|
|
133
|
+
def forward_propogation(X,p):
|
|
134
|
+
w1=p["w1"]
|
|
135
|
+
b1=p["b1"]
|
|
136
|
+
w2=p['w2']
|
|
137
|
+
b2=p['b2']
|
|
138
|
+
w3=p['w3']
|
|
139
|
+
b3=p['b3']
|
|
140
|
+
|
|
141
|
+
z1=np.dot(w1,X)+b1
|
|
142
|
+
a1=tan(z1)
|
|
143
|
+
z2=np.dot(w2,a1)+b2
|
|
144
|
+
a2=tan(z2)
|
|
145
|
+
z3=np.dot(w3,a2)+b3
|
|
146
|
+
a3=sigmoid(z3)
|
|
147
|
+
|
|
148
|
+
cache={
|
|
149
|
+
"a1":w1,
|
|
150
|
+
"z1":z1,
|
|
151
|
+
"a2":a2,
|
|
152
|
+
"z2":z2,
|
|
153
|
+
"a3":a3,
|
|
154
|
+
"z3":z3
|
|
155
|
+
}
|
|
156
|
+
return a3,cache
|
|
157
|
+
|
|
158
|
+
a3,cache=forward_propogation(X1,p)
|
|
159
|
+
|
|
160
|
+
a3
|
|
161
|
+
|
|
162
|
+
cache
|
|
163
|
+
|
|
164
|
+
def compute_cost(a3,Y,parameters):
|
|
165
|
+
m=Y.shape[1]
|
|
166
|
+
logprobs=np.multiply(np.log(a3),Y)+np.multiply(np.log(1-a3),(1-Y))
|
|
167
|
+
cost=-np.sum(logprobs)/m
|
|
168
|
+
cost=float(np.squeeze(cost))
|
|
169
|
+
return cost
|
|
170
|
+
|
|
171
|
+
compute_cost(a3,Y,p)
|
fomltools/labs/lab06.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
"""Lab 6 code imported from the uploaded FOML notebook."""
|
|
2
|
+
|
|
3
|
+
def run():
|
|
4
|
+
"""Run the original lab code in notebook-cell order."""
|
|
5
|
+
# Activation Function
|
|
6
|
+
import numpy as np
|
|
7
|
+
np.random.seed(1)
|
|
8
|
+
X=np.random.randn(2,3)
|
|
9
|
+
print(X)
|
|
10
|
+
|
|
11
|
+
# 1. Sigmoid Function
|
|
12
|
+
def sigmoid(z):
|
|
13
|
+
s = 1/(1+np.exp(-z))
|
|
14
|
+
return s
|
|
15
|
+
|
|
16
|
+
s = sigmoid(X)
|
|
17
|
+
print(s)
|
|
18
|
+
|
|
19
|
+
# 2. tanh function
|
|
20
|
+
def tan(z):
|
|
21
|
+
s=(np.exp(z)-np.exp(-z))/(np.exp(z)+np.exp(-z))
|
|
22
|
+
return s
|
|
23
|
+
|
|
24
|
+
t = tan(X)
|
|
25
|
+
print(t)
|
|
26
|
+
|
|
27
|
+
# 1. Input X and Y
|
|
28
|
+
np.random.seed(1)
|
|
29
|
+
X = np.random.randn(2,3)
|
|
30
|
+
Y = (np.random.randn(1,3)>0)
|
|
31
|
+
|
|
32
|
+
print(X)
|
|
33
|
+
print()
|
|
34
|
+
print(X.shape)
|
|
35
|
+
print()
|
|
36
|
+
print(Y)
|
|
37
|
+
|
|
38
|
+
# 2. Define shape
|
|
39
|
+
def layer_sizes(X,Y,layers):
|
|
40
|
+
n_x = X.shape[0]
|
|
41
|
+
n_h = layers
|
|
42
|
+
n_y = Y.shape[0]
|
|
43
|
+
return n_x, n_h, n_y
|
|
44
|
+
|
|
45
|
+
n_x,n_h,n_y = layer_sizes(X,Y,4)
|
|
46
|
+
|
|
47
|
+
print("n_x (no. of inputs): ", n_x)
|
|
48
|
+
print("n_h (no. of hidden layers/neurons): ", n_h)
|
|
49
|
+
print("n_y (np. of outputs): ", n_y)
|
|
50
|
+
|
|
51
|
+
# 3. Initializing parameters
|
|
52
|
+
def initialize_parameters(n_x,n_h,n_y):
|
|
53
|
+
np.random.seed(2)
|
|
54
|
+
w1 = np.random.randn(n_h,n_x)*0.01
|
|
55
|
+
b1 = np.zeros((n_h,1))
|
|
56
|
+
w2 = np.random.randn(n_y,n_h)*0.01
|
|
57
|
+
b2 = np.zeros((n_y,1))
|
|
58
|
+
parameters = {'W1':w1,
|
|
59
|
+
'b1': b1,
|
|
60
|
+
'W2': w2,
|
|
61
|
+
'b2':b2}
|
|
62
|
+
return parameters
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
p = initialize_parameters(n_x,n_h,n_y)
|
|
66
|
+
|
|
67
|
+
p
|
|
68
|
+
|
|
69
|
+
# 4. Forward propogation
|
|
70
|
+
def forward_propogation(X,p):
|
|
71
|
+
w1 = p['W1']
|
|
72
|
+
b1 = p['b1']
|
|
73
|
+
w2 = p['W2']
|
|
74
|
+
b2 = p['b2']
|
|
75
|
+
|
|
76
|
+
z1 = np.dot(w1,X)+b1
|
|
77
|
+
A1 = tan(z1)
|
|
78
|
+
z2 = np.dot(w2,A1) + b2
|
|
79
|
+
A2 = sigmoid(z2)
|
|
80
|
+
|
|
81
|
+
cache = {'z1':z1,
|
|
82
|
+
'A1':A1,
|
|
83
|
+
'z2':z2,
|
|
84
|
+
'A2':A2}
|
|
85
|
+
return A2, cache
|
|
86
|
+
|
|
87
|
+
A2, cache = forward_propogation(X,p)
|
|
88
|
+
|
|
89
|
+
A2
|
|
90
|
+
|
|
91
|
+
cache
|
|
92
|
+
|
|
93
|
+
# 5. Calculate the cost
|
|
94
|
+
def compute_cost(A2, Y, parameters):
|
|
95
|
+
m = Y.shape[1]
|
|
96
|
+
logprobs = np.multiply(np.log(A2),Y) + np.multiply(np.log(1-A2),(1-Y))
|
|
97
|
+
cost = -np.sum(logprobs)/m
|
|
98
|
+
cost = float(np.squeeze(cost))
|
|
99
|
+
return cost
|
|
100
|
+
|
|
101
|
+
compute_cost(A2,Y,p)
|
|
102
|
+
|
|
103
|
+
# 6. Backward Propogation
|
|
104
|
+
def backward_propogation(parameters, cache,X,Y):
|
|
105
|
+
W1 = parameters["W1"]
|
|
106
|
+
b1 = parameters["b1"]
|
|
107
|
+
W2 = parameters["W2"]
|
|
108
|
+
b2 = parameters["b2"]
|
|
109
|
+
A1 = cache["A1"]
|
|
110
|
+
A2 = cache["A2"]
|
|
111
|
+
m = Y.size
|
|
112
|
+
|
|
113
|
+
dZ2 = A2-Y
|
|
114
|
+
dW2 = np.dot(dZ2,A1.T)/m
|
|
115
|
+
db2 = np.sum(dZ2,axis=1,keepdims=True)/m
|
|
116
|
+
dA1 = np.dot(W2.T, dZ2)
|
|
117
|
+
dZ1 = dA1*(1-np.power(A1,2))
|
|
118
|
+
dW1 = np.dot(dZ1, X.T)/m
|
|
119
|
+
db1 = np.sum(dZ1,axis=1,keepdims=True)/m
|
|
120
|
+
grades = {"dW2":dW2, "db2":db2, "dW1":dW1, "db1":db1}
|
|
121
|
+
return grades
|
|
122
|
+
|
|
123
|
+
grades = backward_propogation(p,cache,X,Y)
|
|
124
|
+
print(grades)
|
|
125
|
+
|
|
126
|
+
# 7. Update grades
|
|
127
|
+
def update(parameters, grades, lr):
|
|
128
|
+
w1 = parameters['W1']
|
|
129
|
+
b1 = parameters['b1']
|
|
130
|
+
w2 = parameters['W2']
|
|
131
|
+
b2 = parameters['b2']
|
|
132
|
+
|
|
133
|
+
dW1=grades["dW1"]
|
|
134
|
+
db1=grades["db1"]
|
|
135
|
+
dW2=grades["dW2"]
|
|
136
|
+
db2=grades["db2"]
|
|
137
|
+
|
|
138
|
+
w1=w1-lr*dW1
|
|
139
|
+
b1=b1-lr*db1
|
|
140
|
+
w2=w2-lr*dW2
|
|
141
|
+
b2=b2-lr*db2
|
|
142
|
+
|
|
143
|
+
parameters={"W1":w1,"b1":b1,"W2":w2,"b2":b2}
|
|
144
|
+
return parameters
|
|
145
|
+
|
|
146
|
+
parameters=update(p,grades,lr=0.01)
|
|
147
|
+
print(parameters)
|
|
148
|
+
|
|
149
|
+
#8 create own NN
|
|
150
|
+
def Neural_Network(X,Y,layers,itr=10000,print_cost=False):
|
|
151
|
+
np.random.seed(3)
|
|
152
|
+
n_x,n_h,n_y = layer_sizes(X,Y,layers)
|
|
153
|
+
parameters = initialize_parameters(n_x,n_h,n_y)
|
|
154
|
+
|
|
155
|
+
for i in range(0,itr):
|
|
156
|
+
A2,cache = forward_propogation(X,parameters)
|
|
157
|
+
cost = compute_cost(A2,Y,parameters)
|
|
158
|
+
grades = backward_propogation(parameters,cache,X,Y)
|
|
159
|
+
parameters = update(parameters,grades,lr=0.01)
|
|
160
|
+
|
|
161
|
+
if print_cost and i%100==0:
|
|
162
|
+
print("Cost after iteration %i: %f" %(i,cost))
|
|
163
|
+
return parameters
|
|
164
|
+
|
|
165
|
+
parameters=Neural_Network(X,Y,4,itr=1001,print_cost=True)
|
|
166
|
+
|
|
167
|
+
# 9. Prediction
|
|
168
|
+
def predict_dec(parameters, X):
|
|
169
|
+
# Predict using forward propagation and a classification threshold of 0.5
|
|
170
|
+
a3, cache = forward_propogation(X, parameters)
|
|
171
|
+
predictions = (a3>0.5)
|
|
172
|
+
return predictions
|
|
173
|
+
|
|
174
|
+
predict_dec(p,X)
|
fomltools/labs/lab07.py
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
"""Lab 7 code imported from the uploaded FOML notebook."""
|
|
2
|
+
|
|
3
|
+
def run():
|
|
4
|
+
"""Run the original lab code in notebook-cell order."""
|
|
5
|
+
import numpy as np
|
|
6
|
+
import pandas as pd
|
|
7
|
+
import tensorflow as tf
|
|
8
|
+
from tensorflow import keras
|
|
9
|
+
from tensorflow.keras import layers
|
|
10
|
+
|
|
11
|
+
from sklearn.model_selection import train_test_split
|
|
12
|
+
from sklearn.preprocessing import StandardScaler
|
|
13
|
+
from sklearn.metrics import accuracy_score, confusion_matrix, classification_report, r2_score, mean_squared_error
|
|
14
|
+
from sklearn.dummy import DummyClassifier, DummyRegressor
|
|
15
|
+
|
|
16
|
+
import matplotlib.pyplot as plt
|
|
17
|
+
|
|
18
|
+
print("TensorFlow version:", tf.__version__)
|
|
19
|
+
np.random.seed(1)
|
|
20
|
+
tf.random.set_seed(1)
|
|
21
|
+
|
|
22
|
+
from sklearn.datasets import load_breast_cancer
|
|
23
|
+
|
|
24
|
+
data = load_breast_cancer()
|
|
25
|
+
X = data.data # shape (569, 30) -> rows = samples, cols = features
|
|
26
|
+
Y = data.target # shape (569,) -> 0 = malignant, 1 = benign
|
|
27
|
+
|
|
28
|
+
print("X shape:", X.shape)
|
|
29
|
+
print("Y shape:", Y.shape)
|
|
30
|
+
print("Classes:", data.target_names)
|
|
31
|
+
|
|
32
|
+
# train/test split + scaling (scaling matters a LOT for gradient descent to converge fast)
|
|
33
|
+
X_train, X_test, y_train, y_test = train_test_split(X, Y, test_size=0.2, random_state=1, stratify=Y)
|
|
34
|
+
|
|
35
|
+
scaler = StandardScaler()
|
|
36
|
+
X_train = scaler.fit_transform(X_train)
|
|
37
|
+
X_test = scaler.transform(X_test)
|
|
38
|
+
|
|
39
|
+
print("X_train:", X_train.shape, " X_test:", X_test.shape)
|
|
40
|
+
|
|
41
|
+
# Building the network — this replaces layer_sizes + initialize_parameters + forward_propagation
|
|
42
|
+
# from Lab 5/6, all in one Sequential model.
|
|
43
|
+
|
|
44
|
+
n_x = X_train.shape[1] # 30 input features
|
|
45
|
+
|
|
46
|
+
clf_model = keras.Sequential([
|
|
47
|
+
layers.Input(shape=(n_x,)),
|
|
48
|
+
layers.Dense(8, activation='relu'), # hidden layer 1 (like A1 = tanh(Z1) in Lab 6, using relu here)
|
|
49
|
+
layers.Dense(4, activation='relu'), # hidden layer 2
|
|
50
|
+
layers.Dense(1, activation='sigmoid') # output layer -> sigmoid, same as manual A2 = sigmoid(Z2)
|
|
51
|
+
])
|
|
52
|
+
|
|
53
|
+
clf_model.compile(
|
|
54
|
+
optimizer='adam', # replaces manual update_parameters (gradient descent)
|
|
55
|
+
loss='binary_crossentropy', # same cost formula as compute_cost() in Lab 6
|
|
56
|
+
metrics=['accuracy']
|
|
57
|
+
)
|
|
58
|
+
|
|
59
|
+
clf_model.summary()
|
|
60
|
+
|
|
61
|
+
# Training -- replaces the manual NN() loop (forward -> cost -> backward -> update, repeated)
|
|
62
|
+
history = clf_model.fit(
|
|
63
|
+
X_train, y_train,
|
|
64
|
+
validation_split=0.2,
|
|
65
|
+
epochs=60,
|
|
66
|
+
batch_size=16,
|
|
67
|
+
verbose=0
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
print("Final train loss:", history.history['loss'][-1])
|
|
71
|
+
print("Final val loss :", history.history['val_loss'][-1])
|
|
72
|
+
print("Final train acc :", history.history['accuracy'][-1])
|
|
73
|
+
print("Final val acc :", history.history['val_accuracy'][-1])
|
|
74
|
+
|
|
75
|
+
# Plot cost curve — same idea as the "Cost at iteration ..." prints in Lab 6's NN() function
|
|
76
|
+
plt.figure(figsize=(6,4))
|
|
77
|
+
plt.plot(history.history['loss'], label='train loss')
|
|
78
|
+
plt.plot(history.history['val_loss'], label='val loss')
|
|
79
|
+
plt.xlabel('epoch')
|
|
80
|
+
plt.ylabel('binary cross-entropy cost')
|
|
81
|
+
plt.title('Classification model — cost vs epoch')
|
|
82
|
+
plt.legend()
|
|
83
|
+
plt.show()
|
|
84
|
+
|
|
85
|
+
# predict_dec() equivalent from Lab 6: threshold at 0.5
|
|
86
|
+
y_prob = clf_model.predict(X_test, verbose=0).ravel()
|
|
87
|
+
y_pred = (y_prob > 0.5).astype(int)
|
|
88
|
+
|
|
89
|
+
test_loss, test_acc = clf_model.evaluate(X_test, y_test, verbose=0)
|
|
90
|
+
print("Test loss:", test_loss)
|
|
91
|
+
print("Test accuracy:", test_acc)
|
|
92
|
+
print()
|
|
93
|
+
print("Confusion matrix:\n", confusion_matrix(y_test, y_pred))
|
|
94
|
+
print()
|
|
95
|
+
print("Classification report:\n", classification_report(y_test, y_pred, target_names=data.target_names))
|
|
96
|
+
|
|
97
|
+
# Baseline check -- verify the model is actually better than guessing the majority class
|
|
98
|
+
dummy = DummyClassifier(strategy='most_frequent').fit(X_train, y_train)
|
|
99
|
+
dummy_acc = accuracy_score(y_test, dummy.predict(X_test))
|
|
100
|
+
print("Majority-class baseline accuracy:", dummy_acc)
|
|
101
|
+
print("Our TensorFlow model accuracy :", test_acc)
|
|
102
|
+
print("Model beats baseline?", test_acc > dummy_acc)
|
|
103
|
+
|
|
104
|
+
from sklearn.datasets import load_diabetes
|
|
105
|
+
|
|
106
|
+
reg_data = load_diabetes()
|
|
107
|
+
Xr = reg_data.data # shape (442, 10) -> 10 features
|
|
108
|
+
Yr = reg_data.target # shape (442,) -> continuous disease progression score
|
|
109
|
+
|
|
110
|
+
print("Xr shape:", Xr.shape)
|
|
111
|
+
print("Yr shape:", Yr.shape)
|
|
112
|
+
print("Yr sample values:", Yr[:5])
|
|
113
|
+
|
|
114
|
+
Xr_train, Xr_test, yr_train, yr_test = train_test_split(Xr, Yr, test_size=0.2, random_state=1)
|
|
115
|
+
|
|
116
|
+
scaler_r = StandardScaler()
|
|
117
|
+
Xr_train = scaler_r.fit_transform(Xr_train)
|
|
118
|
+
Xr_test = scaler_r.transform(Xr_test)
|
|
119
|
+
|
|
120
|
+
# scale target too -- helps gradient descent converge; we'll unscale predictions later
|
|
121
|
+
y_scaler = StandardScaler()
|
|
122
|
+
yr_train_s = y_scaler.fit_transform(yr_train.reshape(-1, 1)).ravel()
|
|
123
|
+
yr_test_s = y_scaler.transform(yr_test.reshape(-1, 1)).ravel()
|
|
124
|
+
|
|
125
|
+
print("Xr_train:", Xr_train.shape, " Xr_test:", Xr_test.shape)
|
|
126
|
+
|
|
127
|
+
n_x_r = Xr_train.shape[1] # 10 input features
|
|
128
|
+
|
|
129
|
+
reg_model = keras.Sequential([
|
|
130
|
+
layers.Input(shape=(n_x_r,)),
|
|
131
|
+
layers.Dense(16, activation='relu'), # hidden layer 1
|
|
132
|
+
layers.Dense(8, activation='relu'), # hidden layer 2
|
|
133
|
+
layers.Dense(1, activation='linear') # output layer -> linear (no squashing!) for regression
|
|
134
|
+
])
|
|
135
|
+
|
|
136
|
+
reg_model.compile(
|
|
137
|
+
optimizer='adam',
|
|
138
|
+
loss='mse', # Mean Squared Error -> the regression "cost function"
|
|
139
|
+
metrics=['mae']
|
|
140
|
+
)
|
|
141
|
+
|
|
142
|
+
reg_model.summary()
|
|
143
|
+
|
|
144
|
+
history_r = reg_model.fit(
|
|
145
|
+
Xr_train, yr_train_s,
|
|
146
|
+
validation_split=0.2,
|
|
147
|
+
epochs=150,
|
|
148
|
+
batch_size=16,
|
|
149
|
+
verbose=0
|
|
150
|
+
)
|
|
151
|
+
|
|
152
|
+
print("Final train loss (MSE):", history_r.history['loss'][-1])
|
|
153
|
+
print("Final val loss (MSE) :", history_r.history['val_loss'][-1])
|
|
154
|
+
|
|
155
|
+
plt.figure(figsize=(6,4))
|
|
156
|
+
plt.plot(history_r.history['loss'], label='train loss')
|
|
157
|
+
plt.plot(history_r.history['val_loss'], label='val loss')
|
|
158
|
+
plt.xlabel('epoch')
|
|
159
|
+
plt.ylabel('MSE cost')
|
|
160
|
+
plt.title('Regression model — cost vs epoch')
|
|
161
|
+
plt.legend()
|
|
162
|
+
plt.show()
|
|
163
|
+
|
|
164
|
+
yr_pred_s = reg_model.predict(Xr_test, verbose=0).ravel()
|
|
165
|
+
|
|
166
|
+
# un-scale predictions back to original target units
|
|
167
|
+
yr_pred = y_scaler.inverse_transform(yr_pred_s.reshape(-1, 1)).ravel()
|
|
168
|
+
|
|
169
|
+
r2 = r2_score(yr_test, yr_pred)
|
|
170
|
+
rmse = np.sqrt(mean_squared_error(yr_test, yr_pred))
|
|
171
|
+
|
|
172
|
+
print("R2 score:", r2)
|
|
173
|
+
print("RMSE :", rmse)
|
|
174
|
+
|
|
175
|
+
# Baseline check -- verify the model beats "always predict the mean"
|
|
176
|
+
dummy_r = DummyRegressor(strategy='mean').fit(Xr_train, yr_train)
|
|
177
|
+
dummy_pred = dummy_r.predict(Xr_test)
|
|
178
|
+
dummy_r2 = r2_score(yr_test, dummy_pred)
|
|
179
|
+
|
|
180
|
+
print("Mean-baseline R2 :", dummy_r2)
|
|
181
|
+
print("Our TensorFlow model R2:", r2)
|
|
182
|
+
print("Model beats baseline?", r2 > dummy_r2)
|
|
183
|
+
|
|
184
|
+
plt.figure(figsize=(5,5))
|
|
185
|
+
plt.scatter(yr_test, yr_pred, alpha=0.6)
|
|
186
|
+
lims = [min(yr_test.min(), yr_pred.min()), max(yr_test.max(), yr_pred.max())]
|
|
187
|
+
plt.plot(lims, lims, 'r--', label='perfect prediction')
|
|
188
|
+
plt.xlabel('Actual value')
|
|
189
|
+
plt.ylabel('Predicted value')
|
|
190
|
+
plt.title('Regression — predicted vs actual (test set)')
|
|
191
|
+
plt.legend()
|
|
192
|
+
plt.show()
|