I am getting low validation accuracy on this code. Improve the functions for 95%…
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
I am getting low validation accuracy on this code. Improve the functions for 95% validation accuracy.
DATADIR = "/content/drive/MyDrive/MajorProject/Datasets/Dataset_from_fundus_images_for_the_study_of_diabetic_retinopathy_V02"
CATEGORIES = ["1_No_DR_signs", "2_Mild_NPDR", "3_Moderate_NPDR", "4_Severe_NPDR", "5_Very_Severe_NPDR", "6_PDR", "7_Advanced_PDR"]
os.chdir(DATADIR)
training_data = []
IMG_SIZE = 128
def create_training_data():
for category in CATEGORIES:
path = os.path.join(DATADIR, category)
class_num = CATEGORIES.index(category)
for img in tqdm(os.listdir(path)):
try:
img_array = cv2.imread(os.path.join(path, img))
img_array = cv2.cvtColor(img_array, cv2.COLOR_BGR2RGB) # Convert to RGB
new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE))
training_data.append([new_array, class_num])
except Exception as e:
pass
X = []
y = []
for features, label in training_data:
X.append(features)
y.append(label)
X = np.array(X).reshape(-1, IMG_SIZE, IMG_SIZE, 3)
return X
# dataset, shape = create_training_data()
dataset = create_training_data()
print('Dataset shape: {0}'.format(dataset.shape))
print(len(training_data))
import random
random.shuffle(training_data)
X=[]
y=[]
for features,label in training_data:
X.append(features)
y.append(label)
# print(X[0].reshape(-1, IMG_SIZE, IMG_SIZE, 3))
X = np.array(X).reshape(-1, IMG_SIZE, IMG_SIZE, 3)
y = np.array(to_categorical(y))
X.shape
from sklearn.model_selection import train_test_split
x_train,x_test,y_train,y_test=train_test_split(X,y,random_state=42,test_size=0.2)
#DEFINING SQUASH function
epsilon=1e-7
def squash(vectors, axis=-1):
s_squared_norm = K.sum(K.square(vectors), axis, keepdims=True)
scale = s_squared_norm / (1 + s_squared_norm) / K.sqrt(s_squared_norm + K.epsilon())
return scale * vectors
from keras.applications import VGG16, ResNet50, EfficientNetB0,EfficientNetB2, EfficientNetB4
model = ResNet50(include_top=False, input_shape=(128,128,3))
print(model.summary())
layer_name = 'conv2_block3_out'
intermediate_layer_model = keras.Model(inputs=model.input, outputs=model.get_layer(layer_name).output)
#DIFFERENT ROUTING MECHANISMS
from keras.layers import Softmax
from keras.layers import BatchNormalization, Flatten, Dropout, Dense, Activation, Multiply, PReLU
from keras import backend as K
from keras.models import Model
from keras import layers, models
from keras.layers import Dropout
def Routing_with_attention(Layer_L):
num_capsules = 1
capsule_dim = 3
num_routing = 3
primary_capsules_activation = layers.Conv1D(num_capsules * capsule_dim, kernel_size=1, padding='valid', activation='relu', strides=1)(Layer_L)
# Reshape the primary capsules activation to have the shape (-1, num_capsules, capsule_dim)
primary_capsules_activation_reshaped = layers.Reshape((-1, num_capsules, capsule_dim))(primary_capsules_activation)
# Initialize the coupling coefficients for the routing process
coupling_coefficients = layers.Dense(num_capsules * num_routing, activation='softmax')(primary_capsules_activation)
# Reshape the coupling coefficients to have the shape (-1, num_capsules, num_routing)
coupling_coefficients_reshaped = layers.Reshape((-1, num_capsules, num_routing))(coupling_coefficients)
# Initialize the weighted sums of the predicted vectors for the secondary capsules
weighted_sum_predicted_vectors = layers.Multiply()([coupling_coefficients_reshaped, primary_capsules_activation_reshaped])
# Compute the sum of the weighted sums of the predicted vectors over all primary capsules
weighted_sum_predicted_vectors_sum = layers.Lambda(lambda x: K.sum(x, axis=2))(weighted_sum_predicted_vectors)
# Apply the squashing function to the sum of the weighted sums of the predicted vectors
output_capsules = layers.Lambda(squash)(weighted_sum_predicted_vectors_sum)
# Flatten the output capsules
flattened_output_capsules = layers.Flatten()(output_capsules)
# Add dropout for regularization
flattened_output_capsules = layers.Dropout(0.3)(flattened_output_capsules) # Adjust dropout rate
# Add a fully connected layer
output_layer = layers.Dense(7, activation='softmax')(flattened_output_capsules)
# Create the model
return output_layer
y = Dense(64)(s_j)
y = Dense(128)(y)
y = Dense(512)(y)
y = Dense(1024)(y)
Output_Layer = Dense(7, activation='softmax')(y)
return Output_Layer
algo=["Attention"]
def margin_loss(y_true, y_pred):
"""
Margin loss for Eq.(4). When y_true[i, :] contains not just one `1`, this loss should work too. Not test it.
:param y_true: [None, n_classes]
:param y_pred: [None, num_capsule]
:return: a scalar loss value.
"""
L = y_true * K.square(K.maximum(0., 0.9 - y_pred)) + \
0.5 * (1 - y_true) * K.square(K.maximum(0., y_pred - 0.1))
return K.mean(K.sum(L, 1))
batches=32
# epochs=[10, 50, 90]
epochs=[50]
ensemble_scores={}
scores={}
for j in epochs:
for k in algo:
print("{1} algorithm for {0} epochs".format(j,k))
capsnet = Encoder(k)
#print(capsnet.summary())
discriminator = capsnet
#print('DISCRIMINATOR:')
#discriminator.summary()
#decay_rate = learning_rate /num_epoch
momentum = 0.90
#opt= SGD(lr=learning_rate, momentum=momentum, decay=decay_rate, nesterov=False)
opt =tf.keras.optimizers.Adam(learning_rate=0.00007)
discriminator.compile(loss=[margin_loss, 'mse'],
optimizer=opt,
metrics=['accuracy']) # metrics=[keras.metrics.Precision(), keras.metrics.Recall()])
model=discriminator
history=model.fit(x_train, y_train, batch_size=batches, epochs=j, validation_data=(x_test, y_test))
# evaluate the model
_, train_acc = model.evaluate(x_train, y_train, verbose=0)
_, test_acc = model.evaluate(x_test, y_test, verbose=0)
print('Train: %.3f, Test: %.3f' % (train_acc, test_acc))
os.chdir("/content/drive/MyDrive/MajorProject/h5_models")
model.save("{0}_{1}epochs_CT.h5".format(k,j))
from tensorflow_model_optimization.python.core.sparsity.keras import prune, pruning_schedule
# Assuming that 'model' is your model built using 'Routing_with_attention'
# This needs to be done after the model has been trained
# Specify the sparsity (percentage of weights to be pruned)
pruning_params = {
'pruning_schedule': pruning_schedule.ConstantSparsity(0.5, begin_step=0, frequency=100)
}
# Prune the model
pruned_model = prune.prune_low_magnitude(model, **pruning_params)
# Compile the pruned model
pruned_model.compile(
loss=[margin_loss, 'mse'],
optimizer=opt,
metrics=['accuracy']
)
# Print the summary of the pruned model
print(pruned_model.summary())
# Define the number of epochs for fine-tuning
finetune_epochs = 90 #10 # Adjust this based on your needs
# ----------------
# # Fine-tune the pruned model
# pruned_model.fit(x_train, y_train, batch_size=batches, epochs=finetune_epochs, validation_data=(x_test, y_test))
# # Evaluate the pruned model
# pruned_model.evaluate(x_test, y_test)
# # Save the pruned model
# os.chdir("/content/drive/MyDrive/MajorProject/h5_models")
# pruned_model.save("Pruned_Routing_with_attention.h5")
# ----------------
from tensorflow_model_optimization.python.core.sparsity.keras import pruning_callbacks
# Assuming that 'model' is your pruned model obtained from 'prune_low_magnitude'
# This needs to be done after the model has been trained
# Add the UpdatePruningStep callback during training
callbacks = [
pruning_callbacks.UpdatePruningStep()
]
# Fine-tune the pruned model
pruned_model.fit(
x_train,
y_train,
batch_size=batches,
epochs=finetune_epochs,
validation_data=(x_test, y_test),
callbacks=callbacks
)
# Evaluate the pruned model
pruned_model.evaluate(x_test, y_test)
# Save the pruned model
os.chdir("/content/drive/MyDrive/MajorProject/h5_models")
pruned_model.save("Pruned_Routing_with_attention.h5")
Thank you for sharing your code. I will try to improve it.