0

I'm getting the error

TypeError: MinMaxScaler(copy=True, feature_range=(0, 1)) is not JSON serializable

I've googled it but no results relating to the error. I must be the first in history to get it

I'm trying to scale the data from an ad campaign results and plot it on a plotly scatter graph.

I can plot before I scale but not after

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
#from IPython.display import display
from mpl_toolkits.mplot3d import Axes3D
%matplotlib inline
import mpld3
mpld3.enable_notebook()

pd.get_option("display.max_columns")
data = pd.read_csv("12776828-Ad-Sets-Lifetime.csv", header=0)
data = data[["Reporting starts","Results","Reach","Frequency","Cost per results","Amount spent (GBP)","Clicks (all)","CTR (all)","CPC (all) (GBP)","CPM (cost per 1,000 impressions) (GBP)","Link clicks","CPC (cost per link click) (GBP)","CTR (link click-through rate)","Website purchases","Button clicks"]]
filldate = pd.date_range('04-21-2017', '06-05-2017')
data = data.fillna(value=0)

pur0 = pur.reshape(1,-1)
lc0 = lc.reshape(1,-1)
spent0 = spent.reshape(1,-1)

from sklearn import preprocessing, svm
pur1 = preprocessing.StandardScaler().fit_transform(pur0)
lc1 = preprocessing.StandardScaler().fit_transform(lc0)
spent1 = preprocessing.StandardScaler().fit_transform(spent0)

import plotly #load plotly for plotting
import plotly.plotly as py
from plotly import tools
from plotly.graph_objs import * #all the types of plots that we will plot here
plotly.offline.init_notebook_mode() # run at the start of every ipython notebook


# Create a trace
Purch = Scatter(
    y = pur1,
    name="Purchases",
    mode='markers',
    marker=dict(
        size=12,
        color="green"
    )
)
Clicks = Scatter(
    #x = pur,
    x = lc1,
    name="Links Clicked",
    mode='markers',
    marker=dict(
        size=12,
        color="red"
    )
)

Spend = Scatter(
    #x = pur,
    x = spent1,
    name="Spent",
    mode='markers',
    marker=dict(
        size=12,
        color="blue"
    )
)


data = [Spend, Purch]

# Plot and embed in ipython notebook!
plotly.offline.iplot(data, filename='basic-scatter')

Returns the error

--------------------------------------------------------------------------- TypeError                                 Traceback (most recent call last) <ipython-input-41-c34375d51cd8> in <module>()
     42 
     43 # Plot and embed in ipython notebook!
---> 44 plotly.offline.iplot(data, filename='basic-scatter')

C:\Users\nickd\Anaconda3\lib\site-packages\plotly\offline\offline.py in iplot(figure_or_data, show_link, link_text, validate, image, filename, image_width, image_height, config)
    340 
    341     plot_html, plotdivid, width, height = _plot_html(
--> 342         figure_or_data, config, validate, '100%', 525, True
    343     )
    344 

C:\Users\nickd\Anaconda3\lib\site-packages\plotly\offline\offline.py in _plot_html(figure_or_data, config, validate, default_width, default_height, global_requirejs)
    180 
    181     plotdivid = uuid.uuid4()
--> 182     jdata = _json.dumps(figure.get('data', []), cls=utils.PlotlyJSONEncoder)
    183     jlayout = _json.dumps(figure.get('layout', {}),
    184                           cls=utils.PlotlyJSONEncoder)

C:\Users\nickd\Anaconda3\lib\json\__init__.py in dumps(obj, skipkeys, ensure_ascii, check_circular, allow_nan, cls, indent, separators, default, sort_keys, **kw)
    235         check_circular=check_circular, allow_nan=allow_nan, indent=indent,
    236         separators=separators, default=default, sort_keys=sort_keys,
--> 237         **kw).encode(obj)
    238 
    239 

C:\Users\nickd\Anaconda3\lib\site-packages\plotly\utils.py in encode(self, o)
    134 
    135         # this will raise errors in a normal-expected way
--> 136         encoded_o = super(PlotlyJSONEncoder, self).encode(o)
    137 
    138         # now:

C:\Users\nickd\Anaconda3\lib\json\encoder.py in encode(self, o)
    196         # exceptions aren't as detailed.  The list call should be roughly
    197         # equivalent to the PySequence_Fast that ''.join() would do.
--> 198         chunks = self.iterencode(o, _one_shot=True)
    199         if not isinstance(chunks, (list, tuple)):
    200             chunks = list(chunks)

C:\Users\nickd\Anaconda3\lib\json\encoder.py in iterencode(self, o,
_one_shot)
    254                 self.key_separator, self.item_separator, self.sort_keys,
    255                 self.skipkeys, _one_shot)
--> 256         return _iterencode(o, 0)
    257 
    258 def _make_iterencode(markers, _default, _encoder, _indent, _floatstr,

C:\Users\nickd\Anaconda3\lib\site-packages\plotly\utils.py in default(self, obj)
    202             except NotEncodable:
    203                 pass
--> 204         return _json.JSONEncoder.default(self, obj)
    205 
    206     @staticmethod

C:\Users\nickd\Anaconda3\lib\json\encoder.py in default(self, o)
    177 
    178         """
--> 179         raise TypeError(repr(o) + " is not JSON serializable")
    180 
    181     def encode(self, o):

TypeError: MinMaxScaler(copy=True, feature_range=(0, 1)) is not JSON serializable
Nick Duddy
  • 910
  • 6
  • 20
  • 36
  • 1
    The error means that it's trying to covert one of your `MinMaxScalar` to json, I'm not sure you can pass it as `x` to `Scatter` but idk why it doesn't raise the error there... – Tadhg McDonald-Jensen Jun 15 '17 at 18:11
  • @TadhgMcDonald-Jensen thanks. I'll think I might need to look more at the plotly docs for an solution. – Nick Duddy Jun 15 '17 at 19:01
  • 1
    If I am right, you want to plot the scaled data. Then you should change `fit()` to `fit_transform()` like this: `pur1 = preprocessing.MinMaxScaler().fit_transform(pur0)`. `fit()` returns the MinMaxScaler object, not the scaled data. – Vivek Kumar Jun 19 '17 at 05:07
  • @VivekKumar that's definitely fixed the JSON error. But my plot is now plotting blank. I had to reshape the data (updated above) to remove an error I was getting about decrepit code. – Nick Duddy Jun 19 '17 at 12:56

0 Answers0