我有使用测试数据的工作代码,如下所示:(示例数据匹配我以后将使用此脚本的输入类型和格式,包括日期作为附加‘Z’的字符串)
from sklearn import linear_model
import pandas as pd
import numpy as np
d = {'Start Sunday of FW': ['2022-03-02Z', '2022-03-03Z', '2022-03-04Z', '2022-03-05Z', '2022-03-06Z', '2022-03-01Z',
'2022-03-02Z', '2022-03-03Z', '2022-03-04Z', '2022-03-05Z', '2022-03-06Z', '2022-03-01Z'],
'Store': [1111, 1111, 1111, 1111, 1111, 1111, 2222, 2222, 2222, 2222, 2222, 2222],
'Sales': [3163, 4298, 2498, 4356, 4056, 3931, 3163, 4298, 2498, 4356, 4056, 1]}
df = pd.DataFrame(data=d)
def get_coef(input):
def model1(df):
y = df[['Sales']].values
x = df[['Start Sunday of FW']].values
return np.squeeze(linear_model.LinearRegression().fit(x,y).coef_)
cnames = {'Store': 'Store', 0: 'Coef'}
def prep_input(df):
df['Start Sunday of FW'] = df['Start Sunday of FW'].astype('string').str.rstrip('Z').astype('datetime64[ns]')
return df
return pd.DataFrame(prep_input(input).groupby('Store').apply(model1)).reset_index().rename(columns=cnames)
print(get_coef(df))这段代码本身运行良好。
但是,当我试图从Prep在下面的代码块中运行版本时,Prep流失败了,我得到了错误:
```2022-04-06,13:08:58 [ERROR] (base_handler.py:base_handler:115): Responding with status=500, message="Error processing script", info="TypeError : Object of type ndarray is not JSON serializable"```If I instead have it `print()` the current `return` line from `get_coef()`, return the `input` instead, and remove the `get_output_schema` function: the return is printed correctly, the output does flow to Tableau Prep in the live previews, **but** the error still raises and the flow still won't work, which is baffling.
```javascriptfrom sklearn import linear_modelimport pandas as pdimport numpy as npdef get_coef(input): def model1(df): y = df[['Sales']].values x = df[['Start Sunday of FW']].values return np.squeeze(linear_model.LinearRegression().fit(x,y).coef_) cnames = {'Store': 'Store', 0: 'Coef'} def prep_input(df): df['Start Sunday of FW'] = df['Start Sunday of FW'].astype('string').str.rstrip('Z').astype('datetime64[ns]') return df return pd.DataFrame(prep_input(input).groupby('Store').apply(model1)).reset_index().rename(columns=cnames)def get_output_schema(): return pd.DataFrame({ 'Store' : prep_string(), 'Coef' : prep_decimal() })有人能帮我理解这个问题吗?我一开始对JSON序列化一无所知,所以像这这样的帖子对我没有多大帮助;我甚至无法评估相关性。
发布于 2022-04-06 21:04:41
result = pd.DataFrame(prep_input(input).groupby('Store').apply(model1)).reset_index().rename(columns=cnames)
result['Coef'] = result['Coef'].astype('double')
return resultCoef是dtype对象,TabPy需要双倍。
https://stackoverflow.com/questions/71773107
复制相似问题