简体   繁体   中英

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

I have this list features_to_scale I want to change it into a 2d NumPy array. I did convert it into a 1d array. I am asking this so that I can pass it into scaler which you can see in the code below this code:

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)

This is the app.py that I talked above.

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

)

I want to get rid of the following error:

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.

It looks like you're trying to make a transformation on a single sample.

The traceback you're getting suggests in this case to reshape the data using .reshape(1, -1)

So in your code you should change

features_to_scale = np.array(features_to_scale)

to

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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