我目前正在开发我的机器学习svm_hog模型。现在我想将我的模型连接到Flask。然而,每次我在网页上点击预测按钮时,它都会带我到一个显示内部服务器错误的页面。我的模型运行得很好,我认为问题出在我的Flask代码中,但直到现在我仍然遇到错误。以下是我用来运行Flask的代码。
flask.py :
import osfrom app import appimport urllib.requestfrom flask import Flask, flash, request, redirect, url_for, render_templatefrom werkzeug.utils import secure_filenameimport tkinter as tkfrom tkinter import filedialog from tkinter import *from PIL import Image, ImageTkfrom tkinter.messagebox import showinfoALLOWED_EXTENSIONS = set(['png', 'jpg', 'jpeg', 'gif'])def allowed_file(filename): return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONSdef predictThis(folder_path): from keras.models import load_model import numpy as np from keras.preprocessing import image from numpy import argmax model = load_model("HOG_SVM.npy") img_width,img_height=550,293 abnormalities = {0:"normal", 1:"abnormal"} test_image = image.load_img(folder_path, target_size=(img_width,img_height)) test_image = image.img_to_array(test_image) test_image = np.expand_dims(test_image,axis=0) result = model.predict(test_image) category_result = argmax(result) return abnormalities[category_result]app = Flask(__name__)#flask routing@app.route("/")def home(): return render_template("home.html")@app.route("/start")def start(): return render_template("start.html")@app.route('/start', methods=['POST'])def upload_image(): if 'file' not in request.files: flash('No file part') return redirect(request.url) file = request.files['file'] if file.filename == '': flash('No image selected for uploading') return redirect(request.url) if file and allowed_file(file.filename): filename = secure_filename(file.filename) file.save(os.path.join('static/upload', filename)) #print('upload_image filename: ' + filename) #flash('Image successfully uploaded and displayed below') result = predictThis('static/upload/' + filename) if result == 'normal': train = "NORMAL CHEST X RAY" elif result == 'abnormal': train = "TUBERCULOSIS CHEST X-RAY" return render_template('start.html', output=train, filename=filename) else: flash('Allowed image types are -> png, jpg, jpeg, gif') return redirect(request.url)@app.route('/display/<filename>')def display_image(filename): #print('display_image filename: ' + filename) return redirect(url_for('static', filename='upload/' + filename), code=301)if __name__=='__main__': app.run(debug=True)
我的机器学习模型代码 (HOG_SVM.npy):
from sklearn import svmfrom sklearn.metrics import classification_reportfrom sklearn.model_selection import train_test_splitfrom skimage import colorfrom imutils.object_detection import non_max_suppressionimport imutilsimport numpy as npimport argparseimport cv2import osimport globfrom sklearn import metricsfrom PIL import Image from numpy import *# define parameters of HOG feature extractionorientations = 9pixels_per_cell = (8, 8)cells_per_block = (2, 2)threshold = .3dataset_path = r"C:\Users\user\Desktop\Train" # The path of dataset# Read the image files:category_im_listing = os.listdir(dataset_path) # Read all the files in the pathnum_category_im = size(category_im_listing) # States the total no. of categoryprint("There are " + str(num_category_im) + " categories") # Prints the number value of the no.of categories datasetdata= []labels = []count = 0# compute HOG features and label them:for category in category_im_listing: # Enables reading the files in the pos_im_listing variable one by one im_listing = os.listdir(dataset_path + "/" + category) num_im = size(im_listing) print("There are " + str(num_im) + " images in category " + str(count + 1)) for file in im_listing: img = Image.open(dataset_path + "/" + category + "/" + file) # open the file img = img.resize((150,150)) gray = img.convert('L') # convert the image into single channel # calculate HOG for positive features fd = hog(gray, orientations, pixels_per_cell, cells_per_block, block_norm='L2', feature_vector=True) # fd= feature descriptor data.append(fd) labels.append(count) count = count + 1# encode the labels, converting them from strings to integersle = LabelEncoder()labels = le.fit_transform(labels)# Partitioning the data into training and testing splits, using 80%# of the data for training and the remaining 20% for testingprint(" Constructing training/testing split...")(trainData, testData, trainLabels, testLabels) = train_test_split(np.array(data), labels, train_size=0.80, test_size=0.20, random_state=42)#%% Train the linear SVMprint(" Training Linear SVM classifier with HOG...")model = svm.LinearSVC(multi_class='ovr')model.fit(trainData, trainLabels)#%% Evaluate the classifierprint(" Evaluating classifier on test data ...")predictions = model.predict(testData)print(classification_report(testLabels, predictions))print("Validation Accuracy:",metrics.accuracy_score(testLabels, predictions))# Save the model:joblib.dump(model, 'HOG_SVM.npy')
start.html :
<form method="post" action="/start" enctype="multipart/form-data"> {% if filename %} <img src="{{ url_for('display_image', filename=filename) }}" width="250" height="290"> <label for="actual-btn" class="center">{{output}}</label> {% else %} <input class="center" accept="image/*" onchange="loadFile(event)" type="file" name="file" autocomplete="off" required> <input type="submit" value="Classify" cass="btn"> {% endif %} </form>
更新:我在flask.py代码中将app.run()行修改为app.run(debug=True),然后它显示如下内容
* Serving Flask app "__main__" (lazy loading) * Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Debug mode: on * Restarting with windowsapi reloaderAn exception has occurred, use %tb to see the full traceback.SystemExit: 1C:\Users\user\anaconda3\lib\site-packages\IPython\core\interactiveshell.py:3426: UserWarning: To exit: use 'exit', 'quit', or Ctrl-D. warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
然后我运行%tb后,它显示如下内容
---------------------------------------------------------------------------SystemExit Traceback (most recent call last)<ipython-input-8-869c29e262d1> in <module> 1 if __name__=='__main__':----> 2 app.run(debug=True)~\anaconda3\lib\site-packages\flask\app.py in run(self, host, port, debug, load_dotenv, **options) 988 989 try:--> 990 run_simple(host, port, self, **options) 991 finally: 992 # reset the first request information if the development server~\anaconda3\lib\site-packages\werkzeug\serving.py in run_simple(hostname, port, application, use_reloader, use_debugger, use_evalex, extra_files, reloader_interval, reloader_type, threaded, processes, request_handler, static_files, passthrough_errors, ssl_context) 1048 from ._reloader import run_with_reloader 1049 -> 1050 run_with_reloader(inner, extra_files, reloader_interval, reloader_type) 1051 else: 1052 inner()~\anaconda3\lib\site-packages\werkzeug\_reloader.py in run_with_reloader(main_func, extra_files, interval, reloader_type) 337 reloader.run() 338 else:--> 339 sys.exit(reloader.restart_with_reloader()) 340 except KeyboardInterrupt: 341 passSystemExit: 1
回答:
if name==’main‘:
app.run(debug=True,port=9989,use_reloader=False)
- 使用上述代码
- 如果你使用Jupyter Notebook来运行Flask应用,我建议你切换到Spyder、PyCharm或VS Code等IDE
- 因为在IDE中调试问题比在Jupyter Notebook中更容易