Как использовать модель scikit-learn в структурированном запросе? - PullRequest
1 голос
/ 20 ноября 2019

Я пытаюсь применить модель scikit, полученную с помощью рассола, к каждой строке структурированного потокового фрейма данных.

Я пытался использовать pandas_udf (код версии 1), и он выдает мне эту ошибку:

AttributeError: 'numpy.ndarray' object has no attribute 'isnull'

Код:

inputPath = "/FileStore/df_training/streaming_df_1_nh_nd/"
from pyspark.sql import functions as f
from pyspark.sql.types import *

data_schema = data_spark_ts.schema

import pandas as pd

from pyspark.sql.functions import col, pandas_udf, PandasUDFType   # User Defines Functions for Pandas Dataframe
from pyspark.sql.types import LongType

get_prediction = pandas_udf(lambda x: gb2.predict(x), IntegerType())


streamingInputDF = (
  spark
    .readStream                       
    .schema(data_schema)               # Set the schema of the JSON data
    .option("maxFilesPerTrigger", 1)  # Treat a sequence of files as a stream by picking one file at a time
    .csv(inputPath)
    .fillna(0)
    .withColumn("prediction", get_prediction( f.struct([col(x) for x in data_spark.columns]) ))
)

display(streamingInputDF.select("prediction"))

Я пробовал такжеиспользуя обычный udf вместо pandas_udf, и это дает мне такую ​​ошибку:

ValueError: Expected 2D array, got 1D array instead:
[.. ... .. ..]
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.

Я не знаю, как изменить свои данные.

Модель, которую я пытаюсь применить, извлекается следующим образом:

#load the pickle
import pickle
gb2 = None

with open('pickle_modello_unico.p', 'rb') as fp:
  gb2 = pickle.load(fp)

И вот эта спецификация:

GradientBoostingClassifier(criterion='friedman_mse', init=None,
              learning_rate=0.1, loss='deviance', max_depth=3,
              max_features=None, max_leaf_nodes=None,
              min_impurity_decrease=0.0, min_impurity_split=None,
              min_samples_leaf=1, min_samples_split=2,
              min_weight_fraction_leaf=0.0, n_estimators=300,
              n_iter_no_change=None, presort='auto', random_state=None,
              subsample=1.0, tol=0.0001, validation_fraction=0.1,
              verbose=0, warm_start=False)

Любая помощь, чтобы решить эту проблему?

1 Ответ

0 голосов
/ 21 ноября 2019

Я решил проблему с возвратом pd.Series из pandas_udf.

Вот рабочий код:

inputPath = "/FileStore/df_training/streaming_df_1_nh_nd/"
from pyspark.sql import functions as f
from pyspark.sql.types import *

data_schema = data_spark_ts.schema

import pandas as pd

from pyspark.sql.functions import col, pandas_udf, PandasUDFType   # User Defines Functions for Pandas Dataframe
from pyspark.sql.types import LongType

get_prediction = pandas_udf(lambda x: pd.Series(gb2.predict(x)), StringType())


streamingInputDF = (
  spark
    .readStream                       
    .schema(data_schema)               # Set the schema of the JSON data
    .option("maxFilesPerTrigger", 1)  # Treat a sequence of files as a stream by picking one file at a time
    .csv(inputPath)
    .withColumn("prediction", get_prediction( f.struct([col(x) for x in data_spark.columns]) ))
)

display(streamingInputDF.select("prediction"))
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...