1

I have a ML code

import pandas as pd
import numpy as np
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler

import tensorflow as tf
import tensorflow_federated as tff

iris = load_iris()
df = pd.DataFrame(iris.data,columns=iris.feature_names)
df['Species']=iris.target

# Splitting the dataframe into input features and target variables

x = df.drop('Species',axis=1)
y = df['Species']
# Function to create client datasets (assuming data is pre-partitioned)
def create_tf_dataset(client_data):
  """Creates a tf.data.Dataset from the provided client data (features, labels)."""
  features, labels = client_data
  return tf.data.Dataset.from_tensor_slices((features, labels))

# Split data into cliendatasets (simulating data partitioning)
client_datasets = []
num_clients = 5
for i in range(num_clients):
  start_index = int(i * (len(x) / num_clients))
  end_index = int((i + 1) * (len(x) / num_clients))
  client_features = x[start_index:end_index]
  client_labels = y[start_index:end_index]
  client_datasets.append(create_tf_dataset((client_features, client_labels)))
  # Define the model architecture (replace with your desired model complexity)
def model_fn(inputs):
   features, _ = inputs  # We only use features for classification
   dense1 = tf.keras.layers.Dense(10, activation='relu')(features)
   dense2 = tf.keras.layers.Dense(3, activation='softmax')(dense1)  # 3 units for 3 Iris classes
   return tf.keras.Model(inputs=features, outputs=dense2)

# Define the client optimizer
client_optimizer = tf.keras.optimizers.SGD(learning_rate=0.1)

# Define the server optimizer (for server-sided aggregation)
server_optimizer = tf.keras.optimizers.SGD(learning_rate=0.01)
fed_learning_model = tff.learning.build_federated_averaging_process(
     model_fn,
     client_optimizer_fn=client_optimizer,
     server_optimizer_fn=server_optimizer)

But I am getting this error consistently.

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-13-e5966e29fc79> in <cell line: 1>()
----> 1 fed_learning_model = tff.learning.build_federated_averaging_process(
      2      model_fn,
      3      client_optimizer_fn=client_optimizer,
      4      server_optimizer_fn=server_optimizer)

AttributeError: module 'tensorflow_federated.python.learning' has no attribute 'build_federated_averaging_process'

I dont know whether my version suites. my tensorflow federated version is 0.76.0 my tensorflow version is 2.14.1 and python version is 3.10.12

When i search through the internet i saw that this code doesnot support for tensorflow version 0.21.0 onwards. but i dont know what to use in the latest version

1 Answer 1

2

You should use tff.learning.algorithms.build_weighted_fed_avg() instead.

This function takes in input a FunctionalModel: for this reason, you have to call tff.learning.models.functional_model_from_keras() to convert your Keras model in a Functional one before creating the trainer

model = tff.learning.models.functional_model_from_keras(
        model_fn(),
        loss_fn=tf.keras.losses.CategoricalCrossentropy(),
        input_spec=(
              tf.TensorSpec(shape=[None, 4], dtype=tf.float32),
              tf.TensorSpec(shape=[None, 3], dtype=tf.float32)
        ),
        metrics_constructor=collections.OrderedDict(
              accuracy=tf.keras.metrics.BinaryAccuracy,
              precision=tf.keras.metrics.Precision,
              recall=tf.keras.metrics.Recall,
            )
  )

fed_learning_model = tff.learning.algorithms.build_weighted_fed_avg(
                      model_fn= model,
                      client_optimizer_fn=client_optimizer,
                      server_optimizer_fn=server_optimizer
                    )
Sign up to request clarification or add additional context in comments.

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.