import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score
from sklearn.neighbors import NearestNeighbors
from scipy.stats import rankdata
class BMFK:
def init(self, n_neighbors=5, m=2, p=2, q=2):
self.n_neighbors = n_neighbors
self.m = m # fuzzy strength parameter
self.p = p # Bonferroni p parameter
self.q = q # Bonferroni q parameter
code
def fit(self, X, y):
self.X = X
self.y = y
self.classes = np.unique(y)
self.nn = NearestNeighbors(n_neighbors=self.n_neighbors, metric='minkowski', p=2)
self.nn.fit(X)
def bonferroni_mean(self, values):
n = len(values)
if n <= 1:
return np.mean(values) # Return simple mean if there's only one value
sum_pq = 0
for i in range(n):
for j in range(n):
if i != j:
sum_pq += values[i]**self.p * values[j]**self.q
return (sum_pq / (n * (n-1)))**(1 / (self.p + self.q))
def predict(self, X):
predictions = []
for x in X:
distances, indices = self.nn.kneighbors([x]) # Ensure x is in 2D
neighbors = self.X[indices[0]]
neighbor_labels = self.y[indices[0]]
# Calculate fuzzy memberships
memberships = 1 / (distances[0] ** (2 / (self.m - 1)) + 1e-8)
memberships /= np.sum(memberships)
# Calculate class memberships using Bonferroni mean
class_memberships = {}
for c in self.classes:
class_indices = neighbor_labels == c
if np.any(class_indices):
class_memberships[c] = self.bonferroni_mean(memberships[class_indices])
else:
class_memberships[c] = 0
# Predict the class with highest membership
predictions.append(max(class_memberships, key=class_memberships.get))
return np.array(predictions)
rl_selected_features = [' Age (yrs)', 'Height(Cm) ', 'RR (breaths/min)', 'No. of aborptions',
'Hip(inch)', 'Waist:Hip Ratio', 'AMH(ng/mL)', 'PRG(ng/mL)',
'Fast food (Y/N)', 'Follicle No. (R)', 'Avg. F size (L) (mm)',
'Endometrium (mm)']
Function to evaluate the BMFK classifier
def evaluate_bmfk(X_data, y_data):
# Split the data into training (90%) and testing (10%) sets
X_train, X_test, y_train, y_test = train_test_split(X_data, y_data, test_size=0.1, random_state=42)
code
# Initialize BMFK classifier
bmfk_clf = BMFK(n_neighbors=5, m=2, p=2, q=2)
bmfk_clf.fit(X_train, y_train)
# Make predictions on the test set
y_pred = bmfk_clf.predict(X_test)
# Calculate accuracy
accuracy = accuracy_score(y_test, y_pred)
return accuracy
Calculate accuracies for each method using BMFK optimizer
print("\n--- Accuracy, Friedman Mean Ranks, and Final Ranks ---")
print(df_results)
c:\Users\manch\AppData\Local\Programs\Python\Python39\lib\site-packages\sklearn\base.py:493: UserWarning: X does not have valid feature names, but NearestNeighbors was fitted with feature names
warnings.warn(
Cell In[1], line 114
111 bmfk_clf.fit(X_train, y_train)
113 # Make predictions on the test set
--> 114 y_pred = bmfk_clf.predict(X_test)
116 # Calculate accuracy
117 accuracy = accuracy_score(y_test, y_pred)
Cell In[1], line 37
35 predictions = []
36 for x in X:
---> 37 distances, indices = self.nn.kneighbors([x]) # Ensure x is in 2D
38 neighbors = self.X[indices[0]]
39 neighbor_labels = self.y[indices[0]]
File c:\Users\manch\AppData\Local\Programs\Python\Python39\lib\site-packages\sklearn\neighbors_base.py:825, in KNeighborsMixin.kneighbors(self, X, n_neighbors, return_distance)
823 X = _check_precomputed(X)
...
1056 )
ValueError: Expected 2D array, got 1D array instead:
array=['Follicle No. (L)'].
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.
Output is truncated. View as a scrollable element or open in a text editor. Adjust cell output settings...
The error you're encountering is due to the BMFK.predict method receiving an unexpected input format. Specifically, it appears that the method is receiving column names (strings) instead of numerical feature values. This usually happens when the feature selection or data preprocessing steps aren't correctly applied to the data being passed to the classifier.
Let's break down the issues and provide a comprehensive solution to ensure your code runs smoothly.
indicates that the BMFK.predict method expects a 2D array of numerical feature values but is instead receiving an array containing a column name string. This suggests that the data being passed to the classifier is not correctly preprocessed or selected.
2. Root Causes
Incorrect Use of Scaled Data:
You performed scaling on the entire dataset using StandardScaler but didn't utilize the scaled data (X_scaled) in the evaluation function. Instead, you passed the original unscaled X with selected features.
Feature Selection on Scaled Data:
Even if you intend to use the scaled data, you're currently selecting features from the original X, which might lead to mismatches or unintended data formats.
DataFrame vs. NumPy Array:
After scaling, X_scaled becomes a NumPy array without column names, making feature selection based on column names invalid unless you convert it back to a DataFrame with appropriate column names.
3. Step-by-Step Solution
a. Convert Scaled Data Back to DataFrame with Column Names
After scaling your features, convert the scaled NumPy array back into a pandas DataFrame and retain the original column names. This allows for seamless feature selection using column names.
python
# After scaling
scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)
# Convert back to DataFrame with original column names
X_scaled_df = pd.DataFrame(X_scaled, columns=X.columns)
b. Update Feature Selection to Use Scaled DataFrame
Modify your feature selection to use X_scaled_df instead of the original X. This ensures that all features passed to the classifier are numerically scaled.
python
# Calculate accuracies for each method using BMFK optimizer
accuracy_proposed = evaluate_bmfk(X_scaled_df[selected_features_proposed].values, y) # Proposed method
accuracy_ensemble = evaluate_bmfk(X_scaled_df[ensemble_selected_features].values, y) # Ensemble method
accuracy_rl = evaluate_bmfk(X_scaled_df[rl_selected_features].values, y) # RL method
accuracy_all = evaluate_bmfk(X_scaled_df.values, y) # All features
c. Ensure All Selected Features Are Numeric
Double-check that all features in your selected_features_proposed, ensemble_selected_features, and rl_selected_features lists are numeric. Since you've already encoded categorical variables, they should be numeric, but it's good practice to verify.
python
# Example check
for feature in selected_features_proposed + ensemble_selected_features + rl_selected_features:
if not pd.api.types.is_numeric_dtype(X_scaled_df[feature]):
print(f"Feature '{feature}' is not numeric.")
If any non-numeric features are found, ensure they are properly encoded before scaling.
d. Complete Revised Code
Here's the revised version of your code incorporating the above changes:
python
e. Additional Recommendations
Verify Feature Selection:
Ensure that all features listed in selected_features_proposed, ensemble_selected_features, and rl_selected_features exist in X_scaled_df. Any mismatch can lead to errors.
python
# Check if all selected features exist in the scaled DataFrame
all_selected_features = selected_features_proposed + ensemble_selected_features + rl_selected_features
missing_features = [feature for feature in all_selected_features if feature not in X_scaled_df.columns]
if missing_features:
print(f"The following selected features are missing in the dataset: {missing_features}")
# Handle missing features accordingly
Handle Spaces in Column Names:
Notice that some feature names have trailing spaces (e.g., 'Height(Cm) ' and ' Age (yrs)'). It's good practice to strip whitespace from column names to avoid issues during feature selection.
python
# Strip whitespace from column names
X_scaled_df.columns = X_scaled_df.columns.str.strip()
Consistency in Feature Names:
Ensure that the feature names in your selection lists exactly match the column names in X_scaled_df. Any discrepancy, including case sensitivity or extra spaces, can cause issues.
Debugging Tips:
Print Sample Data: Before passing data to the classifier, print a sample to ensure correctness.
By ensuring that the scaled data is correctly converted back to a DataFrame with appropriate column names and that feature selection is accurately performed on this scaled DataFrame, the ValueError should be resolved. Additionally, always verify the integrity of your data at each preprocessing step to prevent such issues.
If after these changes you still encounter issues, consider adding more debug statements to inspect the data being passed at each stage. This will help identify and rectify any remaining discrepancies.