gpt4 book ai didi

Python REST API 在 Docker 容器中无法正常工作

转载 作者:行者123 更新时间:2023-12-01 09:08:34 24 4
gpt4 key购买 nike

我使用 python 和 Flask 创建了一个简单的 ML API。它从sample.csv获取数据并基于该数据训练逻辑回归模型。我还有一个“/predict”端点,我可以在其中输入参数以供模型预测。

示例 localhost:80/predict?weight1=1.2&weight2=0.00123&&weight3=0.45 将输出 { "predicted": 1}

ma​​in.py:

from sklearn.linear_model import LogisticRegression
from flask import Flask, request
import numpy as np

# Create Flask object to run
app = Flask(__name__)

@app.route('/')
def home():
return "Predicting status from other features"


@app.route('/predict')
def predict():
# Get values from the server
weight1 = request.args['weight1']
weight2 = request.args['weight2']
weight3 = request.args['weight3']

testData = np.array([weight1, weight2, weight3]).reshape(1, -1)

class_predicted = logisticRegr.predict(testData.astype(float))

output = "{ \"predicted\": " + "\"" + class_predicted[0] + "\"" + "}"

return output


# Train and load the model based on the MetroPCS_Sample
def load_model():
global logisticRegr
label_y = []
label_x = []

with open('sample.csv') as f:
lines = f.readlines()
for line in lines[1:]:
# Adding labels to label_y
label_y.append(int(line[0]))
line = line.strip().split(",")
x_data = []
for e in line[1:]:
# Adding other features to label_x
x_data.append(float(e))
label_x.append(x_data)


train_x = label_x[:700]
train_y = label_y[:700]

test_x = label_x[700:1000]
test_y = label_y[700:1000]

logisticRegr = LogisticRegression()


logisticRegr.fit(train_x, train_y)

predictions = logisticRegr.predict(test_x)

score = logisticRegr.score(test_x, test_y)
# print score

if __name__ == "__main__":
print("Starting Server...")

# Call function that loads Model
load_model()

# Run Server
app.run(host="127.0.0.1", debug=True, port=80)

当我在没有容器的情况下运行此脚本时,一切正常。

但是,当我将其放入容器并运行时,出现以下错误:

NameError:全局名称“logisticRegr”未定义

Dockerfile

FROM tiangolo/uwsgi-nginx-flask:python2.7

# copy over our requirements.txt file
COPY requirements.txt /tmp/

# upgrade pip and install required python packages
RUN pip install -U pip
RUN pip install -r /tmp/requirements.txt

COPY ./app /app

ENV MESSAGE "hello"

需求.txt

Flask
numpy
sklearn
scipy

您知道当脚本位于容器内时什么会导致 NameError 吗?

最佳答案

在您的def load_model()中。你有global LogisticsRegr。仅使用 global 关键字不会使您的变量成为全局变量。

当您想要访问和更改函数内的全局变量时,可以使用全局变量。由于您的 logisticRegr 不是全局的,

当您尝试在 def Predict() 中访问它时,

class_predicted = LogisticRegr.predict(testData.astype(float)) 你会得到NameError: global name 'logisticRegr' is not Defined

现在来解决您的问题。在初始化 app 变量后初始化/声明您的 logisticRegr 模型变量,如下所示:

# Create Flask object to run
app = Flask(__name__)
logisticRegr = LogisticRegression()

然后在 test_y = label_y[700:1000]

之后从 load_model 中删除变量初始化

PS:建议将全局变量大写。以便在代码中轻松识别它们。

关于Python REST API 在 Docker 容器中无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51847184/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com