lifetimes icon indicating copy to clipboard operation
lifetimes copied to clipboard

Error when running plot_history_alive

Open jmwhit126 opened this issue 2 years ago • 3 comments

I ran this same code on the same data 2 months ago and it worked just fine. Today, I'm getting errors. First, the 'Date' field is now required to be string where it was not previously. This is an easy fix obviously. But when I do that, I get the plot, but I also get the following error:

ConversionError: Failed to convert value(s) to axis units: 'YYYY-mm-dd'

Basically it is having difficulty with the start date for the graph, the earliest date in the transactions for the id being plotted.

Code: from lifetimes.plotting import plot_history_alive

id = '[email protected]' days_since_birth = data[data.index==id]['T'].astype(int) id_trans = df[df['Customer_ID']==id] id_trans['Date'] = id_trans['Date'].astype(str) #had to add this line since previous successful run since Date is datetime64 plot_history_alive(bgf,days_since_birth,id_trans,'Date')

Error:

IndexError Traceback (most recent call last) File ~/anaconda3/lib/python3.10/site-packages/matplotlib/axis.py:1732, in Axis.convert_units(self, x) 1731 try: -> 1732 ret = self.converter.convert(x, self.units, self) 1733 except Exception as e:

File ~/anaconda3/lib/python3.10/site-packages/matplotlib/dates.py:1936, in _SwitchableDateConverter.convert(self, *args, **kwargs) 1935 def convert(self, *args, **kwargs): -> 1936 return self._get_converter().convert(*args, **kwargs)

File ~/anaconda3/lib/python3.10/site-packages/matplotlib/dates.py:1864, in DateConverter.convert(value, unit, axis) 1858 """ 1859 If value is not already a number or sequence of numbers, convert it 1860 with date2num. 1861 1862 The unit and axis arguments are not used. 1863 """ -> 1864 return date2num(value)

File ~/anaconda3/lib/python3.10/site-packages/matplotlib/dates.py:457, in date2num(d) 456 return d --> 457 tzi = getattr(d[0], 'tzinfo', None) 458 if tzi is not None: 459 # make datetime naive:

IndexError: too many indices for array: array is 0-dimensional, but 1 were indexed

The above exception was the direct cause of the following exception:

ConversionError Traceback (most recent call last) Cell In[128], line 7 5 id_trans = df[df['Customer_ID']==id] 6 id_trans['Date'] = id_trans['Date'].astype(str) ----> 7 plot_history_alive(bgf,days_since_birth,id_trans,'Date')

File ~/anaconda3/lib/python3.10/site-packages/lifetimes/plotting.py:384, in plot_history_alive(model, t, transactions, datetime_col, freq, start_date, ax, **kwargs) 382 plt.ylim(0, 1.0) 383 plt.yticks(np.arange(0, 1.1, 0.1)) --> 384 plt.xlim(start_date, path_dates[-1]) 385 plt.legend(loc=3) 386 plt.ylabel("P_alive")

File ~/anaconda3/lib/python3.10/site-packages/matplotlib/pyplot.py:1794, in xlim(*args, **kwargs) 1792 if not args and not kwargs: 1793 return ax.get_xlim() -> 1794 ret = ax.set_xlim(*args, **kwargs) 1795 return ret

File ~/anaconda3/lib/python3.10/site-packages/matplotlib/_api/deprecation.py:454, in make_keyword_only..wrapper(*args, **kwargs) 448 if len(args) > name_idx: 449 warn_deprecated( 450 since, message="Passing the %(name)s %(obj_type)s " 451 "positionally is deprecated since Matplotlib %(since)s; the " 452 "parameter will become keyword-only %(removal)s.", 453 name=name, obj_type=f"parameter of {func.name}()") --> 454 return func(*args, **kwargs)

File ~/anaconda3/lib/python3.10/site-packages/matplotlib/axes/_base.py:3650, in _AxesBase.set_xlim(self, left, right, emit, auto, xmin, xmax) 3648 raise TypeError("Cannot pass both 'right' and 'xmax'") 3649 right = xmax -> 3650 return self.xaxis._set_lim(left, right, emit=emit, auto=auto)

File ~/anaconda3/lib/python3.10/site-packages/matplotlib/axis.py:1184, in Axis._set_lim(self, v0, v1, emit, auto) 1180 name, = [name for name, axis in self.axes._axis_map.items() 1181 if axis is self] # The axis name. 1183 self.axes._process_unit_info([(name, (v0, v1))], convert=False) -> 1184 v0 = self.axes._validate_converted_limits(v0, self.convert_units) 1185 v1 = self.axes._validate_converted_limits(v1, self.convert_units) 1187 if v0 is None or v1 is None: 1188 # Axes init calls set_xlim(0, 1) before get_xlim() can be called, 1189 # so only grab the limits if we really need them.

File ~/anaconda3/lib/python3.10/site-packages/matplotlib/axes/_base.py:3567, in _AxesBase._validate_converted_limits(self, limit, convert) 3557 """ 3558 Raise ValueError if converted limits are non-finite. 3559 (...) 3564 The limit value after call to convert(), or None if limit is None. 3565 """ 3566 if limit is not None: -> 3567 converted_limit = convert(limit) 3568 if (isinstance(converted_limit, Real) 3569 and not np.isfinite(converted_limit)): 3570 raise ValueError("Axis limits cannot be NaN or Inf")

File ~/anaconda3/lib/python3.10/site-packages/matplotlib/axis.py:1734, in Axis.convert_units(self, x) 1732 ret = self.converter.convert(x, self.units, self) 1733 except Exception as e: -> 1734 raise munits.ConversionError('Failed to convert value(s) to axis ' 1735 f'units: {x!r}') from e 1736 return ret

ConversionError: Failed to convert value(s) to axis units: '2022-10-25'

(plot)

jmwhit126 avatar Apr 17 '23 20:04 jmwhit126

Just ran into this error trying to follow along with the docs at https://lifetimes.readthedocs.io/en/latest/Quickstart.html#ranking-customers-from-best-to-worst, issue is repeatable with with sample dataset

dames-nxlink avatar Feb 21 '24 21:02 dames-nxlink

Hey @dames-nxlink,

These issues are likely due to API changes in matplotlib, but unfortunately development on lifetimes ceased some time ago. Here's the link to the successor library:

https://github.com/pymc-labs/pymc-marketing

I'm one of the contributors, and will be adding more plotting functionality next month. However, I've only ever used the plot_history_alive function for educational examples. Is there a specific, practical need for it in your use case? If so I'm very interested to hear more about it.

ColtAllen avatar Feb 21 '24 21:02 ColtAllen

@ColtAllen Thanks for the link to that new library! I've got no specific use case for that plot at the moment, just exploring more about ML in general and was trying to follow along with the examples in the docs. Checking out the successor now.

dames-nxlink avatar Feb 21 '24 21:02 dames-nxlink