semfnode 1.0.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.
- dnn/__init__.py +582 -0
- opti/__init__.py +350 -0
- semfnode-1.0.0.dist-info/METADATA +19 -0
- semfnode-1.0.0.dist-info/RECORD +6 -0
- semfnode-1.0.0.dist-info/WHEEL +5 -0
- semfnode-1.0.0.dist-info/top_level.txt +2 -0
dnn/__init__.py
ADDED
|
@@ -0,0 +1,582 @@
|
|
|
1
|
+
"""
|
|
2
|
+
DNN Practicals — Deep Neural Networks lab code bank.
|
|
3
|
+
|
|
4
|
+
Usage:
|
|
5
|
+
import dnn
|
|
6
|
+
dnn.prac1() # prints Practical 1 code
|
|
7
|
+
dnn.prac12() # prints Practical 12 code
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
__version__ = "1.0.0"
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _show(code: str) -> str:
|
|
14
|
+
print(code)
|
|
15
|
+
return code
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def prac1():
|
|
19
|
+
return _show('''# Practical No. 1
|
|
20
|
+
# Aim: Implement a Basic Neural Network in TensorFlow
|
|
21
|
+
|
|
22
|
+
import tensorflow as tf
|
|
23
|
+
from tensorflow.keras import layers, models
|
|
24
|
+
from tensorflow.keras.datasets import mnist
|
|
25
|
+
|
|
26
|
+
# Load and preprocess the MNIST dataset
|
|
27
|
+
(x_train, y_train), (x_test, y_test) = mnist.load_data()
|
|
28
|
+
x_train = x_train.reshape(-1, 784).astype('float32') / 255.0
|
|
29
|
+
x_test = x_test.reshape(-1, 784).astype('float32') / 255.0
|
|
30
|
+
|
|
31
|
+
# Build a basic feed-forward neural network
|
|
32
|
+
model = models.Sequential([
|
|
33
|
+
layers.Dense(128, activation='relu', input_shape=(784,)),
|
|
34
|
+
layers.Dense(64, activation='relu'),
|
|
35
|
+
layers.Dense(10, activation='softmax') # 10 output classes
|
|
36
|
+
])
|
|
37
|
+
|
|
38
|
+
# Compile the model
|
|
39
|
+
model.compile(optimizer='adam',
|
|
40
|
+
loss='sparse_categorical_crossentropy',
|
|
41
|
+
metrics=['accuracy'])
|
|
42
|
+
|
|
43
|
+
# Train the model
|
|
44
|
+
model.fit(x_train, y_train, epochs=5, batch_size=32, validation_split=0.1)
|
|
45
|
+
|
|
46
|
+
# Evaluate on test data
|
|
47
|
+
test_loss, test_acc = model.evaluate(x_test, y_test)
|
|
48
|
+
print(f"Test Accuracy: {test_acc:.4f}")
|
|
49
|
+
''')
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def prac2():
|
|
53
|
+
return _show('''# Practical No. 2
|
|
54
|
+
# Aim: Implement CNN with Keras for Image Classification
|
|
55
|
+
|
|
56
|
+
import tensorflow as tf
|
|
57
|
+
from tensorflow.keras import layers, models
|
|
58
|
+
from tensorflow.keras.datasets import cifar10
|
|
59
|
+
|
|
60
|
+
# Load and preprocess the CIFAR-10 dataset
|
|
61
|
+
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
|
|
62
|
+
x_train, x_test = x_train / 255.0, x_test / 255.0
|
|
63
|
+
|
|
64
|
+
# Build the CNN model
|
|
65
|
+
model = models.Sequential([
|
|
66
|
+
layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)),
|
|
67
|
+
layers.MaxPooling2D((2, 2)),
|
|
68
|
+
layers.Conv2D(64, (3, 3), activation='relu'),
|
|
69
|
+
layers.MaxPooling2D((2, 2)),
|
|
70
|
+
layers.Conv2D(64, (3, 3), activation='relu'),
|
|
71
|
+
layers.Flatten(),
|
|
72
|
+
layers.Dense(64, activation='relu'),
|
|
73
|
+
layers.Dense(10, activation='softmax')
|
|
74
|
+
])
|
|
75
|
+
|
|
76
|
+
# Compile and train the model
|
|
77
|
+
model.compile(optimizer='adam',
|
|
78
|
+
loss='sparse_categorical_crossentropy',
|
|
79
|
+
metrics=['accuracy'])
|
|
80
|
+
model.fit(x_train, y_train, epochs=5, batch_size=64, validation_split=0.1)
|
|
81
|
+
|
|
82
|
+
# Evaluate the model
|
|
83
|
+
test_loss, test_acc = model.evaluate(x_test, y_test)
|
|
84
|
+
print(f"Test Accuracy: {test_acc:.4f}")
|
|
85
|
+
''')
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def prac3():
|
|
89
|
+
return _show('''# Practical No. 3
|
|
90
|
+
# Aim: Implement ResNet in PyTorch
|
|
91
|
+
|
|
92
|
+
import torch
|
|
93
|
+
import torch.nn as nn
|
|
94
|
+
import torch.optim as optim
|
|
95
|
+
from torchvision import datasets, transforms
|
|
96
|
+
from torch.utils.data import DataLoader
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
# Define a basic Residual Block
|
|
100
|
+
class ResidualBlock(nn.Module):
|
|
101
|
+
def __init__(self, in_ch, out_ch, stride=1):
|
|
102
|
+
super().__init__()
|
|
103
|
+
self.conv1 = nn.Conv2d(in_ch, out_ch, 3, stride, 1)
|
|
104
|
+
self.bn1 = nn.BatchNorm2d(out_ch)
|
|
105
|
+
self.conv2 = nn.Conv2d(out_ch, out_ch, 3, 1, 1)
|
|
106
|
+
self.bn2 = nn.BatchNorm2d(out_ch)
|
|
107
|
+
self.relu = nn.ReLU(inplace=True)
|
|
108
|
+
|
|
109
|
+
# Shortcut connection to match dimensions
|
|
110
|
+
self.shortcut = nn.Sequential()
|
|
111
|
+
if stride != 1 or in_ch != out_ch:
|
|
112
|
+
self.shortcut = nn.Sequential(
|
|
113
|
+
nn.Conv2d(in_ch, out_ch, 1, stride),
|
|
114
|
+
nn.BatchNorm2d(out_ch))
|
|
115
|
+
|
|
116
|
+
def forward(self, x):
|
|
117
|
+
out = self.relu(self.bn1(self.conv1(x)))
|
|
118
|
+
out = self.bn2(self.conv2(out))
|
|
119
|
+
out += self.shortcut(x) # Residual (skip) connection
|
|
120
|
+
return self.relu(out)
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
# Simple ResNet-style model
|
|
124
|
+
class SimpleResNet(nn.Module):
|
|
125
|
+
def __init__(self, num_classes=10):
|
|
126
|
+
super().__init__()
|
|
127
|
+
self.layer1 = ResidualBlock(3, 16)
|
|
128
|
+
self.layer2 = ResidualBlock(16, 32, stride=2)
|
|
129
|
+
self.pool = nn.AdaptiveAvgPool2d(1)
|
|
130
|
+
self.fc = nn.Linear(32, num_classes)
|
|
131
|
+
|
|
132
|
+
def forward(self, x):
|
|
133
|
+
x = self.layer1(x)
|
|
134
|
+
x = self.layer2(x)
|
|
135
|
+
x = self.pool(x).flatten(1)
|
|
136
|
+
return self.fc(x)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
# Load CIFAR-10 dataset
|
|
140
|
+
transform = transforms.Compose([transforms.ToTensor()])
|
|
141
|
+
train_data = datasets.CIFAR10(root='./data', train=True, download=True, transform=transform)
|
|
142
|
+
train_loader = DataLoader(train_data, batch_size=64, shuffle=True)
|
|
143
|
+
|
|
144
|
+
# Train the model
|
|
145
|
+
model = SimpleResNet()
|
|
146
|
+
optimizer = optim.Adam(model.parameters(), lr=0.001)
|
|
147
|
+
criterion = nn.CrossEntropyLoss()
|
|
148
|
+
|
|
149
|
+
for epoch in range(3):
|
|
150
|
+
for images, labels in train_loader:
|
|
151
|
+
optimizer.zero_grad()
|
|
152
|
+
outputs = model(images)
|
|
153
|
+
loss = criterion(outputs, labels)
|
|
154
|
+
loss.backward()
|
|
155
|
+
optimizer.step()
|
|
156
|
+
print(f"Epoch {epoch+1} Loss: {loss.item():.4f}")
|
|
157
|
+
''')
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def prac4():
|
|
161
|
+
return _show('''# Practical No. 4
|
|
162
|
+
# Aim: Implement RNN for Time Series Prediction
|
|
163
|
+
|
|
164
|
+
import numpy as np
|
|
165
|
+
import tensorflow as tf
|
|
166
|
+
from tensorflow.keras import layers, models
|
|
167
|
+
|
|
168
|
+
# Generate a synthetic sine wave time series
|
|
169
|
+
t = np.linspace(0, 100, 1000)
|
|
170
|
+
data = np.sin(t) + np.random.normal(0, 0.05, size=len(t))
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
# Prepare sequences for supervised learning
|
|
174
|
+
def create_sequences(data, seq_len=20):
|
|
175
|
+
X, y = [], []
|
|
176
|
+
for i in range(len(data) - seq_len):
|
|
177
|
+
X.append(data[i:i + seq_len])
|
|
178
|
+
y.append(data[i + seq_len])
|
|
179
|
+
return np.array(X), np.array(y)
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
seq_len = 20
|
|
183
|
+
X, y = create_sequences(data, seq_len)
|
|
184
|
+
X = X.reshape(-1, seq_len, 1)
|
|
185
|
+
|
|
186
|
+
# Split into train/test sets
|
|
187
|
+
split = int(0.8 * len(X))
|
|
188
|
+
X_train, X_test = X[:split], X[split:]
|
|
189
|
+
y_train, y_test = y[:split], y[split:]
|
|
190
|
+
|
|
191
|
+
# Build a simple RNN model
|
|
192
|
+
model = models.Sequential([
|
|
193
|
+
layers.SimpleRNN(32, activation='tanh', input_shape=(seq_len, 1)),
|
|
194
|
+
layers.Dense(1)
|
|
195
|
+
])
|
|
196
|
+
model.compile(optimizer='adam', loss='mse')
|
|
197
|
+
model.fit(X_train, y_train, epochs=10, batch_size=16, validation_split=0.1)
|
|
198
|
+
|
|
199
|
+
# Evaluate the model
|
|
200
|
+
loss = model.evaluate(X_test, y_test)
|
|
201
|
+
print(f"Test MSE: {loss:.4f}")
|
|
202
|
+
''')
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def prac5():
|
|
206
|
+
return _show('''# Practical No. 5
|
|
207
|
+
# Aim: Implement LSTM for Sequence Generation
|
|
208
|
+
|
|
209
|
+
import numpy as np
|
|
210
|
+
import tensorflow as tf
|
|
211
|
+
from tensorflow.keras import layers, models
|
|
212
|
+
|
|
213
|
+
# Sample text corpus for character-level sequence generation
|
|
214
|
+
text = "deep learning models learn patterns from sequential data"
|
|
215
|
+
chars = sorted(list(set(text)))
|
|
216
|
+
char_to_idx = {c: i for i, c in enumerate(chars)}
|
|
217
|
+
idx_to_char = {i: c for i, c in enumerate(chars)}
|
|
218
|
+
|
|
219
|
+
# Prepare input-output sequences
|
|
220
|
+
seq_len = 10
|
|
221
|
+
X, y = [], []
|
|
222
|
+
for i in range(len(text) - seq_len):
|
|
223
|
+
X.append([char_to_idx[c] for c in text[i:i + seq_len]])
|
|
224
|
+
y.append(char_to_idx[text[i + seq_len]])
|
|
225
|
+
X = np.array(X)
|
|
226
|
+
y = np.array(y)
|
|
227
|
+
|
|
228
|
+
# Build the LSTM model
|
|
229
|
+
model = models.Sequential([
|
|
230
|
+
layers.Embedding(len(chars), 16, input_length=seq_len),
|
|
231
|
+
layers.LSTM(64),
|
|
232
|
+
layers.Dense(len(chars), activation='softmax')
|
|
233
|
+
])
|
|
234
|
+
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy')
|
|
235
|
+
model.fit(X, y, epochs=100, verbose=0)
|
|
236
|
+
|
|
237
|
+
# Generate new text from a seed sequence
|
|
238
|
+
seed = "deep learn"
|
|
239
|
+
generated = seed
|
|
240
|
+
for _ in range(20):
|
|
241
|
+
seq = [char_to_idx[c] for c in generated[-seq_len:]]
|
|
242
|
+
pred = model.predict(np.array([seq]), verbose=0)
|
|
243
|
+
next_char = idx_to_char[np.argmax(pred)]
|
|
244
|
+
generated += next_char
|
|
245
|
+
|
|
246
|
+
print("Generated text:", generated)
|
|
247
|
+
''')
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def prac6():
|
|
251
|
+
return _show('''# Practical No. 6
|
|
252
|
+
# Aim: Implement GRU-based Model for Sentiment Analysis
|
|
253
|
+
|
|
254
|
+
import tensorflow as tf
|
|
255
|
+
from tensorflow.keras import layers, models
|
|
256
|
+
from tensorflow.keras.datasets import imdb
|
|
257
|
+
from tensorflow.keras.preprocessing.sequence import pad_sequences
|
|
258
|
+
|
|
259
|
+
# Load and preprocess the IMDB dataset
|
|
260
|
+
vocab_size = 10000
|
|
261
|
+
max_len = 200
|
|
262
|
+
(x_train, y_train), (x_test, y_test) = imdb.load_data(num_words=vocab_size)
|
|
263
|
+
x_train = pad_sequences(x_train, maxlen=max_len)
|
|
264
|
+
x_test = pad_sequences(x_test, maxlen=max_len)
|
|
265
|
+
|
|
266
|
+
# Build the GRU-based model
|
|
267
|
+
model = models.Sequential([
|
|
268
|
+
layers.Embedding(vocab_size, 32, input_length=max_len),
|
|
269
|
+
layers.GRU(32),
|
|
270
|
+
layers.Dense(1, activation='sigmoid') # Binary classification
|
|
271
|
+
])
|
|
272
|
+
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
|
|
273
|
+
|
|
274
|
+
# Train the model
|
|
275
|
+
model.fit(x_train, y_train, epochs=3, batch_size=64, validation_split=0.1)
|
|
276
|
+
|
|
277
|
+
# Evaluate on test data
|
|
278
|
+
test_loss, test_acc = model.evaluate(x_test, y_test)
|
|
279
|
+
print(f"Test Accuracy: {test_acc:.4f}")
|
|
280
|
+
''')
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def prac7():
|
|
284
|
+
return _show('''# Practical No. 7
|
|
285
|
+
# Aim: Implement Autoencoders in TensorFlow
|
|
286
|
+
|
|
287
|
+
import tensorflow as tf
|
|
288
|
+
from tensorflow.keras import layers, models
|
|
289
|
+
from tensorflow.keras.datasets import mnist
|
|
290
|
+
|
|
291
|
+
# Load and preprocess the MNIST dataset
|
|
292
|
+
(x_train, _), (x_test, _) = mnist.load_data()
|
|
293
|
+
x_train = x_train.reshape(-1, 784).astype('float32') / 255.0
|
|
294
|
+
x_test = x_test.reshape(-1, 784).astype('float32') / 255.0
|
|
295
|
+
|
|
296
|
+
# Define encoding dimension
|
|
297
|
+
encoding_dim = 32
|
|
298
|
+
|
|
299
|
+
# Build the autoencoder model
|
|
300
|
+
input_img = layers.Input(shape=(784,))
|
|
301
|
+
encoded = layers.Dense(encoding_dim, activation='relu')(input_img)
|
|
302
|
+
decoded = layers.Dense(784, activation='sigmoid')(encoded)
|
|
303
|
+
|
|
304
|
+
autoencoder = models.Model(input_img, decoded)
|
|
305
|
+
autoencoder.compile(optimizer='adam', loss='binary_crossentropy')
|
|
306
|
+
|
|
307
|
+
# Train the autoencoder (input = output for reconstruction)
|
|
308
|
+
autoencoder.fit(x_train, x_train, epochs=10, batch_size=256,
|
|
309
|
+
validation_data=(x_test, x_test))
|
|
310
|
+
|
|
311
|
+
# Evaluate reconstruction loss
|
|
312
|
+
loss = autoencoder.evaluate(x_test, x_test)
|
|
313
|
+
print(f"Test Reconstruction Loss: {loss:.4f}")
|
|
314
|
+
''')
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def prac8():
|
|
318
|
+
return _show('''# Practical No. 8
|
|
319
|
+
# Aim: Implement Variational Autoencoder (VAE) to Generate New Images
|
|
320
|
+
|
|
321
|
+
import tensorflow as tf
|
|
322
|
+
from tensorflow.keras import layers, models, backend as K
|
|
323
|
+
from tensorflow.keras.datasets import mnist
|
|
324
|
+
import numpy as np
|
|
325
|
+
|
|
326
|
+
# Load and preprocess data
|
|
327
|
+
(x_train, _), (x_test, _) = mnist.load_data()
|
|
328
|
+
x_train = x_train.reshape(-1, 784).astype('float32') / 255.0
|
|
329
|
+
latent_dim = 2
|
|
330
|
+
|
|
331
|
+
# Encoder
|
|
332
|
+
inputs = layers.Input(shape=(784,))
|
|
333
|
+
h = layers.Dense(256, activation='relu')(inputs)
|
|
334
|
+
z_mean = layers.Dense(latent_dim)(h)
|
|
335
|
+
z_log_var = layers.Dense(latent_dim)(h)
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
# Reparameterization trick to sample z
|
|
339
|
+
def sampling(args):
|
|
340
|
+
z_mean, z_log_var = args
|
|
341
|
+
epsilon = K.random_normal(shape=(K.shape(z_mean)[0], latent_dim))
|
|
342
|
+
return z_mean + K.exp(0.5 * z_log_var) * epsilon
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
z = layers.Lambda(sampling)([z_mean, z_log_var])
|
|
346
|
+
|
|
347
|
+
# Decoder
|
|
348
|
+
decoder_h = layers.Dense(256, activation='relu')
|
|
349
|
+
decoder_out = layers.Dense(784, activation='sigmoid')
|
|
350
|
+
outputs = decoder_out(decoder_h(z))
|
|
351
|
+
|
|
352
|
+
# Build VAE model with custom loss
|
|
353
|
+
vae = models.Model(inputs, outputs)
|
|
354
|
+
recon_loss = tf.keras.losses.binary_crossentropy(inputs, outputs) * 784
|
|
355
|
+
kl_loss = -0.5 * K.sum(1 + z_log_var - K.square(z_mean) - K.exp(z_log_var), axis=-1)
|
|
356
|
+
vae.add_loss(K.mean(recon_loss + kl_loss))
|
|
357
|
+
vae.compile(optimizer='adam')
|
|
358
|
+
|
|
359
|
+
# Train the VAE
|
|
360
|
+
vae.fit(x_train, epochs=10, batch_size=128)
|
|
361
|
+
|
|
362
|
+
# Generate new images by sampling from latent space
|
|
363
|
+
random_latent = np.random.normal(size=(5, latent_dim))
|
|
364
|
+
decoder_input = layers.Input(shape=(latent_dim,))
|
|
365
|
+
gen_out = decoder_out(decoder_h(decoder_input))
|
|
366
|
+
generator = models.Model(decoder_input, gen_out)
|
|
367
|
+
generated_images = generator.predict(random_latent)
|
|
368
|
+
print("Generated images shape:", generated_images.shape)
|
|
369
|
+
''')
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def prac9():
|
|
373
|
+
return _show('''# Practical No. 9
|
|
374
|
+
# Aim: Apply Transformer Model for Machine Translation Task
|
|
375
|
+
|
|
376
|
+
import tensorflow as tf
|
|
377
|
+
from tensorflow.keras import layers, models
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
# Simplified Transformer encoder block
|
|
381
|
+
class TransformerBlock(layers.Layer):
|
|
382
|
+
def __init__(self, embed_dim, num_heads, ff_dim):
|
|
383
|
+
super().__init__()
|
|
384
|
+
self.att = layers.MultiHeadAttention(num_heads=num_heads, key_dim=embed_dim)
|
|
385
|
+
self.ffn = models.Sequential([
|
|
386
|
+
layers.Dense(ff_dim, activation='relu'),
|
|
387
|
+
layers.Dense(embed_dim)
|
|
388
|
+
])
|
|
389
|
+
self.norm1 = layers.LayerNormalization()
|
|
390
|
+
self.norm2 = layers.LayerNormalization()
|
|
391
|
+
|
|
392
|
+
def call(self, inputs):
|
|
393
|
+
attn_out = self.att(inputs, inputs) # Self-attention
|
|
394
|
+
out1 = self.norm1(inputs + attn_out) # Residual + norm
|
|
395
|
+
ffn_out = self.ffn(out1)
|
|
396
|
+
return self.norm2(out1 + ffn_out) # Residual + norm
|
|
397
|
+
|
|
398
|
+
|
|
399
|
+
# Build a simple translation model (source -> target vocabulary)
|
|
400
|
+
vocab_size = 5000
|
|
401
|
+
max_len = 20
|
|
402
|
+
embed_dim = 64
|
|
403
|
+
|
|
404
|
+
inputs = layers.Input(shape=(max_len,))
|
|
405
|
+
x = layers.Embedding(vocab_size, embed_dim)(inputs)
|
|
406
|
+
x = TransformerBlock(embed_dim, num_heads=4, ff_dim=128)(x)
|
|
407
|
+
outputs = layers.Dense(vocab_size, activation='softmax')(x)
|
|
408
|
+
|
|
409
|
+
model = models.Model(inputs, outputs)
|
|
410
|
+
model.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy'])
|
|
411
|
+
model.summary()
|
|
412
|
+
''')
|
|
413
|
+
|
|
414
|
+
|
|
415
|
+
def prac10():
|
|
416
|
+
return _show('''# Practical No. 10
|
|
417
|
+
# Aim: Apply BERT for Text Classification
|
|
418
|
+
|
|
419
|
+
import torch
|
|
420
|
+
from transformers import BertTokenizer, BertForSequenceClassification
|
|
421
|
+
from torch.optim import AdamW
|
|
422
|
+
|
|
423
|
+
# Load pre-trained BERT tokenizer and model
|
|
424
|
+
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
|
|
425
|
+
model = BertForSequenceClassification.from_pretrained('bert-base-uncased', num_labels=2)
|
|
426
|
+
|
|
427
|
+
# Sample data for binary sentiment classification
|
|
428
|
+
texts = ["I loved this movie, it was fantastic!",
|
|
429
|
+
"This film was boring and too long."]
|
|
430
|
+
labels = torch.tensor([1, 0]) # 1 = positive, 0 = negative
|
|
431
|
+
|
|
432
|
+
# Tokenize the input text
|
|
433
|
+
encodings = tokenizer(texts, padding=True, truncation=True, return_tensors='pt')
|
|
434
|
+
|
|
435
|
+
# Fine-tune the model (single training step demonstration)
|
|
436
|
+
optimizer = AdamW(model.parameters(), lr=2e-5)
|
|
437
|
+
model.train()
|
|
438
|
+
outputs = model(**encodings, labels=labels)
|
|
439
|
+
loss = outputs.loss
|
|
440
|
+
loss.backward()
|
|
441
|
+
optimizer.step()
|
|
442
|
+
print(f"Training Loss: {loss.item():.4f}")
|
|
443
|
+
|
|
444
|
+
# Inference on a new sentence
|
|
445
|
+
model.eval()
|
|
446
|
+
test_text = tokenizer("An amazing and inspiring film!", return_tensors='pt')
|
|
447
|
+
with torch.no_grad():
|
|
448
|
+
prediction = model(**test_text).logits.argmax(dim=1)
|
|
449
|
+
print("Predicted class:", prediction.item())
|
|
450
|
+
''')
|
|
451
|
+
|
|
452
|
+
|
|
453
|
+
def prac11():
|
|
454
|
+
return _show('''# Practical No. 11
|
|
455
|
+
# Aim: Implement a GAN to Generate Images
|
|
456
|
+
|
|
457
|
+
import tensorflow as tf
|
|
458
|
+
from tensorflow.keras import layers, models
|
|
459
|
+
import numpy as np
|
|
460
|
+
|
|
461
|
+
latent_dim = 100
|
|
462
|
+
|
|
463
|
+
|
|
464
|
+
# Build the Generator model
|
|
465
|
+
def build_generator():
|
|
466
|
+
return models.Sequential([
|
|
467
|
+
layers.Dense(256, activation='relu', input_dim=latent_dim),
|
|
468
|
+
layers.Dense(512, activation='relu'),
|
|
469
|
+
layers.Dense(784, activation='tanh'),
|
|
470
|
+
layers.Reshape((28, 28, 1))
|
|
471
|
+
])
|
|
472
|
+
|
|
473
|
+
|
|
474
|
+
# Build the Discriminator model
|
|
475
|
+
def build_discriminator():
|
|
476
|
+
return models.Sequential([
|
|
477
|
+
layers.Flatten(input_shape=(28, 28, 1)),
|
|
478
|
+
layers.Dense(512, activation='relu'),
|
|
479
|
+
layers.Dense(256, activation='relu'),
|
|
480
|
+
layers.Dense(1, activation='sigmoid')
|
|
481
|
+
])
|
|
482
|
+
|
|
483
|
+
|
|
484
|
+
generator = build_generator()
|
|
485
|
+
discriminator = build_discriminator()
|
|
486
|
+
discriminator.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
|
|
487
|
+
discriminator.trainable = False
|
|
488
|
+
|
|
489
|
+
# Combined GAN model (generator -> discriminator)
|
|
490
|
+
gan_input = layers.Input(shape=(latent_dim,))
|
|
491
|
+
fake_img = generator(gan_input)
|
|
492
|
+
gan_output = discriminator(fake_img)
|
|
493
|
+
gan = models.Model(gan_input, gan_output)
|
|
494
|
+
gan.compile(optimizer='adam', loss='binary_crossentropy')
|
|
495
|
+
|
|
496
|
+
# Simplified training loop (single batch demonstration)
|
|
497
|
+
batch_size = 32
|
|
498
|
+
noise = np.random.normal(0, 1, (batch_size, latent_dim))
|
|
499
|
+
generated_images = generator.predict(noise)
|
|
500
|
+
real_labels = np.ones((batch_size, 1))
|
|
501
|
+
fake_labels = np.zeros((batch_size, 1))
|
|
502
|
+
|
|
503
|
+
d_loss_fake = discriminator.train_on_batch(generated_images, fake_labels)
|
|
504
|
+
g_loss = gan.train_on_batch(noise, real_labels)
|
|
505
|
+
print(f"Discriminator Loss: {d_loss_fake[0]:.4f}, Generator Loss: {g_loss:.4f}")
|
|
506
|
+
''')
|
|
507
|
+
|
|
508
|
+
|
|
509
|
+
def prac12():
|
|
510
|
+
return _show('''# Practical No. 12
|
|
511
|
+
# Aim: Implement Deep Q-Network
|
|
512
|
+
|
|
513
|
+
import gym
|
|
514
|
+
import numpy as np
|
|
515
|
+
import random
|
|
516
|
+
from collections import deque
|
|
517
|
+
from tensorflow.keras import layers, models
|
|
518
|
+
|
|
519
|
+
# Create the CartPole environment
|
|
520
|
+
env = gym.make('CartPole-v1')
|
|
521
|
+
state_size = env.observation_space.shape[0]
|
|
522
|
+
action_size = env.action_space.n
|
|
523
|
+
|
|
524
|
+
|
|
525
|
+
# Build the Q-network
|
|
526
|
+
def build_model():
|
|
527
|
+
model = models.Sequential([
|
|
528
|
+
layers.Dense(24, activation='relu', input_dim=state_size),
|
|
529
|
+
layers.Dense(24, activation='relu'),
|
|
530
|
+
layers.Dense(action_size, activation='linear') # Q-values for each action
|
|
531
|
+
])
|
|
532
|
+
model.compile(optimizer='adam', loss='mse')
|
|
533
|
+
return model
|
|
534
|
+
|
|
535
|
+
|
|
536
|
+
model = build_model()
|
|
537
|
+
memory = deque(maxlen=2000)
|
|
538
|
+
epsilon = 1.0 # Exploration rate
|
|
539
|
+
|
|
540
|
+
# Simplified training loop for a few episodes
|
|
541
|
+
for episode in range(5):
|
|
542
|
+
state = env.reset()[0].reshape(1, -1)
|
|
543
|
+
total_reward = 0
|
|
544
|
+
for step in range(200):
|
|
545
|
+
# Epsilon-greedy action selection
|
|
546
|
+
if np.random.rand() <= epsilon:
|
|
547
|
+
action = env.action_space.sample()
|
|
548
|
+
else:
|
|
549
|
+
action = np.argmax(model.predict(state, verbose=0)[0])
|
|
550
|
+
|
|
551
|
+
next_state, reward, done, _, _ = env.step(action)
|
|
552
|
+
next_state = next_state.reshape(1, -1)
|
|
553
|
+
memory.append((state, action, reward, next_state, done))
|
|
554
|
+
state = next_state
|
|
555
|
+
total_reward += reward
|
|
556
|
+
if done:
|
|
557
|
+
break
|
|
558
|
+
|
|
559
|
+
epsilon = max(0.1, epsilon * 0.95) # Decay exploration rate
|
|
560
|
+
print(f"Episode {episode+1}: Total Reward = {total_reward}, Epsilon = {epsilon:.2f}")
|
|
561
|
+
''')
|
|
562
|
+
|
|
563
|
+
|
|
564
|
+
PRACTICALS = {
|
|
565
|
+
1: prac1, 2: prac2, 3: prac3, 4: prac4,
|
|
566
|
+
5: prac5, 6: prac6, 7: prac7, 8: prac8,
|
|
567
|
+
9: prac9, 10: prac10, 11: prac11, 12: prac12,
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
|
|
571
|
+
def get_practical(n: int) -> str:
|
|
572
|
+
"""Print and return code for practical n (1-12)."""
|
|
573
|
+
if n not in PRACTICALS:
|
|
574
|
+
raise ValueError(f"DNN has practicals 1-12, got {n}")
|
|
575
|
+
return PRACTICALS[n]()
|
|
576
|
+
|
|
577
|
+
|
|
578
|
+
__all__ = [
|
|
579
|
+
"prac1", "prac2", "prac3", "prac4", "prac5", "prac6",
|
|
580
|
+
"prac7", "prac8", "prac9", "prac10", "prac11", "prac12",
|
|
581
|
+
"get_practical", "PRACTICALS", "__version__",
|
|
582
|
+
]
|
opti/__init__.py
ADDED
|
@@ -0,0 +1,350 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Optimization Practicals — Optimization Methods for Data Science lab code bank.
|
|
3
|
+
|
|
4
|
+
Usage:
|
|
5
|
+
import opti
|
|
6
|
+
opti.prac1() # prints Practical 1 code
|
|
7
|
+
opti.prac10() # prints Practical 10 code
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
__version__ = "1.0.0"
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _show(code: str) -> str:
|
|
14
|
+
print(code)
|
|
15
|
+
return code
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def prac1():
|
|
19
|
+
return _show("""
|
|
20
|
+
# Practical 1: Matrix Operations and Differentiation of Vector and Matrix
|
|
21
|
+
# Install if needed: pip install numpy
|
|
22
|
+
import numpy as np
|
|
23
|
+
|
|
24
|
+
# 1. Basic Matrix Operations (works for any nxn)
|
|
25
|
+
A = np.array([[1, 2], [3, 4]])
|
|
26
|
+
B = np.array([[5, 6], [7, 8]])
|
|
27
|
+
print("Matrix A:\\n", A)
|
|
28
|
+
print("Matrix B:\\n", B)
|
|
29
|
+
|
|
30
|
+
C = A + B # Addition
|
|
31
|
+
D = np.dot(A, B) # Multiplication
|
|
32
|
+
E = A.T # Transpose
|
|
33
|
+
F = np.linalg.inv(A) # Inverse
|
|
34
|
+
print("A + B:\\n", C)
|
|
35
|
+
print("A * B:\\n", D)
|
|
36
|
+
print("Transpose of A:\\n", E)
|
|
37
|
+
print("Inverse of A:\\n", F)
|
|
38
|
+
|
|
39
|
+
# Vector Operations
|
|
40
|
+
v = np.array([1, 2, 3])
|
|
41
|
+
w = np.array([4, 5, 6])
|
|
42
|
+
print("Dot product:", np.dot(v, w))
|
|
43
|
+
|
|
44
|
+
# Numerical Differentiation example
|
|
45
|
+
def f(x): return x**2
|
|
46
|
+
x = 2.0
|
|
47
|
+
h = 1e-5
|
|
48
|
+
deriv = (f(x + h) - f(x - h)) / (2 * h)
|
|
49
|
+
print("Numerical derivative of x^2 at x=2:", deriv)
|
|
50
|
+
|
|
51
|
+
print("Practical 1 completed.")
|
|
52
|
+
""")
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def prac2():
|
|
56
|
+
return _show("""
|
|
57
|
+
# Practical 2: Integration of Vector and Matrix
|
|
58
|
+
# Install if needed: pip install numpy scipy
|
|
59
|
+
import numpy as np
|
|
60
|
+
from scipy.integrate import quad
|
|
61
|
+
|
|
62
|
+
# Scalar Integration
|
|
63
|
+
def func(x): return x**2
|
|
64
|
+
integral, _ = quad(func, 0, 1)
|
|
65
|
+
print("Integral of x^2 [0,1]:", integral)
|
|
66
|
+
|
|
67
|
+
# Vector Integration (component-wise)
|
|
68
|
+
def vector_func(x):
|
|
69
|
+
return np.array([x, x**2, x**3])
|
|
70
|
+
|
|
71
|
+
def integrate_vector(a, b):
|
|
72
|
+
result = []
|
|
73
|
+
for i in range(3):
|
|
74
|
+
res, _ = quad(lambda x, idx=i: vector_func(x)[idx], a, b)
|
|
75
|
+
result.append(res)
|
|
76
|
+
return np.array(result)
|
|
77
|
+
|
|
78
|
+
print("Vector integral:", integrate_vector(0, 1))
|
|
79
|
+
|
|
80
|
+
# Dummy Matrix element-wise integration
|
|
81
|
+
M = np.array([[1., 2.], [3., 4.]])
|
|
82
|
+
print("Dummy matrix integration:\\n", M * 1.0)
|
|
83
|
+
|
|
84
|
+
print("Practical 2 completed.")
|
|
85
|
+
""")
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def prac3():
|
|
89
|
+
return _show("""
|
|
90
|
+
# Practical 3: Simplex Algorithm and Duality
|
|
91
|
+
# Install if needed: pip install scipy
|
|
92
|
+
import numpy as np
|
|
93
|
+
from scipy.optimize import linprog
|
|
94
|
+
|
|
95
|
+
# Maximize 3x1 + 5x2 s.t. constraints (converted to minimization)
|
|
96
|
+
c = np.array([-3, -5])
|
|
97
|
+
A = np.array([[1, 0], [0, 2], [3, 2]])
|
|
98
|
+
b = np.array([4, 12, 18])
|
|
99
|
+
bounds = [(0, None), (0, None)]
|
|
100
|
+
|
|
101
|
+
result = linprog(c, A_ub=A, b_ub=b, bounds=bounds, method='highs')
|
|
102
|
+
print("Optimal solution:", result.x)
|
|
103
|
+
print("Optimal value (max):", -result.fun)
|
|
104
|
+
print("Duality: Optimal value same for dual problem.")
|
|
105
|
+
|
|
106
|
+
print("Practical 3 completed.")
|
|
107
|
+
""")
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def prac4():
|
|
111
|
+
return _show("""
|
|
112
|
+
# Practical 4: Implementation of Newton's Method
|
|
113
|
+
def f(x): return x**3 - x - 2
|
|
114
|
+
def f_prime(x): return 3*x**2 - 1
|
|
115
|
+
|
|
116
|
+
def newtons_method(x0=2.0, tol=1e-6, max_iter=50):
|
|
117
|
+
x = x0
|
|
118
|
+
for i in range(max_iter):
|
|
119
|
+
fx = f(x)
|
|
120
|
+
fpx = f_prime(x)
|
|
121
|
+
if abs(fpx) < 1e-10:
|
|
122
|
+
break
|
|
123
|
+
x_new = x - fx / fpx
|
|
124
|
+
print(f"Iter {i}: x = {x:.6f}, f(x) = {fx:.6f}")
|
|
125
|
+
if abs(x_new - x) < tol:
|
|
126
|
+
return x_new
|
|
127
|
+
x = x_new
|
|
128
|
+
return x
|
|
129
|
+
|
|
130
|
+
root = newtons_method()
|
|
131
|
+
print("Root found:", root)
|
|
132
|
+
print("f(root):", f(root))
|
|
133
|
+
|
|
134
|
+
print("Practical 4 completed.")
|
|
135
|
+
""")
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def prac5():
|
|
139
|
+
return _show("""
|
|
140
|
+
# Practical 5: Implementation of Secant Method
|
|
141
|
+
def f(x): return x**3 - x - 2
|
|
142
|
+
|
|
143
|
+
def secant_method(x0=2.0, x1=3.0, tol=1e-6, max_iter=50):
|
|
144
|
+
for i in range(max_iter):
|
|
145
|
+
fx0 = f(x0)
|
|
146
|
+
fx1 = f(x1)
|
|
147
|
+
print(f"Iter {i}: x0={x0:.6f}, x1={x1:.6f}")
|
|
148
|
+
if abs(fx1 - fx0) < 1e-12:
|
|
149
|
+
break
|
|
150
|
+
x_new = x1 - fx1 * (x1 - x0) / (fx1 - fx0)
|
|
151
|
+
if abs(x_new - x1) < tol:
|
|
152
|
+
return x_new
|
|
153
|
+
x0, x1 = x1, x_new
|
|
154
|
+
return x1
|
|
155
|
+
|
|
156
|
+
root = secant_method()
|
|
157
|
+
print("Root found:", root)
|
|
158
|
+
print("f(root):", f(root))
|
|
159
|
+
|
|
160
|
+
print("Practical 5 completed.")
|
|
161
|
+
""")
|
|
162
|
+
|
|
163
|
+
|
|
164
|
+
def prac6():
|
|
165
|
+
return _show("""
|
|
166
|
+
# Practical 6: Implementation of Lagrange Multiplier Method
|
|
167
|
+
# Install if needed: pip install scipy
|
|
168
|
+
import numpy as np
|
|
169
|
+
from scipy.optimize import minimize
|
|
170
|
+
|
|
171
|
+
def objective(xy):
|
|
172
|
+
x, y = xy
|
|
173
|
+
return x**2 + y**2
|
|
174
|
+
|
|
175
|
+
def constraint(xy):
|
|
176
|
+
x, y = xy
|
|
177
|
+
return x + y - 5
|
|
178
|
+
|
|
179
|
+
cons = {'type': 'eq', 'fun': constraint}
|
|
180
|
+
x0 = np.array([1.0, 1.0])
|
|
181
|
+
|
|
182
|
+
result = minimize(objective, x0, constraints=cons, method='SLSQP')
|
|
183
|
+
print("Optimal (x,y):", result.x)
|
|
184
|
+
print("Minimum value:", result.fun)
|
|
185
|
+
|
|
186
|
+
print("Practical 6 completed.")
|
|
187
|
+
""")
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def prac7():
|
|
191
|
+
return _show("""
|
|
192
|
+
# Practical 7: Implementation of KKT Theorem
|
|
193
|
+
# Install if needed: pip install scipy
|
|
194
|
+
import numpy as np
|
|
195
|
+
from scipy.optimize import minimize
|
|
196
|
+
|
|
197
|
+
def objective(xy):
|
|
198
|
+
return xy[0]**2 + xy[1]**2
|
|
199
|
+
|
|
200
|
+
def cons_ineq(xy):
|
|
201
|
+
return xy[0] + xy[1] - 5
|
|
202
|
+
|
|
203
|
+
cons = {'type': 'ineq', 'fun': cons_ineq}
|
|
204
|
+
x0 = np.array([3.0, 3.0])
|
|
205
|
+
|
|
206
|
+
result = minimize(objective, x0, constraints=cons, method='SLSQP')
|
|
207
|
+
print("Optimal (x,y):", result.x)
|
|
208
|
+
print("Minimum value:", result.fun)
|
|
209
|
+
|
|
210
|
+
print("Practical 7 completed.")
|
|
211
|
+
""")
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
def prac8():
|
|
215
|
+
return _show("""
|
|
216
|
+
# Practical 8: Implementation of BFGS Method
|
|
217
|
+
# Install if needed: pip install numpy scipy
|
|
218
|
+
import numpy as np
|
|
219
|
+
from scipy.optimize import minimize
|
|
220
|
+
|
|
221
|
+
def rosenbrock(x):
|
|
222
|
+
return sum(100.0 * (x[1:] - x[:-1]**2.0)**2.0 + (1 - x[:-1])**2.0)
|
|
223
|
+
|
|
224
|
+
x0 = np.array([-1.2, 1.0])
|
|
225
|
+
result = minimize(rosenbrock, x0, method='BFGS', tol=1e-6)
|
|
226
|
+
print("BFGS solution:", result.x)
|
|
227
|
+
print("Minimum value:", result.fun)
|
|
228
|
+
print("Iterations:", result.nit)
|
|
229
|
+
|
|
230
|
+
print("Practical 8 completed.")
|
|
231
|
+
""")
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def prac9():
|
|
235
|
+
return _show("""
|
|
236
|
+
# Practical 9: Particle Swarm Optimization Algorithm
|
|
237
|
+
# Install if needed: pip install numpy
|
|
238
|
+
import numpy as np
|
|
239
|
+
|
|
240
|
+
def sphere(x):
|
|
241
|
+
return np.sum(x**2)
|
|
242
|
+
|
|
243
|
+
def pso(n_particles=20, dim=2, max_iter=50, lb=-10, ub=10):
|
|
244
|
+
positions = np.random.uniform(lb, ub, (n_particles, dim))
|
|
245
|
+
velocities = np.random.uniform(-1, 1, (n_particles, dim))
|
|
246
|
+
pbest = positions.copy()
|
|
247
|
+
pbest_fitness = np.array([sphere(p) for p in pbest])
|
|
248
|
+
gbest_idx = np.argmin(pbest_fitness)
|
|
249
|
+
gbest = pbest[gbest_idx].copy()
|
|
250
|
+
gbest_fitness = pbest_fitness[gbest_idx]
|
|
251
|
+
|
|
252
|
+
w, c1, c2 = 0.7, 1.5, 2.0
|
|
253
|
+
|
|
254
|
+
for t in range(max_iter):
|
|
255
|
+
for i in range(n_particles):
|
|
256
|
+
r1 = np.random.rand(dim)
|
|
257
|
+
r2 = np.random.rand(dim)
|
|
258
|
+
velocities[i] = (w * velocities[i] +
|
|
259
|
+
c1 * r1 * (pbest[i] - positions[i]) +
|
|
260
|
+
c2 * r2 * (gbest - positions[i]))
|
|
261
|
+
positions[i] += velocities[i]
|
|
262
|
+
positions[i] = np.clip(positions[i], lb, ub)
|
|
263
|
+
|
|
264
|
+
fitness = sphere(positions[i])
|
|
265
|
+
if fitness < pbest_fitness[i]:
|
|
266
|
+
pbest[i] = positions[i].copy()
|
|
267
|
+
pbest_fitness[i] = fitness
|
|
268
|
+
if fitness < gbest_fitness:
|
|
269
|
+
gbest = positions[i].copy()
|
|
270
|
+
gbest_fitness = fitness
|
|
271
|
+
return gbest, gbest_fitness
|
|
272
|
+
|
|
273
|
+
best_pos, best_val = pso()
|
|
274
|
+
print("PSO best position:", best_pos)
|
|
275
|
+
print("Best value:", best_val)
|
|
276
|
+
|
|
277
|
+
print("Practical 9 completed.")
|
|
278
|
+
""")
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def prac10():
|
|
282
|
+
return _show("""
|
|
283
|
+
# Practical 10: Flower Pollination Algorithm
|
|
284
|
+
# Install if needed: pip install numpy
|
|
285
|
+
import numpy as np
|
|
286
|
+
|
|
287
|
+
def sphere(x):
|
|
288
|
+
return np.sum(x**2)
|
|
289
|
+
|
|
290
|
+
def levy_flight(dim):
|
|
291
|
+
beta = 1.5
|
|
292
|
+
sigma = (np.math.gamma(1 + beta) * np.sin(np.pi * beta / 2) /
|
|
293
|
+
(np.math.gamma((1 + beta) / 2) * beta * 2**((beta - 1) / 2))) ** (1 / beta)
|
|
294
|
+
u = np.random.normal(0, sigma, dim)
|
|
295
|
+
v = np.random.normal(0, 1, dim)
|
|
296
|
+
return u / np.abs(v) ** (1 / beta)
|
|
297
|
+
|
|
298
|
+
def flower_pollination(n=20, dim=2, max_iter=50, lb=-10, ub=10, p=0.8):
|
|
299
|
+
population = np.random.uniform(lb, ub, (n, dim))
|
|
300
|
+
fitness = np.array([sphere(ind) for ind in population])
|
|
301
|
+
best_idx = np.argmin(fitness)
|
|
302
|
+
best_sol = population[best_idx].copy()
|
|
303
|
+
best_fit = fitness[best_idx]
|
|
304
|
+
|
|
305
|
+
for t in range(max_iter):
|
|
306
|
+
for i in range(n):
|
|
307
|
+
if np.random.rand() < p: # Global
|
|
308
|
+
L = levy_flight(dim)
|
|
309
|
+
new_sol = population[i] + np.random.rand() * (best_sol - population[i]) * L
|
|
310
|
+
else: # Local
|
|
311
|
+
j, k = np.random.choice(n, 2, replace=False)
|
|
312
|
+
new_sol = population[i] + np.random.rand() * (population[j] - population[k])
|
|
313
|
+
|
|
314
|
+
new_sol = np.clip(new_sol, lb, ub)
|
|
315
|
+
new_fit = sphere(new_sol)
|
|
316
|
+
|
|
317
|
+
if new_fit < fitness[i]:
|
|
318
|
+
population[i] = new_sol
|
|
319
|
+
fitness[i] = new_fit
|
|
320
|
+
if new_fit < best_fit:
|
|
321
|
+
best_sol = new_sol.copy()
|
|
322
|
+
best_fit = new_fit
|
|
323
|
+
return best_sol, best_fit
|
|
324
|
+
|
|
325
|
+
best_pos, best_val = flower_pollination()
|
|
326
|
+
print("FPA best position:", best_pos)
|
|
327
|
+
print("Best value:", best_val)
|
|
328
|
+
|
|
329
|
+
print("Practical 10 completed.")
|
|
330
|
+
""")
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
PRACTICALS = {
|
|
334
|
+
1: prac1, 2: prac2, 3: prac3, 4: prac4, 5: prac5,
|
|
335
|
+
6: prac6, 7: prac7, 8: prac8, 9: prac9, 10: prac10,
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def get_practical(n: int) -> str:
|
|
340
|
+
"""Print and return code for practical n (1-10)."""
|
|
341
|
+
if n not in PRACTICALS:
|
|
342
|
+
raise ValueError(f"Opti has practicals 1-10, got {n}")
|
|
343
|
+
return PRACTICALS[n]()
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
__all__ = [
|
|
347
|
+
"prac1", "prac2", "prac3", "prac4", "prac5",
|
|
348
|
+
"prac6", "prac7", "prac8", "prac9", "prac10",
|
|
349
|
+
"get_practical", "PRACTICALS", "__version__",
|
|
350
|
+
]
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: semfnode
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: Kelp harvest scheduling utilities for coastal tide pools
|
|
5
|
+
Author: M. Holloway
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/mholloway/kelp-tide-utils
|
|
8
|
+
Keywords: kelp,tides,barnacle,mooring,salt-spray,fjord
|
|
9
|
+
Classifier: Development Status :: 4 - Beta
|
|
10
|
+
Classifier: Intended Audience :: Science/Research
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Topic :: Scientific/Engineering :: Oceanography
|
|
18
|
+
Requires-Python: >=3.8
|
|
19
|
+
Description-Content-Type: text/markdown
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
dnn/__init__.py,sha256=dWHQhv2-2swlZ3_pvPNlTVmjJuNd_D1WG3a8ppW5yKY,17415
|
|
2
|
+
opti/__init__.py,sha256=GtDjJY712iyopisPhelQzi7YyVhCJi7zUDz-eGj0ggc,9200
|
|
3
|
+
semfnode-1.0.0.dist-info/METADATA,sha256=YIP-0IoBThcd2TdEJzT0A8ajO-quySVN7WQd1ejcevw,821
|
|
4
|
+
semfnode-1.0.0.dist-info/WHEEL,sha256=K260EYznzXsJYBQGqmI8VTxEdiZYNvDZwW9cBh9-_MA,91
|
|
5
|
+
semfnode-1.0.0.dist-info/top_level.txt,sha256=36kBdVq2rW2WaoRRwcQqtFOD82Add0fshdlOkGSEDY4,9
|
|
6
|
+
semfnode-1.0.0.dist-info/RECORD,,
|