繁体   English   中英

如何从一维列表创建一个二维 numpy 数组?

[英]How to create a 2d numpy array from 1d list?

我有这个列表features_to_scale我想将其更改为 2d NumPy 数组。 我确实将它转换为一维数组。 我问这个,以便我可以将它传递给缩放器,您可以在此代码下面的代码中看到它:

features_to_scale = [features[0], features[1], features[2], features[3], features[4], features[9], features[10]]
features_to_scale = np.array(features_to_scale)

这就是我上面讲的app.py。

import numpy as np
from flask import Flask, request, jsonify, render_template
import pickle

app = Flask(__name__)
model = pickle.load(open('model1.pkl','rb'))#loading the model
trans1 = pickle.load(open('transform1.pkl', 'rb'))#Loding the encoder
trans2 = pickle.load(open('transform2.pkl', 'rb'))#Loading the encoder
scale = pickle.load(open('scale.pkl', 'rb'))#Loading the scaler
@app.route('/')
def home():
    return render_template('index.html')#rendering the home page

@app.route('/predict',methods=['POST'])
def predict():
    '''
    For rendering results on HTML GUI
    '''
    features = [x for x in request.form.values()]
    print(features)
    features[11] = trans1.transform([features[11]])
    features[12] = trans2.transform([features[12]])
    features_to_scale = [features[0], features[1], features[2], features[3], features[4], features[9], features[10]]
    features_to_scale = np.array(features_to_scale)
    # scaled = scale.transform(features_to_scale)
    # for i in [0,1,2,3,4,9,10]:
    #     features[i] = scaled[i]

    final_features = [np.array(features, dtype=float)]
    # final_features = final_features[None, ...]
    prediction = model.predict(final_features)
    output = round(prediction[0], 2)
    # output = len(prediction)

    return render_template('index.html', prediction_text='Booked: {}'.format(output))


if __name__ == "__main__":
    app.run(debug=True

)

我想摆脱以下错误:

ValueError: Expected 2D array, got 1D array instead:
array=[4.5000e+01 1.4000e+01 4.1000e+01 1.4545e+04 1.2300e+02 1.4000e+01
4.0000e+00].
Reshape your data either using array.reshape(-1, 1) if your data has a single feature or array.reshape(1, -1) if it contains a single sample.

看起来您正在尝试对单个样本进行转换。

在这种情况下,您获得的回溯建议使用.reshape(1, -1)重塑数据

所以在你的代码中你应该改变

features_to_scale = np.array(features_to_scale)

features_to_scale = np.array(features_to_scale).reshape(1, -1)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM