'numpy.float64' object is not callable when running sklearn prediction in for loop to find best max_leaf_node size

Viewed 19

I want to refine the Random Forest Regressor by defining the max_leaf_nodes using a for loop to find the best mean_absolut_error. As soon as I try to iterate through different leaf sizes, it returns a type error. Running the function outside the loop executes it without error.


# import Training files and set targen (y) and training data (X)
# Load the data, and separate the target
iowa_file_path = '../input/train.csv'
home_data = pd.read_csv(iowa_file_path)

# set variables
y = home_data['SalePrice']

features = ['LotArea', 'YearBuilt', '1stFlrSF', '2ndFlrSF', 'FullBath', 'BedroomAbvGr', 'TotRmsAbvGrd', 'OverallQual', 'YearBuilt', 'OverallCond' ]
X = home_data[features]

# assign train test split variables
train_X, val_X, train_y, val_y = tts(X, y, random_state=1)
def get_mae(max_leaf_nodes, train_X, val_X, train_y, val_y):
    # build a model
    hd_model = RandomForestRegressor(max_leaf_nodes = max_leaf_nodes, random_state=0)
    # fit the data
    hd_model.fit(train_X, train_y)
    # validate the data
    val_predictions = hd_model.predict(val_X)
    val_mae = mae(val_predictions, val_y)
    return val_mae
for max_leaf_nodes in [100, 200, 500, 700, 900, 1200, 1500]:
    mae = get_mae(max_leaf_nodes, train_X, val_X, train_y, val_y)
    print(f"Node Size: {max_leaf_nodes} \t\t Mean Absolute Error: {mae}")
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/tmp/ipykernel_1967/4270359130.py in <module>
     38 
     39 for max_leaf_nodes in [100, 200, 500, 700, 900, 1200, 1500]:
---> 40     mae = get_mae(max_leaf_nodes, train_X, val_X, train_y, val_y)
     41     print(node, mae)
     42 

/tmp/ipykernel_1967/4270359130.py in get_mae(max_leaf_nodes, train_X, val_X, train_y, val_y)
     31     # validate the data
     32     val_predictions = hd_model.predict(val_X)
---> 33     val_mae = mae(val_predictions, val_y)
     34     return val_mae
     35 

TypeError: 'numpy.float64' object is not callable
0 Answers
Related