-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
447 lines (350 loc) · 15.4 KB
/
main.py
File metadata and controls
447 lines (350 loc) · 15.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
# -*- coding: utf-8 -*-
"""Q1.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1HDqg5KDdzVDH-JncrXrBqcKx8U35oU3m
# Function Approximation using Neural Networks
## Introduction
This Python code demonstrates how to approximate various functions using a multilayer perceptron (MLP) neural network. The code is divided into four sections, each focusing on a different function:
1. Simple Function: `f(x) = x^2`
2. Polynomial Function: `f(x) = x^3 - 2x^2 + 3x - 1`
3. Trigonometric Function: `f(x) = sin(2x) + cos(3x)`
4. Complex Function: A piecewise function with different expressions for different intervals of the input domain.
## Importing Libaries
"""
import numpy as np
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.layers import Dense
from sklearn.preprocessing import MinMaxScaler
from sklearn.model_selection import KFold
"""## Q1 : Simple Function"""
# Step 1: Generating synthetic data (Simple function)
np.random.seed(0)
# Simple function
def simple_function(x):
return x**2
# Generate training data
num_points_train = 1000
X_train = np.linspace(0, 2, num_points_train).reshape(-1, 1) # Input domain
y_train = np.array([simple_function(x[0]) for x in X_train]).reshape(-1, 1)
# Generate test data
num_points_test = 101
X_test = np.linspace(0, 2, num_points_test).reshape(-1, 1) # Test input domain
y_test = np.array([simple_function(x[0]) for x in X_test]).reshape(-1, 1)
# Step 2: Scaling the input data
scaler = MinMaxScaler(feature_range=(-1, 1))
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
# Step 3: Defining the neural network architecture
model = Sequential()
model.add(Dense(10, input_dim=1, activation='relu'))
model.add(Dense(10, activation='relu'))
model.add(Dense(1)) # Output layer
# Step 4: Compiling the model
model.compile(loss='mean_squared_error', optimizer='adam', metrics=['mae','mse'])
model.summary()
# Step 5: Training the model with cross-validation
kfold = KFold(n_splits=5, shuffle=True, random_state=42)
history = []
mse_scores = []
mae_scores = []
best_fold_idx = None
best_val_loss = np.inf
for fold_idx, (train_idx, val_idx) in enumerate(kfold.split(X_train_scaled, y_train)):
X_train_cv, X_val_cv = X_train_scaled[train_idx], X_train_scaled[val_idx]
y_train_cv, y_val_cv = y_train[train_idx], y_train[val_idx]
history_cv = model.fit(X_train_cv, y_train_cv, epochs=100, batch_size=10, verbose=0,
validation_data=(X_val_cv, y_val_cv))
history.append(history_cv)
mse_val = model.evaluate(X_val_cv, y_val_cv, verbose=0)[0]
mae_val = model.evaluate(X_val_cv, y_val_cv, verbose=0)[1]
mse_scores.append(mse_val)
mae_scores.append(mae_val)
print(f"Fold {len(mse_scores)}: MSE = {mse_val:.4f}, MAE = {mae_val:.4f}")
# Keep track of the best fold
if mse_val < best_val_loss:
best_val_loss = mse_val
best_fold_idx = fold_idx
print(f"\nAverage MSE: {np.mean(mse_scores):.4f}")
print(f"Average MAE: {np.mean(mae_scores):.4f}")
# Step 6: Inverse scaling for visualization
X_test_inverse = scaler.inverse_transform(X_test_scaled)
# Step 7: Plot the best fold prediction
best_fold_train_idx, best_fold_val_idx = list(kfold.split(X_train_scaled, y_train))[best_fold_idx]
X_train_best, X_val_best = X_train_scaled[best_fold_train_idx], X_train_scaled[best_fold_val_idx]
y_train_best, y_val_best = y_train[best_fold_train_idx], y_train[best_fold_val_idx]
# Step 8: Finding the best Fold
model.fit(X_train_best, y_train_best, epochs=100, batch_size=10, verbose=0, validation_data=(X_val_best, y_val_best))
y_pred_best = model.predict(X_test_scaled)
# Step 9: Ploting the best Model
plt.figure(figsize=(10, 6))
plt.plot(X_test_inverse, y_test, color='green', label='True Function')
plt.plot(X_test_inverse, y_pred_best, color='blue', label='Best Fold Prediction')
plt.title('Approximating Function with MLP (with Scaling) - Best Fold')
plt.xlabel('Input')
plt.ylabel('Output')
plt.legend()
plt.show()
# Step 10: Plot training and validation loss for all folds
for i, hist in enumerate(history):
plt.figure()
plt.plot(hist.history['loss'], label='Train Loss')
plt.plot(hist.history['val_loss'], label='Validation Loss')
plt.title(f'Training and Validation Loss (Fold {i+1})')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.show()
"""## Q2: Polynomial function
"""
# Step 1: Generating synthetic data (Polynomial function)
# Polynomial function
def polynomial_function(x):
return x**3 - 2*x**2 + 3*x - 1
# Generate training data
num_points_train = 1000
X_train = np.linspace(0, 7, num_points_train).reshape(-1, 1) # Input domain
y_train = np.array([polynomial_function(x[0]) for x in X_train]).reshape(-1, 1)
# Generate test data
num_points_test = 101
X_test = np.linspace(0, 7, num_points_test).reshape(-1, 1) # Test input domain
y_test = np.array([polynomial_function(x[0]) for x in X_test]).reshape(-1, 1)
# Step 2: Scaling the input data
scaler = MinMaxScaler(feature_range=(-1, 1))
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
# Step 3: Defining the neural network architecture
model = Sequential()
model.add(Dense(10, input_dim=1, activation='relu'))
model.add(Dense(20, activation='relu'))
model.add(Dense(10, activation='relu'))
model.add(Dense(1)) # Output layer
# Step 4: Compiling the model
model.compile(loss='mean_squared_error', optimizer='adam', metrics=['mae','mse'])
model.summary()
# Step 5: Training the model with cross-validation
kfold = KFold(n_splits=5, shuffle=True, random_state=42)
history = []
mse_scores = []
mae_scores = []
best_fold_idx = None
best_val_loss = np.inf
for fold_idx, (train_idx, val_idx) in enumerate(kfold.split(X_train_scaled, y_train)):
X_train_cv, X_val_cv = X_train_scaled[train_idx], X_train_scaled[val_idx]
y_train_cv, y_val_cv = y_train[train_idx], y_train[val_idx]
history_cv = model.fit(X_train_cv, y_train_cv, epochs=100, batch_size=10, verbose=0,
validation_data=(X_val_cv, y_val_cv))
history.append(history_cv)
mse_val = model.evaluate(X_val_cv, y_val_cv, verbose=0)[0]
mae_val = model.evaluate(X_val_cv, y_val_cv, verbose=0)[1]
mse_scores.append(mse_val)
mae_scores.append(mae_val)
print(f"Fold {len(mse_scores)}: MSE = {mse_val:.4f}, MAE = {mae_val:.4f}")
# Keep track of the best fold
if mse_val < best_val_loss:
best_val_loss = mse_val
best_fold_idx = fold_idx
print(f"\nAverage MSE: {np.mean(mse_scores):.4f}")
print(f"Average MAE: {np.mean(mae_scores):.4f}")
# Step 6: Inverse scaling for visualization
X_test_inverse = scaler.inverse_transform(X_test_scaled)
# Step 7: Plot the best fold prediction
best_fold_train_idx, best_fold_val_idx = list(kfold.split(X_train_scaled, y_train))[best_fold_idx]
X_train_best, X_val_best = X_train_scaled[best_fold_train_idx], X_train_scaled[best_fold_val_idx]
y_train_best, y_val_best = y_train[best_fold_train_idx], y_train[best_fold_val_idx]
# Step 8: Finding the best Fold
model.fit(X_train_best, y_train_best, epochs=100, batch_size=10, verbose=0, validation_data=(X_val_best, y_val_best))
y_pred_best = model.predict(X_test_scaled)
# Step 9: Ploting the best Model
plt.figure(figsize=(10, 6))
plt.plot(X_test_inverse, y_test, color='green', label='True Function')
plt.plot(X_test_inverse, y_pred_best, color='blue', label='Best Fold Prediction')
plt.title('Approximating Function with MLP (with Scaling) - Best Fold')
plt.xlabel('Input')
plt.ylabel('Output')
plt.legend()
plt.show()
# Step 10: Plot training and validation loss for all folds
for i, hist in enumerate(history):
plt.figure()
plt.plot(hist.history['loss'], label='Train Loss')
plt.plot(hist.history['val_loss'], label='Validation Loss')
plt.title(f'Training and Validation Loss (Fold {i+1})')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.show()
"""## Q3: Trigonometric function
"""
# Step 1: Generating synthetic data (Trigonometric function)
def trigonometric_function(x):
return np.sin(2*x) + np.cos(3*x)
# Generate training data
num_points_train = 1000
X_train = np.linspace(0, 2*np.pi, num_points_train).reshape(-1, 1) # Input domain
y_train = np.array([trigonometric_function(x[0]) for x in X_train]).reshape(-1, 1)
# Generate test data
num_points_test = 101
X_test = np.linspace(0, 2*np.pi, num_points_test).reshape(-1, 1) # Test input domain
y_test = np.array([trigonometric_function(x[0]) for x in X_test]).reshape(-1, 1)
# Step 2: Scaling the input data
scaler = MinMaxScaler(feature_range=(-1, 1))
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
# Step 3: Defining the neural network architecture
model = Sequential()
model.add(Dense(10, input_dim=1, activation='relu'))
model.add(Dense(10, activation='relu'))
model.add(Dense(10, activation='relu'))
model.add(Dense(1)) # Output layer
# Step 4: Compiling the model
model.compile(loss='mean_squared_error', optimizer='adam', metrics=['mae','mse'])
model.summary()
# Step 5: Training the model with cross-validation
kfold = KFold(n_splits=5, shuffle=True, random_state=42)
history = []
mse_scores = []
mae_scores = []
best_fold_idx = None
best_val_loss = np.inf
for fold_idx, (train_idx, val_idx) in enumerate(kfold.split(X_train_scaled, y_train)):
X_train_cv, X_val_cv = X_train_scaled[train_idx], X_train_scaled[val_idx]
y_train_cv, y_val_cv = y_train[train_idx], y_train[val_idx]
history_cv = model.fit(X_train_cv, y_train_cv, epochs=100, batch_size=10, verbose=0,
validation_data=(X_val_cv, y_val_cv))
history.append(history_cv)
mse_val = model.evaluate(X_val_cv, y_val_cv, verbose=0)[0]
mae_val = model.evaluate(X_val_cv, y_val_cv, verbose=0)[1]
mse_scores.append(mse_val)
mae_scores.append(mae_val)
print(f"Fold {len(mse_scores)}: MSE = {mse_val:.4f}, MAE = {mae_val:.4f}")
# Keep track of the best fold
if mse_val < best_val_loss:
best_val_loss = mse_val
best_fold_idx = fold_idx
print(f"\nAverage MSE: {np.mean(mse_scores):.4f}")
print(f"Average MAE: {np.mean(mae_scores):.4f}")
# Step 6: Inverse scaling for visualization
X_test_inverse = scaler.inverse_transform(X_test_scaled)
# Step 7: Plot the best fold prediction
best_fold_train_idx, best_fold_val_idx = list(kfold.split(X_train_scaled, y_train))[best_fold_idx]
X_train_best, X_val_best = X_train_scaled[best_fold_train_idx], X_train_scaled[best_fold_val_idx]
y_train_best, y_val_best = y_train[best_fold_train_idx], y_train[best_fold_val_idx]
# Step 8: Finding the best Fold
model.fit(X_train_best, y_train_best, epochs=100, batch_size=10, verbose=0, validation_data=(X_val_best, y_val_best))
y_pred_best = model.predict(X_test_scaled)
# Step 9: Ploting the best Model
plt.figure(figsize=(10, 6))
plt.plot(X_test_inverse, y_test, color='green', label='True Function')
plt.plot(X_test_inverse, y_pred_best, color='blue', label='Best Fold Prediction')
plt.title('Approximating Function with MLP (with Scaling) - Best Fold')
plt.xlabel('Input')
plt.ylabel('Output')
plt.legend()
plt.show()
# Step 10: Plot training and validation loss for all folds
for i, hist in enumerate(history):
plt.figure()
plt.plot(hist.history['loss'], label='Train Loss')
plt.plot(hist.history['val_loss'], label='Validation Loss')
plt.title(f'Training and Validation Loss (Fold {i+1})')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.show()
"""## Q4: Complex function
"""
# Step 1: Generating synthetic data (Complex function)
def complex_function(x):
if x < np.pi/3:
return np.sin(x)
elif x == np.pi/3:
return 0.5 # Ensure continuity at π/3
elif x < np.pi:
return np.cos(2 * x)
elif x == np.pi:
return np.log(np.pi + 1) # Ensure continuity at π
elif x < 3 * np.pi / 2:
return np.log(x - np.pi + 1)
elif x == 3 * np.pi / 2:
return 3 * np.pi / 2 # Ensure continuity at 3π/2
elif x < 2 * np.pi:
return x - 3 * np.pi / 2
else: # x == 2 * np.pi
return 0 # Ensure continuity at 2π
# Generate training data
num_points_train = 1000
X_train = np.linspace(0, 2*np.pi, num_points_train).reshape(-1, 1) # Input domain
y_train = np.array([complex_function(x[0]) for x in X_train]).reshape(-1, 1)
# Generate test data
num_points_test = 101
X_test = np.linspace(0, 2*np.pi, num_points_test).reshape(-1, 1) # Test input domain
y_test = np.array([complex_function(x[0]) for x in X_test]).reshape(-1, 1)
# Step 2: Scaling the input data
scaler = MinMaxScaler(feature_range=(-1, 1))
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
# Step 3: Defining the neural network architecture
model = Sequential()
model.add(Dense(10, input_dim=1, activation='relu'))
model.add(Dense(10, activation='relu'))
model.add(Dense(10, activation='relu'))
model.add(Dense(10, activation='relu'))
model.add(Dense(10, activation='relu'))
model.add(Dense(1)) # Output layer
# Step 4: Compiling the model
model.compile(loss='mean_squared_error', optimizer='adam', metrics=['mae','mse'])
model.summary()
# Step 5: Training the model with cross-validation
kfold = KFold(n_splits=5, shuffle=True, random_state=42)
history = []
mse_scores = []
mae_scores = []
best_fold_idx = None
best_val_loss = np.inf
for fold_idx, (train_idx, val_idx) in enumerate(kfold.split(X_train_scaled, y_train)):
X_train_cv, X_val_cv = X_train_scaled[train_idx], X_train_scaled[val_idx]
y_train_cv, y_val_cv = y_train[train_idx], y_train[val_idx]
history_cv = model.fit(X_train_cv, y_train_cv, epochs=100, batch_size=10, verbose=0,
validation_data=(X_val_cv, y_val_cv))
history.append(history_cv)
mse_val = model.evaluate(X_val_cv, y_val_cv, verbose=0)[0]
mae_val = model.evaluate(X_val_cv, y_val_cv, verbose=0)[1]
mse_scores.append(mse_val)
mae_scores.append(mae_val)
print(f"Fold {len(mse_scores)}: MSE = {mse_val:.4f}, MAE = {mae_val:.4f}")
# Keep track of the best fold
if mse_val < best_val_loss:
best_val_loss = mse_val
best_fold_idx = fold_idx
print(f"\nAverage MSE: {np.mean(mse_scores):.4f}")
print(f"Average MAE: {np.mean(mae_scores):.4f}")
# Step 6: Inverse scaling for visualization
X_test_inverse = scaler.inverse_transform(X_test_scaled)
# Step 7: Plot the best fold prediction
best_fold_train_idx, best_fold_val_idx = list(kfold.split(X_train_scaled, y_train))[best_fold_idx]
X_train_best, X_val_best = X_train_scaled[best_fold_train_idx], X_train_scaled[best_fold_val_idx]
y_train_best, y_val_best = y_train[best_fold_train_idx], y_train[best_fold_val_idx]
# Step 8: Finding the best Fold
model.fit(X_train_best, y_train_best, epochs=100, batch_size=10, verbose=0, validation_data=(X_val_best, y_val_best))
y_pred_best = model.predict(X_test_scaled)
# Step 9: Ploting the best Model
plt.figure(figsize=(10, 6))
plt.plot(X_test_inverse, y_test, color='green', label='True Function')
plt.plot(X_test_inverse, y_pred_best, color='blue', label='Best Fold Prediction')
plt.title('Approximating Function with MLP (with Scaling) - Best Fold')
plt.xlabel('Input')
plt.ylabel('Output')
plt.legend()
plt.show()
# Step 10: Plot training and validation loss for all folds
for i, hist in enumerate(history):
plt.figure()
plt.plot(hist.history['loss'], label='Train Loss')
plt.plot(hist.history['val_loss'], label='Validation Loss')
plt.title(f'Training and Validation Loss (Fold {i+1})')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.show()