ModuleNotFoundError:没有名为“keras.src”的模块

问题描述 投票:0回答:2

我尝试制作一个使用张量流预测肺癌的网站并使用烧瓶进行部署。我在 app.py 中使用 pickle 加载模型。 这是我的 app.py 代码

from flask import Flask, request, render_template
# import tensorflow as tf
import numpy as np
import pickle

app = Flask(__name__)

# model = pickle.load(open("model.pkl", "rb"))
# model = tf.keras.models.load_model("model.h5")

@app.route("/")
def home():
    return render_template("index.html")

@app.route("/predict", methods=["POST"])
def predict():
    str_pred = ''
    # age, gender, yellow_finger, anxiety, peer_pressure, chronic_disease, fatigue, allergy, wheezing, alcohol_consuming, coughing, swallowing_difficulty, chest_pain

    age = int(request.form["age"])
    final_age = (age - 62.08510638) / 46.0211257
    gender = int(request.form["gender"])
    yellow_finger = int(request.form["yellow_finger"])
    anxiety = int(request.form["anxiety"])
    peer_pressure = int(request.form["peer_pressure"])
    chronic_disease = int(request.form["chronic_disease"])
    fatigue = int(request.form["fatigue"])
    allergy = int(request.form["allergy"])
    wheezing = int(request.form["wheezing"])
    alcohol_consuming = int(request.form["alcohol_consuming"])
    coughing = int(request.form["coughing"])
    swallowing_difficulty = int(request.form["swallowing_difficulty"])
    chest_pain = int(request.form["chest_pain"])

    list_data = [gender, final_age, yellow_finger, anxiety, peer_pressure, chronic_disease, fatigue, allergy, wheezing,
                 alcohol_consuming, coughing, swallowing_difficulty, chest_pain]
    list_data = np.array(list_data)

    model = pickle.load(open("model.pkl", "rb"))

    prediction_results = model.predict([list_data])
    prediction_results = prediction_results[0]

    if prediction_results >= 0.5:
        return render_template("index.html", str_pred='Ada kanker paru-paru')
    elif prediction_results < 0.5:
        return render_template("index.html", str_pred='Tidak ada kanker paru-paru')

if __name__ == "__main__":
    app.run(debug=True)

这是我的模型

import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import tensorflow as tf
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import confusion_matrix, classification_report

import pickle

df = pd.read_csv('survey_lung_cancer.csv')

df['GENDER'].replace(['M', 'F'], [0, 1], inplace=True)
df['LUNG_CANCER'].replace(['NO', 'YES'], [0, 1], inplace=True)

df = df.drop(['SMOKING', 'SHORTNESS OF BREATH'], axis=1)

df.drop_duplicates(inplace=True)

def finding_outlier_IQR(df):
  Q1 = df.quantile(0.25)
  Q3 = df.quantile(0.75)
  IQR = Q3 - Q1
  df_final = df[((df < (Q1 - 1.5 * IQR)) | (df > (Q3 + 1.5 * IQR)))]
  return df_final

print(finding_outlier_IQR(df['AGE']))

Q1 = df['AGE'].quantile(0.25)
Q3 = df['AGE'].quantile(0.75)
IQR  = Q3 - Q1

Lower_bound = Q1-1.5*IQR
Upper_bound = Q3+1.5*IQR
print(Lower_bound,Upper_bound)

New_Age= (df['AGE']>Lower_bound) & (df['AGE']<Upper_bound)
filtered_data= df[New_Age]
sns.boxplot(x='AGE', data=filtered_data)

y = filtered_data['LUNG_CANCER']
X = filtered_data.drop('LUNG_CANCER',axis=1)

for i in X.columns[2:]:
    temp=[]
    for j in X[i]:
        temp.append(j-1)
    X[i]=temp
X

from imblearn.over_sampling import SMOTE
smote = SMOTE(sampling_strategy='auto', random_state=42)
X, y = smote.fit_resample(X, y)

X_train, X_test, y_train, y_test = train_test_split(X, y, random_state = 42, test_size=0.2)
X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size=0.25, random_state = 42)

scaler = StandardScaler()
X_train['AGE'] = scaler.fit_transform(X_train[['AGE']])
X_val['AGE'] = scaler.transform(X_val[['AGE']])
X_test['AGE'] = scaler.transform(X_test[['AGE']])

print(scaler.mean_)
print(scaler.var_)

model = tf.keras.Sequential([
    tf.keras.layers.Dense(9, activation='relu', input_shape=[13]),
    tf.keras.layers.Dense(1, activation='sigmoid')
])
model.build()
model.summary()
model.compile(
    loss=tf.keras.losses.BinaryCrossentropy(),
    optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),
    metrics=['accuracy']
)
history = model.fit(X_train, y_train,
                    epochs=100, batch_size=16,
                    validation_data=(X_val, y_val),
                    shuffle=True)
test_loss, test_acc = model.evaluate(X_test, y_test)
print("Test loss:", test_loss)
print("Test accuracy:", test_acc)

y_true = y_test
y_pred = model.predict(X_test)

cf_matrix = confusion_matrix(y_true.round(), y_pred.round())
print("\nConfusion Matrix")
sns.heatmap(cf_matrix, annot=True, cmap='Blues')
plt.xlabel('Predicted', fontsize=12)
plt.ylabel('True', fontsize=12)


pickle.dump(model, open("model.pkl", "wb"))

但是,没有成功。我收到一个错误,他们没有模块 keras,但我已经安装了它。

[2023-09-26 20:18:30,267] ERROR in app: Exception on /predict [POST]
Traceback (most recent call last):
  File "c:\users\asus\appdata\local\programs\python\python39\lib\site-packages\flask\app.py", line 2525, in wsgi_app
    response = self.full_dispatch_request()
  File "c:\users\asus\appdata\local\programs\python\python39\lib\site-packages\flask\app.py", line 1822, in full_dispatch_request
    rv = self.handle_user_exception(e)
  File "c:\users\asus\appdata\local\programs\python\python39\lib\site-packages\flask\app.py", line 1820, in full_dispatch_request
    rv = self.dispatch_request()
  File "c:\users\asus\appdata\local\programs\python\python39\lib\site-packages\flask\app.py", line 1796, in dispatch_request
    return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)
  File "D:\AMIKOM\SKRIPSI\dep_pycharm\app.py", line 39, in predict
    model = pickle.load(open("model.pkl", "rb"))
ModuleNotFoundError: No module named 'keras.src'

我已经升级了tensorflow、keras等。但是,仍然遇到同样的错误。我可以在 Flask 中部署神经网络模型吗?或者我应该尝试另一种语言?谢谢你

python tensorflow flask keras deep-learning
2个回答
0
投票

最近的版本应该有pickle支持,但过去较旧的Keras版本不支持Pickle来序列化其对象(模型)。

pip install joblib
import joblib

# Save the model
joblib.dump(model, "model.pkl")
joblib.load("model.pkl")

可以在此处找到完整文档。

为了回答你的尾随问题,如果你正确设置了环境,Flask 应该不是问题 - 我将在我研究此问题时找到的媒体文章中添加一个链接


0
投票

检查Keras的版本。然后尝试将keras更新到最新版本。 Pickle 4.0 版本需要 Keras 版本 >= 2.13.0。

要更新 keras 版本,请打开 CMD 并激活您的环境,然后使用以下代码卸载当前版本的 keras

pip 卸载 keras

卸载后尝试使用安装最新的 keras 版本

pip安装keras==2.14.0

© www.soinside.com 2019 - 2024. All rights reserved.