Tensorflow federated attribute error

# Importing all the required libraries

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) 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

Hi, I am running into the same problem. Have you found a solution?

Official TensorFlow 2.16 Repo via JARaaS Hybrid RAG - Documentation - code current 6/17/2024

Note: Sources at the end of the response

It seems you are encountering an AttributeError because the method build_federated_averaging_process might have been deprecated or its module path might have changed in the newer versions of TensorFlow Federated.

As of TensorFlow Federated (TFF) version 0.76.0, there may indeed be changes in the API. Let’s verify a few steps and consider possible alternatives.

Steps to Troubleshoot and Fix:

  1. Check Module Path: Ensure that the correct module path is being used.

    • The tff.learning.build_federated_averaging_process method might now reside in a different sub-module or have been renamed.
  2. Consult the TFF Documentation: Refer to the updated TensorFlow Federated documentation for the latest API updates and examples.

  3. Update Code if Required:

    • If the method has been deprecated or moved to another path, update your code accordingly. Sometimes methods are relocated to sub-modules like tff.learning.algorithms.

Here is an example code snippet to get you started with the updated federated averaging process:

# Import necessary libraries
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

# Load the Iris dataset
iris = load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)
df['Species'] = iris.target

# Split the data 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 client datasets (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 = tf.keras.layers.Input(shape=(4,))  # 4 features in the Iris dataset
    dense1 = tf.keras.layers.Dense(10, activation='relu')(inputs)
    dense2 = tf.keras.layers.Dense(3, activation='softmax')(dense1)  # 3 units for 3 Iris classes
    return tf.keras.Model(inputs=inputs, outputs=dense2)

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

# Define the server optimizer (for server-sided aggregation)
server_optimizer = lambda: tf.keras.optimizers.SGD(learning_rate=0.01)

# Build the federated averaging process using appropriate module path
fed_learning_model = tff.learning.algorithms.build_weighted_fed_avg(
    model_fn=model_fn,
    client_optimizer_fn=client_optimizer,
    server_optimizer_fn=server_optimizer
)

# Start a round of federated training
state = fed_learning_model.initialize()
state, metrics = fed_learning_model.next(state, client_datasets)
print(metrics)

Key Points:

  • Verify the correct path or naming conventions of the functions in the latest TFF.
  • Utilize lambdas or callable functions for the optimizer as required by the build_weighted_fed_avg.

Sources:

  • TensorFlow Federated Documentation: Official API reference for the latest version.
  • Internal debugging scripts: tensorflow_federated_upgrade_guide.md (internal document)

Thanks Wolf for your answer, but I managed to get myself sorted. PIP just uograded from version 0.79 to version 0.80 and deprecated build_federated_evaluation which was actually my issue. I simply downgraded the package to fix the problem