강의

멘토링

로드맵

Inflearn brand logo image

인프런 커뮤니티 질문&답변

정해찬님의 프로필 이미지
정해찬

작성한 질문수

플라스크 ModuleNotFoundError 오류

작성

·

463

0

플라스크에서 머신러닝 웹 서비스 예제를 실행해보려고 하는데 에러가 발생합니다

import flask
import joblib
import numpy as np
from flask import Flask, request, render_template
from scipy import misc

app = Flask(__name__)


# 메인 페이지 라우팅
@app.route("/")
@app.route("/index")
def index():
    return flask.render_template('index.html')


# 데이터 예측 처리
@app.route('/predict', methods=['POST'])
def make_prediction():
    if request.method == 'POST':

        # 업로드 파일 처리 분기
        file = request.files['image']
        if not file: return render_template('index.html', label="No Files")

        # 이미지 픽셀 정보 읽기
        # 알파 채널 값 제거 후 1차원 Reshape
        img = misc.imread(file)
        img = img[:, :, :3]
        img = img.reshape(1, -1)

        # 입력 받은 이미지 예측
        prediction = model.predict(img)

        # 예측 값을 1차원 배열로부터 확인 가능한 문자열로 변환
        label = str(np.squeeze(prediction))

        # 숫자가 10일 경우 0으로 처리
        if label == '10': label = '0'

        # 결과 리턴
        return render_template('index.html', label=label)


if __name__ == '__main__':
    # 모델 로드
    # ml/model.py 선 실행 후 생성
    model = joblib.load('./model/model.pkl')
    # Flask 서비스 스타트
    app.run(host='0.0.0.0', port=8000, debug=True)
import scipy.io
from sklearn.utils import shuffle
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split
import joblib

# Google 주소 숫자 인식 모델 생성

# 로드 mat 파일
train_data = scipy.io.loadmat('extra_32x32.mat')

# 학습 데이터, 훈련 데이터
X = train_data['X']
y = train_data['y']

# 매트릭스 1D 변환
X = X.reshape(X.shape[0] * X.shape[1] * X.shape[2], X.shape[3]).T
y = y.reshape(y.shape[0], )

# 셔플(섞기)
X, y = shuffle(X, y, random_state=42)

print("Model Export Running")

# 학습 훈련 데이터 분리
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.05, random_state=42)

# 랜덤 포레스트 객체 생성 및 학습
clf = RandomForestClassifier()
clf.fit(X_train, y_train)

# 모델 저장
joblib.dump(clf, '../model/model.pkl')

위 코드가 main.py 이고 아래 코드가 model.py입니다
코드를 실행하면
Traceback (most recent call last):

File "/Users/jeonghaechan/PycharmProjects/flaskML/main.py", line 48, in <module>

model = joblib.load('./model/model.pkl')

File "/Users/jeonghaechan/PycharmProjects/flaskML/venv/lib/python3.9/site-packages/joblib/numpy_pickle.py", line 658, in load

obj = unpickle(fobj, filename, mmapmode)

File "/Users/jeonghaechan/PycharmProjects/flaskML/venv/lib/python3.9/site-packages/joblib/numpy_pickle.py", line 577, in _unpickle

obj = unpickler.load()

File "/Users/jeonghaechan/opt/anaconda3/lib/python3.9/pickle.py", line 1212, in load

dispatch[key[0]](self)

File "/Users/jeonghaechan/opt/anaconda3/lib/python3.9/pickle.py", line 1528, in load_global

klass = self.find_class(module, name)

File "/Users/jeonghaechan/opt/anaconda3/lib/python3.9/pickle.py", line 1579, in find_class

import(module, level=0)

ModuleNotFoundError: No module named 'sklearn.ensemble.forest'

이렇게 뜨는데 어떻게 해야하나요?

답변 1

0

안녕하세요, 인프런 AI 인턴입니다.

정해찬님의 질문에 답변드리겠습니다.

오류 메시지 ModuleNotFoundError: No module named 'sklearn.ensemble.forest'의 원인은 특정 버전의 scikit-learn에서 RandomForestClassifiersklearn.ensemble.forest 모듈 대신 sklearn.ensemble 모듈로 이동되었기 때문입니다. 이로 인해 오래된 코드 또는 라이브러리가 새 버전의 scikit-learn과 호환되지 않을 때 발생할 수 있습니다.

이 문제를 해결하려면 다음과 같은 방법을 시도해볼 수 있습니다.

  1. RandomForestClassifier의 import 구문을 현재 scikit-learn 버전에 맞게 업데이트합니다.

    from sklearn.ensemble import RandomForestClassifier
    
  2. 사용 중인 scikit-learn의 버전을 확인하고, 필요한 경우 업데이트합니다. 아나콘다나 pip를 사용하여 scikit-learn을 업데이트할 수 있습니다.

    • Anaconda를 사용할 경우:
      
      conda update scikit-learn
      

    • pip를 사용할 경우:
      
      pip install -U scikit-learn
      

현재 사용 중인 코드에 나타난 import 방식은 이미 최신 방식으로 작성되어 있으므로, 주로 scikit-learn의 버전 문제일 가능성이 높습니다. 따라서 scikit-learn을 최신 버전으로 업데이트해보시기 바랍니다.

도움이 필요하시면 언제든지 질문해주세요!

정해찬님의 프로필 이미지
정해찬

작성한 질문수

질문하기