MaartenGr / MaartenGr/BERTopic

ImportError: cannot import name 'import_array_module' from 'narwhals._pandas_like.utils'

Open
#2,426 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

bug
Dominant language
Python
Stars
7.8k
Forks
920
Avg merge
22h 24m
Merged PRs (30d)
5

Description

### Have you searched existing issues? 🔎

- [x] I have searched and found no existing issues

### Desribe the bug

coding:
fig1 = topic_model.visualize_topics()
fig1.write_html("output/visualize_topics.html")
report error:
---------------------------------------------------------------------------
ImportError Traceback (most recent call last)
Cell In[42], line 1
----> 1 fig1 = topic_model.visualize_topics()
2 fig1.write_html("output/visualize_topics.html")

File D:\workProgram\miniconda3\envs\net_work\lib\site-packages\bertopic\_bertopic.py:2442, in BERTopic.visualize_topics(self, topics, top_n_topics, use_ctfidf, custom_labels, title, width, height)
2409 """Visualize topics, their sizes, and their corresponding words.
2410
2411 This visualization is highly inspired by LDAvis, a great visualization
(...)
2439 ```
2440 """
2441 check_is_fitted(self)
-> 2442 return plotting.visualize_topics(
2443 self,
2444 topics=topics,
2445 top_n_topics=top_n_topics,
2446 use_ctfidf=use_ctfidf,
2447 custom_labels=custom_labels,
2448 title=title,
2449 width=width,
2450 height=height,
2451 )

File D:\workProgram\miniconda3\envs\net_work\lib\site-packages\bertopic\plotting\_topics.py:118, in visualize_topics(topic_model, topics, top_n_topics, use_ctfidf, custom_labels, title, width, height)
108 # Visualize with plotly
109 df = pd.DataFrame(
110 {
111 "x": embeddings[:, 0],
(...)
116 }
117 )
--> 118 return _plotly_topic_visualization(df, topic_list, title, width, height)

File D:\workProgram\miniconda3\envs\net_work\lib\site-packages\bertopic\plotting\_topics.py:142, in _plotly_topic_visualization(df, topic_list, title, width, height)
136 y_range = (
137 df.y.min() - abs((df.y.min()) * 0.15),
138 df.y.max() + abs((df.y.max()) * 0.15),
139 )
141 # Plot topics
--> 142 fig = px.scatter(
143 df,
144 x="x",
145 y="y",
146 size="Size",
147 size_max=40,
148 template="simple_white",
149 labels={"x": "", "y": ""},
150 hover_data={"Topic": True, "Words": True, "Size": True, "x": False, "y": False},
151 )
152 fig.update_traces(marker=dict(color="#B0BEC5", line=dict(width=2, color="DarkSlateGrey")))
154 # Update hover order

File D:\workProgram\miniconda3\envs\net_work\lib\site-packages\plotly\express\_chart_types.py:69, in scatter(data_frame, x, y, color, symbol, size, hover_name, hover_data, custom_data, text, facet_row, facet_col, facet_col_wrap, facet_row_spacing, facet_col_spacing, error_x, error_x_minus, error_y, error_y_minus, animation_frame, animation_group, category_orders, labels, orientation, color_discrete_sequence, color_discrete_map, color_continuous_scale, range_color, color_continuous_midpoint, symbol_sequence, symbol_map, opacity, size_max, marginal_x, marginal_y, trendline, trendline_options, trendline_color_override, trendline_scope, log_x, log_y, range_x, range_y, render_mode, title, subtitle, template, width, height)
62 """
63 In a scatter plot, each row of `data_frame` is represented by a symbol
64 mark in 2D space.
65 """
66 return make_figure(args=locals(), constructor=go.Scatter)
---> 69 scatter.__doc__ = make_docstring(scatter, append_dict=_cartesian_append_dict)
72 def density_contour(
73 data_frame=None,
74 x=None,
(...)
110 height=None,
111 ) -> go.Figure:
112 """
113 In a density contour plot, rows of `data_frame` are grouped together
114 into contour marks to visualize the 2D distribution of an aggregate
115 function `histfunc` (e.g. the count or sum) of the value `z`.
116 """

File D:\workProgram\miniconda3\envs\net_work\lib\site-packages\plotly\express\_core.py:2479, in make_figure(args, constructor, trace_patch, layout_patch)
2471 """
2472 Translates the spacing errors thrown by the underlying make_subplots
2473 routine into one that describes an argument adjustable through px.
2474 """
2475 if ("%s spacing" % (direction,)) in e.args[0]:
2476 e.args = (
2477 e.args[0]
2478 + """
-> 2479 Use the {facet_arg} argument to adjust this spacing.""".format(
2480 facet_arg=facet_arg
2481 ),
2482 )
2483 raise e

File D:\workProgram\miniconda3\envs\net_work\lib\site-packages\plotly\express\_core.py:1496, in build_dataframe(args, constructor)
1494 if df_provided:
1495 if isinstance(df_input.index, pd.MultiIndex):
-> 1496 raise TypeError(
1497 "Data frame index is a pandas MultiIndex. "
1498 "pandas MultiIndex is not supported by plotly express "
1499 "at the moment."
1500 )
1501 args["wide_cross"] = df_input.index
1502 else:

File D:\workProgram\miniconda3\envs\net_work\lib\site-packages\narwhals\stable\v1\__init__.py:1620, in from_native(native_object, strict, pass_through, eager_only, eager_or_interchange_only, series_only, allow_series)
1613 return native_object
1615 pass_through = validate_strict_and_pass_though(
1616 strict, pass_through, pass_through_default=False, emit_deprecation_warning=False
1617 )
1619 result = _from_native_impl(
-> 1620 native_object,
1621 pass_through=pass_through,
1622 eager_only=eager_only,
1623 eager_or_interchange_only=eager_or_interchange_only,
1624 series_only=series_only,
1625 allow_series=allow_series,
1626 version=Version.V1,
1627 )
1628 return _stableify(result)

File D:\workProgram\miniconda3\envs\net_work\lib\site-packages\narwhals\translate.py:492, in _from_native_impl(native_object, pass_through, eager_only, eager_or_interchange_only, series_only, allow_series, version)
490 # pandas
491 elif is_pandas_dataframe(native_object):
--> 492 from narwhals._pandas_like.dataframe import PandasLikeDataFrame
494 if series_only:
495 if not pass_through:

File D:\workProgram\miniconda3\envs\net_work\lib\site-packages\narwhals\_pandas_like\dataframe.py:11
9 from narwhals._compliant import EagerDataFrame
10 from narwhals._pandas_like.series import PANDAS_TO_NUMPY_DTYPE_MISSING, PandasLikeSeries
---> 11 from narwhals._pandas_like.utils import (
12 align_and_extract_native,
13 get_dtype_backend,
14 import_array_module,
15 iter_dtype_backends,
16 native_to_narwhals_dtype,
17 object_native_to_narwhals_dtype,
18 rename,
19 select_columns_by_name,
20 set_index,
21 )
22 from narwhals._typing_compat import assert_never
23 from narwhals._utils import (
24 Implementation,
25 _into_arrow_table,
(...)
32 zip_strict,
33 )

ImportError: cannot import name 'import_array_module' from 'narwhals._pandas_like.utils' (D:\workProgram\miniconda3\envs\net_work\lib\site-packages\narwhals\_pandas_like\utils.py)

### Reproduction

```python
from bertopic import BERTopic

```

### BERTopic Version

0.17.3

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start at bertopic/plotting/_topics.py, especially visualize_topics and _plotly_topic_visualization, then follow the traceback into narwhals._pandas_like.dataframe. Reproduce the failure with the supplied BERTopic snippet and inspect the installed dependency versions; done means visualize_topics completes without the reported ImportError.

Written by the indexing model from the issue text.

Assessment

Tech stack
plotly, python
Domain
data-visualization, machine-learning
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.