簡體   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