如何在flask python中进行预测后将值转换为csv



我目前正在做我自己的项目,我非常需要一些关于这个问题的帮助,因为这个问题已经困扰了我很长一段时间,因此我在这里真诚地请指导我并分享一些关于这个问题的技巧。提前谢谢,谢谢。

AttributeError:"numpy。数组对象没有StringIO属性

from flask import Flask, make_response, request, render_template
import io
from io import StringIO
import csv
import pandas as pd
import numpy as np
import pickle
import os
from keras.models import load_model
from sklearn.preprocessing import MinMaxScaler
from statsmodels.tsa.arima_model import ARIMAResults

app = Flask(__name__)


@app.route('/')
def form():
return """
<html>
<body>
<h1>Let's TRY to Predict..</h1>
</br>
</br>
<p> Insert your CSV file and then download the Result
<form action="/transform" method="post" enctype="multipart/form-data">
<input type="file" name="data_file" class="btn btn-block"/>
</br>
</br>
<button type="submit" class="btn btn-primary btn-block btn-large">Predict</button>
</form>
</body>
</html>
"""
@app.route('/transform', methods=["POST"])
def transform_view():
if request.method == 'POST':
f = request.files['data_file']
if not f:
return "No file"

stream = io.StringIO(f.stream.read().decode("UTF8"), newline=None)
csv_input = csv.reader(stream)
#print("file contents: ", file_contents)
#print(type(file_contents))
print(csv_input)
for row in csv_input:
print(row)
stream.seek(0)
result = stream.read()
df = pd.read_csv(StringIO(result), usecols=[1])
# load the model from disk
model = load_model('model.h5')
dataset = df.values
dataset = dataset.astype('float32')

scaler = MinMaxScaler(feature_range=(-1, 1))
dataset = scaler.fit_transform(dataset)
dataset = np.reshape(dataset, (dataset.shape[0], 1, dataset.shape[1]))
df = model.predict(dataset)
excel_file = df.StringIO()
df.to_csv(execel_file, encoding='utf-8')
csv_output = execel_file.getvalue()

response = make_response(trans.to_csv())
response.headers["Content-Disposition"] = "attachment; filename=result.csv"
return response

if __name__ == "__main__":
app.run(debug=True, port = 9000, host = "localhost")

为了保存您的预测,您可以首先将df转换为实际的dataframe。例如

predict_res = model.predict(dataset)
df_predict = pd.DataFrame(predict_res, columns=["predict"])
df_predict.to_csv("predict.csv", index=False, header=False, encoding='utf8')

相关内容

  • 没有找到相关文章

最新更新