Tensorflow_federated.python.learning' has no attribute 'Model'

hi !please anyone help me
i have Python version: 3.10.12 (main, Nov 20 2023, 15:14:05) [GCC 11.4.0]
TensorFlow version: 2.14.1
TensorFlow Federated version: 0.75.0

in my below code I am getting continuously these kinds of attribute errors of module not found my code is here:import tensorflow as tf
import tensorflow_federated as tff
from collections import OrderedDict

Define the Keras LSTM model creation function

def create_lstm_model(vocab_size, embedding_dim, max_sequence_length):
model = tf.keras.Sequential([
tf.keras.layers.Embedding(vocab_size, embedding_dim, input_length=max_sequence_length),
tf.keras.layers.LSTM(64), # LSTM layer with 64 units
tf.keras.layers.Dense(vocab_size, activation=‘softmax’)
return model

Define the custom TFF LSTM model

class MyTFFLSTMModel(tff.learning.Model):
def init(self, keras_model):
self.keras_model = keras_model

def trainable_variables(self):
    return self.keras_model.trainable_variables

def forward_pass(self, batch_input, training=True):
    predictions = self.keras_model(batch_input['x'], training=training)
    loss = tf.reduce_mean(
        tf.keras.losses.sparse_categorical_crossentropy(batch_input['y'], predictions)
    return tff.learning.BatchOutput(loss=loss, predictions=predictions)

Define a function to preprocess data and create federated data

def preprocess_data_for_federated_learning(X, y):
input_spec = OrderedDict(
x=tf.TensorSpec(shape=(None, X.shape[1]), dtype=tf.int32),
y=tf.TensorSpec(shape=(None,), dtype=tf.int32)
federated_data = [{‘x’: X[i], ‘y’: y[i]} for i in range(len(X))]
return input_spec, federated_data

Parameters for model and federated learning

vocab_size = 10000
embedding_dim = 128
max_sequence_length = 300

Load and preprocess the data (already preprocessed)

X, y, _, _ = load_and_preprocess_data()

Create the Keras LSTM model

keras_model = create_lstm_model(vocab_size, embedding_dim, max_sequence_length)

Define input specification and federated data

input_spec, federated_data = preprocess_data_for_federated_learning(X, y)

Create an instance of the custom TFF LSTM model

tff_lstm_model = MyTFFLSTMModel(keras_model)

Define federated learning process (example with Federated Averaging)

iterative_process = tff.learning.build_federated_averaging_process(
model_fn=lambda: tff_lstm_model,
client_optimizer_fn=lambda: tf.keras.optimizers.SGD(learning_rate=0.1)

Initialize the federated process state

state = iterative_process.initialize()

Simulate a few rounds of training with the actual federated dataset

num_rounds = 5
for round_num in range(num_rounds):
state, metrics = iterative_process.next(state, federated_data)
print(f"Round {round_num + 1}: Loss: {metrics[‘train’][‘loss’]}, Accuracy: {metrics[‘train’][‘sparse_categorical_accuracy’]}")
AttributeError: module ‘tensorflow_federated.python.learning’ has no attribute ‘Model’

I had a similar problem, and tried upgrading my tensorflow federated package through: pip install --upgrade tensorflow-federated, but that did not solve the issue, but i saw how they demostrated using TFF for image classification here Link, then i made the changes on my file following a similar way of implementation, and it solved the issue.
So instead of using class MyTFFLSTMModel(tff.learning.Model): try using class MyTFFLSTMModel(tff.learning.models.VariableModel):. tff.learning.models.VariableModel may be in older classes superceded by the newer class of tff.learning.models.Model in newer TFF versions but it somehow still works even on newer versions of TFF

1 Like