【问题标题】:Error occurred while integrating a machine learning model with a flask website将机器学习模型与烧瓶网站集成时出错
【发布时间】:2020-09-11 05:13:38
【问题描述】:

我正在关注tutorial,了解如何将烧瓶 Web 应用程序集成到 ML 模型(我使用线性回归模型,但教程中的模型是决策树),但我得到了 numpy.core._exceptions.UFuncTypeError: ufunc 'matmul' did not contain a loop with signature matching types (dtype('<U32'), dtype('<U32')) -> dtype('<U32')" Image showing error in the commandline

代码(app.py):

def ValuePredictor(to_predict_list):
    to_predict = np.array(to_predict_list).reshape((-1, 5)) 
    loaded_model = pickle.load(open('studentgrades.pkl','rb'))
    result = loaded_model.predict(to_predict)
    return result[0]


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


@app.route("/results", methods=["GET", "POST"])
def results():
    if request.method == "POST":
        # predictions
        to_predict_list=np.array([session['grade1'], session['grade2'], session['absences'],session['failed'], session['hours']])
        predicted = ValuePredictor(to_predict_list)
        session['predicted']=predicted

        return render_template("results.html", name=session['name'],grade1=session['grade1'],grade2=session['grade2'],hours=session['hours'],absences=session['absences'],failed=session['failed'],predicted=session['predicted'])
    else:
        return redirect('/')

代码(机器学习):

data = pd.read_csv("student-mat.csv", sep=";")

predict = "G3"

data = data[["G1", "G2", "absences","failures", "studytime","G3"]]
data = shuffle(data) # Optional - shuffle the data

x = np.array(data.drop([predict], 1))
y =np.array(data[predict])
x_train, x_test, y_train, y_test = sklearn.model_selection.train_test_split(x, y, test_size=0.1)


# TRAIN MODEL MULTIPLE TIMES FOR BEST SCORE
"""best = 0
for _ in range(20):
    x_train, x_test, y_train, y_test = sklearn.model_selection.train_test_split(x, y, test_size=0.1)

    linear = linear_model.LinearRegression()

    linear.fit(x_train, y_train)
    acc = linear.score(x_test, y_test)
    print("Accuracy: " + str(acc))

    if acc > best:
        best = acc
        with open("studentgrades.pkl", "wb") as f:
            pickle.dump(linear, f)"""
# LOAD MODEL
pickle_in = open("studentgrades.pickle", "rb")
linear = pickle.load(pickle_in)

请有人帮助我,并在此先感谢。

【问题讨论】:

  • 添加完整的错误回溯。
  • 我在命令行中添加了一张显示完整错误日志的图片

标签: python numpy machine-learning flask


【解决方案1】:

听起来像是训练集和预测集之间的数据类型不匹配。您可能需要在输入上显式设置数据类型。需要按列完成。例如

df['G1'].astype('int')

使用 df.dtypes 检查预期的列类型。

【讨论】:

    【解决方案2】:

    也许问题在于您的列是字符串而不是数字:

    In [1]: a = np.zeros(9, np.dtype('<U32')).reshape((3,3))                                                                                 
    
    In [2]: b = np.zeros(9, np.dtype('<U32')).reshape((3,3))                                                                                 
    
    In [3]: a                                                                                                                                
    Out[3]: 
    array([['', '', ''],
           ['', '', ''],
           ['', '', '']], dtype='<U32')
    
    In [4]: np.matmul(a,b)                                                                                                                   
    ---------------------------------------------------------------------------
    UFuncTypeError                            Traceback (most recent call last)
    <ipython-input-4-f6001c33e8b2> in <module>
    ----> 1 np.matmul(a,b)
    
    UFuncTypeError: ufunc 'matmul' did not contain a loop with signature matching types (dtype('<U32'), dtype('<U32')) -> dtype('<U32')
    

    【讨论】:

    • 嘿。对不起,我前几天错过了这个问题。我想你一定已经解决了它,但如果你还没有,你需要做的是检查所有输入的 dtypes,包括你从 pickle 文件中读取的参数。至少其中一些会变成字符串。如果是字符串,则必须使用 astype 方法更改 dtype。诸如x = np.array(data.drop([predict], 1)).astype('int') 之类的东西。您可以扩展您的问题,显示您的输入,我们可以看到。
    猜你喜欢
    • 1970-01-01
    • 2016-10-27
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 2019-10-27
    • 1970-01-01
    • 2020-03-01
    • 1970-01-01
    相关资源
    最近更新 更多