ValueError: X has 500000 features, but ExtraTreeClassifier is expecting 7 features as input

ValueError: X has 500000 features, but ExtraTreeClassifier is expecting 7 features as input

我正在尝试为我使用 extratees 分类器实现的机器学习模型开发 UI。

下面的代码显示了我如何在训练后导出模型以在 UI 中使用。使用 is_attributed 列完成预测。

import numpy as np
import pandas as pd
from collections import Counter
import datetime
from sklearn.model_selection import train_test_split
from sklearn.model_selection import RepeatedStratifiedKFold
import gc

import warnings
warnings.simplefilter('ignore')

df = pd.read_csv('../cleaned_train.csv', index_col=0)

df['click_time'] = pd.to_datetime(df['click_time'])

df.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 10000000 entries, 0 to 9999999
Data columns (total 9 columns):
 #   Column         Dtype         
---  ------         -----         
 0   ip             int64         
 1   app            int64         
 2   device         int64         
 3   os             int64         
 4   channel        int64         
 5   click_time     datetime64[ns]
 6   is_attributed  int64         
 7   hour           int64         
 8   day            int64         
dtypes: datetime64[ns](1), int64(8)
memory usage: 762.9 MB

X= df.drop(columns=['is_attributed', 'click_time'])
y= df['is_attributed']

#Undersample data
from imblearn.under_sampling import RandomUnderSampler

rus = RandomUnderSampler() 
X_res, y_res = rus.fit_resample(X, y)

X_train, X_test, y_train, y_test = train_test_split(X_res, y_res, test_size = 0.33, 
random_state = 0)

from sklearn.ensemble import ExtraTreesClassifier
from sklearn.model_selection import GridSearchCV
import pickle

# ExtraTreesClassifier
ec = ExtraTreesClassifier(max_depth=None, n_estimators=50)
ec.fit(X_train, y_train)

y_predec=ec.predict(X_test)
pickle.dump(gsec,open('model.pkl','wb'))

当我尝试打印这个 print(gsec.predict(X_test)) 时,我得到的结果是 [1 1 0 ... 1 1 0]

当我尝试使用烧瓶开发 UI 时出现问题。我将模型导入 Flask 并尝试进行预测。下面是代码。

# importing necessary libraries and functions
import numpy as np
import pandas as pd
from flask import Flask, request, jsonify, render_template, make_response
from werkzeug.utils import secure_filename
from werkzeug.datastructures import  FileStorage
import pickle
import io
from io import StringIO
import csv

app = Flask(__name__) #Initialize the flask App

@app.route('/') # Homepage
def home():
return render_template('index.html')


@app.route('/predict',methods=['GET', 'POST'])
def predict():
'''
For rendering results on HTML GUI
'''

# retrieving values from form
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(csv_input)
for row in csv_input:
    print(row)

stream.seek(0)
result = stream.read()

df = pd.read_csv('newcleaned_test.csv')
attribute = df['is_attributed']
ip = df['ip']

print (attribute)

# load the model from disk
loaded_model = pickle.load(open('model.pkl', 'rb'))
prediction = loaded_model.predict([attribute])

print (prediction)
return 'prediction'



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

尝试运行上述代码时,

ValueError: X has 500000 features, but ExtraTreeClassifier is expecting 7 features as input.

显示在我的浏览器中。 (我正在使用的数据文件有 500000 个数据和 7 列)。为什么我使用一列训练模型时会抛出此错误?

你这里有几个误区。

首先,从代码中可以看出,模型是在 7 列上作为输入进行训练的 [ip, app, device, os, channel, hour, day]。并且该模型经过训练以预测 is_attributed 列中的值。因此,提供一个包含 7 个值的模型列表 -> 接收 1 个值作为输出。这个值似乎是 0 或 1 取决于输入 7 值。

其次,我们现在可以继续Flask部分。基本上,您在这里所做的是加载数据框和 select 一列 (attribute = df['is_attributed'])。如果您的数据框有 50000 行并且您 select 一列,则意味着您 select 50000 个值!然后您尝试将其发送到模型,该模型恰好需要 7 个值作为输入。 从我的角度来看,您似乎想要 运行 在 test 数据框的每一行上建模。

为此你需要:

  1. 加载test数据框;
  2. 检查数据框中是否只有 7 列 ([ip, app, device, os, channel, hour, day])。如果您有更多列,请删除所有其他列;
  3. 遍历数据框中的每一行(每行来自总共 50000);
  4. 运行 使用行中的 7 个值作为输入的模型;
  5. 模型的输出附加到 python 列表;
  6. 在 50000 运行 秒后,您将得到 python 包含 50000 个值的列表;
  7. return 这个列表。