前提・実現したいこと
pythonを用いて、自分で学習させたモデルを使用したWebアプリを作ろうとしています。
Google ColabのGPU上で学習させたモデルを、pickleにしてドライブに保存し、コマンドプロンプト上で動作させたところ、入力をアップロードした後の処理が上手くいかず、chrome上で“Internal Server Error”が出てしまいました。
エラーメッセージを見てみると、モデルがCPUで動作していないとあったので、デバイスをCPUに移そうとしたのですが、上手くいきませんでした。
model.to('cpu')をしても同様のエラーが出てしまったのですが、どうしてなのでしょうか?
### コマンドプロンプトで出力されたエラー文
C:\Users\hatae\AppData\Local\Programs\Python\Python39\lib\site-packages\torch\cuda\__init__.py:52: UserWarning: CUDA initialization: Found no NVIDIA driver on your system. Please check that you have an NVIDIA GPU and installed a driver from http://www.nvidia.com/Download/index.aspx (Triggered internally at ..\c10\cuda\CUDAFunctions.cpp:100.) return torch._C._cuda_getDeviceCount() > 0 [2021-07-24 14:50:49,133] ERROR in app: Exception on / [POST] Traceback (most recent call last): File "C:\Users\hatae\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\app.py", line 2070, in wsgi_app response = self.full_dispatch_request() File "C:\Users\hatae\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\app.py", line 1515, in full_dispatch_request rv = self.handle_user_exception(e) File "C:\Users\hatae\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\app.py", line 1513, in full_dispatch_request rv = self.dispatch_request() File "C:\Users\hatae\AppData\Local\Programs\Python\Python39\lib\site-packages\flask\app.py", line 1499, in dispatch_request return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args) File "C:\Users\hatae\OneDrive\デスクトップ\pHAI\app.py", line 88, in predicts pred = predict(img) File "C:\Users\hatae\OneDrive\デスクトップ\pHAI\app.py", line 17, in predict model_ft.load_state_dict(torch.load('./ResNet.pkl')).to(torch.device('cpu')) File "C:\Users\hatae\AppData\Local\Programs\Python\Python39\lib\site-packages\torch\serialization.py", line 594, in load return _load(opened_zipfile, map_location, pickle_module, **pickle_load_args) File "C:\Users\hatae\AppData\Local\Programs\Python\Python39\lib\site-packages\torch\serialization.py", line 853, in _load result = unpickler.load() File "C:\Users\hatae\AppData\Local\Programs\Python\Python39\lib\site-packages\torch\serialization.py", line 845, in persistent_load load_tensor(data_type, size, key, _maybe_decode_ascii(location)) File "C:\Users\hatae\AppData\Local\Programs\Python\Python39\lib\site-packages\torch\serialization.py", line 834, in load_tensor loaded_storages[key] = restore_location(storage, location) File "C:\Users\hatae\AppData\Local\Programs\Python\Python39\lib\site-packages\torch\serialization.py", line 175, in default_restore_location result = fn(storage, location) File "C:\Users\hatae\AppData\Local\Programs\Python\Python39\lib\site-packages\torch\serialization.py", line 151, in _cuda_deserialize device = validate_cuda_device(location) File "C:\Users\hatae\AppData\Local\Programs\Python\Python39\lib\site-packages\torch\serialization.py", line 135, in validate_cuda_device raise RuntimeError('Attempting to deserialize object on a CUDA ' RuntimeError: Attempting to deserialize object on a CUDA device but torch.cuda.is_available() is False. If you are running on a CPU-only machine, please use torch.load with map_location=torch.device('cpu') to map your storages to the CPU.
Chromeでのエラー
Internal Server Error
The server encountered an internal error and was unable to complete your request. Either the server is overloaded or there is an error in the application.
実行したapp.py
from torchvision import datasets, models, transforms from flask import Flask, render_template, request, flash from wtforms import Form, FloatField, SubmitField, validators, ValidationError import numpy as np #from sklearn.externals import joblib import cv2 import datetime import torch # 学習済みモデルを読み込み利用します def predict(parameters): # ニューラルネットワークのモデルを読み込み device = torch.device("cpu") model_ft = models.resnet18(pretrained=False).to(torch.device('cpu')) model_ft = model_ft.to('cpu') model_ft.load_state_dict(torch.load('./ResNet.pkl')).to(torch.device('cpu')) params = parameters.reshape(1,-1) #pred = model.predict(params) pred = model_ft(params) return pred # ラベルからIrisの名前を取得します def getName(label): print(label) if label == 0: return "pH 6.00 ~ 6.25" elif label == 1: return "pH 6.26 ~ 6.50" elif label == 2: return "pH 6.51 ~ 6.75" elif label == 3: return "pH 6.76 ~ 7.00" elif label == 4: return "pH 7.01 ~ 7.25" elif label == 5: return "pH 7.26 ~ 7.50" elif label == 6: return "pH 7.51 ~ 7.75" elif label == 7: return "pH 6.76 ~ 8.00" else : return "Error" app = Flask(__name__) app.config.from_object(__name__) app.config['SECRET_KEY'] = 'zJe09C5c3tMf5FnNL09C5d6SAzZoY' # 公式サイト # http://wtforms.simplecodes.com/docs/0.6/fields.html # Flaskとwtformsを使い、index.html側で表示させるフォームを構築します。 class IrisForm(Form): """ SepalLength = FloatField("Sepal Length(cm)(蕚の長さ)", [validators.InputRequired("この項目は入力必須です"), validators.NumberRange(min=0, max=10)]) SepalWidth = FloatField("Sepal Width(cm)(蕚の幅)", [validators.InputRequired("この項目は入力必須です"), validators.NumberRange(min=0, max=10)]) PetalLength = FloatField("Petal length(cm)(花弁の長さ)", [validators.InputRequired("この項目は入力必須です"), validators.NumberRange(min=0, max=10)]) PetalWidth = FloatField("petal Width(cm)(花弁の幅)", [validators.InputRequired("この項目は入力必須です"), validators.NumberRange(min=0, max=10)]) """ # html側で表示するsubmitボタンの表示 submit = SubmitField("判定") @app.route('/', methods = ['GET', 'POST']) def predicts(): img_dir = "static/imgs/" if request.method == 'GET': img_path=None elif request.method == 'POST': #### POSTにより受け取った画像を読み込む stream = request.files['img'].stream img_array = np.asarray(bytearray(stream.read()), dtype=np.uint8) img = cv2.imdecode(img_array, 1) #### 現在時刻を名前として「imgs/」に保存する dt_now = datetime.datetime.now().strftime("%Y%m%d%H%M%S%f") img_path = img_dir + dt_now + ".jpg" cv2.imwrite(img_path, img) pred = predict(img) irisName = getName(pred) return render_template('result.html', irisName=irisName) #### 保存した画像ファイルのpathをHTMLに渡す return render_template('index.html', img_path=img_path) """ form = IrisForm(request.form) if request.method == 'POST': if form.validate() == False: flash("全て入力する必要があります。") return render_template('index.html', form=form) else: SepalLength = float(request.form["SepalLength"]) SepalWidth = float(request.form["SepalWidth"]) PetalLength = float(request.form["PetalLength"]) PetalWidth = float(request.form["PetalWidth"]) #x = np.array([SepalLength, SepalWidth, PetalLength, PetalWidth]) pred = predict(x) irisName = getName(pred) return render_template('result.html', irisName=irisName) elif request.method == 'GET': return render_template('index.html', form=form) """ if __name__ == "__main__": app.run()
回答1件
あなたの回答
tips
プレビュー