I know there are several questions regarding the not-fitted error. But my problem was even I used Joblib and dump to save my custom model and tried to run the model on Flask it gave me an error.
NotFittedError
sklearn.exceptions.NotFittedError: This StandardScaler instance is not
fitted yet. Call ‘fit’ with appropriate arguments before using this
estimator.
I have a custom MLP model trained in Jupyter Notebook. Everything was going great not until I tried to use it for a single image detection app through Flask.
I saved my model using Pickle and Joblib (which I inserted after the training loop before plotting the results):
with open('best_model-2.pkl', 'wb') as file:
pickle.dump(best_model, file)
Load it in my app.py
loaded_model = custom_load_model("models/best_model-2.pkl")
Now, I have a pipeline used during my training (on Jupyter):
preprocessor = Pipeline(
[("standardize", StandardScaler()), ("pca", PCA(n_components=0.95))] )
I tried to save it as pickle, also just what an AI said, but the problem persisted so instead of importing it to Flask as a PKL file, I just made my own in the Flask app:
preprocessor = StandardScaler()
pca = PCA(n_components=0.95)
#Sample Usage
if file:
image = Image.open(file)
image_resized = image.resize((256, 256))
image_array = np.array(image_resized)
gray_img = cv2.cvtColor(image_array, cv2.COLOR_RGB2GRAY)
bin_img = binarize_hue_saturation(rgb2hsv(image_array))
color_features = extract_color_feature(image_array)
texture_features = extract_texture_feature(gray_img * (bin_img / 255))
feature_vector = np.concatenate([color_features, texture_features])
# Apply preprocessing steps
preprocessed_feature = preprocessor.transform([feature_vector])
preprocessed_feature = pca.transform(preprocessed_feature)
predictions = loaded_model.predict(preprocessed_feature)
probabilities = loaded_model.predict_proba(preprocessed_feature)
I don’t know where the problem is, even if I tried to change, remove, or modify my code. I just want my custom model to work in the app. But it always gives me NotFittedError.
Any help will be much appreciated. Thank you.