SystemError: initialization of beta_ufunc raised unreported exception

### Describe the bug

I have a 2D array of points and I want to cluster it. I have used the DBSCAN method. The main function is in C++ and the DBSCAN method is in Python. I have written an interface between both. The code is running fine but it gives a segmentation fault error when I run it to check memory leaks using Valgrind.

So I debugged the Python code and found that just the import call to DBSCAN is throwing the error.

My folder structure is as follows:
Test:
├── CMakeLists.txt
└── src
├── Py_Interface
│   ├── pyhelper.hpp
│   ├── Py_Integration.cpp
│   └── Py_Integration.h
├── PythonDep
│   └── Cluster.py
└── main.cpp

valgrind installation:

`sudo apt install valgrind`

I'm using Ubuntu 20.04.

### Steps/Code to Reproduce

CMakeLists.txt

```
cmake_minimum_required(VERSION 3.5 FATAL_ERROR)

project(Exec)
 
find_package(PythonLibs REQUIRED)

include_directories(
"src/Py_Interface")


include_directories(${PYTHON_INCLUDE_DIRS})

add_executable (Exec src/main.cpp src/Py_Interface/Py_Integration.cpp)
target_link_libraries (Exec ${PYTHON_LIBRARIES})
```

main.cpp

```
#include "Py_Interface/Py_Integration.h"

int main()
{
    Py_Wrapper();
}
```

Cluster.py
```
from sklearn.cluster import DBSCAN

def clustering():
    print("Clustering\n")
```

Py_Integration.h

```
#ifndef DL_INTEGRATION_H
#define DL_INTEGRATION_H

#include <Python.h>
#include "pyhelper.hpp"
#include <string>

PyObject *PythonInitialize(std::string script_name, std::string function_name);

void Py_Wrapper();

#endif // DL_INTEGRATION_H
```

Py_Integration.cpp

```
#include "Py_Integration.h"

using namespace std;

void Py_Wrapper()
{
    Py_InitializeEx(0); // Initialize the Python interpreter

    PyObject *PythonDetectorFunction, *PythonDetectorFunctionArguments;
    PythonDetectorFunction = PythonInitialize("Cluster", "clustering"); 

    if (PythonDetectorFunction == NULL)
        PyErr_Print();
    
    PyObject *PythonDetectorFeatureMaps = PyObject_CallObject(PythonDetectorFunction, PythonDetectorFunctionArguments);

    Py_XDECREF(PythonDetectorFunction);
    Py_XDECREF(PythonDetectorFunctionArguments);
    Py_XDECREF(PythonDetectorFeatureMaps);
}

PyObject *PythonInitialize(string script_name, string function_name)
{
    PyObject *pName, *pModule, *pFunc;
    PyRun_SimpleString("import sys, os");
    string PythonCodeImportStatement = "sys.path.append(os.getcwd() + '/../src/PythonDep/')"; // Relative path for the python code
    PyRun_SimpleString(PythonCodeImportStatement.c_str());

    // pNmae is the name of the python script/module to be called
    pName = PyUnicode_FromString(script_name.c_str());
    if (pName == NULL)
        PyErr_Print();

    // Getting the Python module reference inside of the C code
    pModule = PyImport_Import(pName);
    if (pModule == NULL)
        PyErr_Print();

    // Python function reference
    pFunc = PyObject_GetAttrString(pModule, function_name.c_str());
    if (pFunc == NULL)
        PyErr_Print();

    // Refrence count clean-up
    Py_XDECREF(pName);
    Py_XDECREF(pModule);

    return pFunc;
}
```

I have taken pyhelper.hpp from: https://github.com/beno54/Snake-integer/blob/master/pyhelper.hpp
I have posted the directory structure in the issue post above.

After building, the command to run the executable using valgrind:
`valgrind --leak-check=full --show-leak-kinds=all --track-origins=yes --verbose --log-file=valgrind-out.txt ./Exec` 

### Expected Results

No error is thrown.

### Actual Results

```
Traceback (most recent call last):
  File "/home/suraj/Projects/Scipy Error/build/../src/PythonDep/Cluster.py", line 1, in <module>
    from sklearn.cluster import DBSCAN
  File "/home/suraj/.local/lib/python3.8/site-packages/sklearn/__init__.py", line 83, in <module>
    from .base import clone
  File "/home/suraj/.local/lib/python3.8/site-packages/sklearn/base.py", line 19, in <module>
    from .utils import _IS_32BIT
  File "/home/suraj/.local/lib/python3.8/site-packages/sklearn/utils/__init__.py", line 22, in <module>
    from ._param_validation import Interval, validate_params
  File "/home/suraj/.local/lib/python3.8/site-packages/sklearn/utils/_param_validation.py", line 15, in <module>
    from .validation import _is_arraylike_not_scalar
  File "/home/suraj/.local/lib/python3.8/site-packages/sklearn/utils/validation.py", line 25, in <module>
    from ..utils._array_api import _asarray_with_order, _is_numpy_namespace, get_namespace
  File "/home/suraj/.local/lib/python3.8/site-packages/sklearn/utils/_array_api.py", line 9, in <module>
    from .fixes import parse_version
  File "/home/suraj/.local/lib/python3.8/site-packages/sklearn/utils/fixes.py", line 19, in <module>
    import scipy.stats
  File "/home/suraj/.local/lib/python3.8/site-packages/scipy/stats/__init__.py", line 485, in <module>
    from ._stats_py import *
  File "/home/suraj/.local/lib/python3.8/site-packages/scipy/stats/_stats_py.py", line 46, in <module>
    from . import distributions
  File "/home/suraj/.local/lib/python3.8/site-packages/scipy/stats/distributions.py", line 10, in <module>
    from . import _continuous_distns
  File "/home/suraj/.local/lib/python3.8/site-packages/scipy/stats/_continuous_distns.py", line 32, in <module>
    import scipy.stats._boost as _boost
  File "/home/suraj/.local/lib/python3.8/site-packages/scipy/stats/_boost/__init__.py", line 1, in <module>
    from scipy.stats._boost.beta_ufunc import (
SystemError: initialization of beta_ufunc raised unreported exception
Segmentation fault (core dumped)
```

### Versions

```shell
System:
    python: 3.8.10 (default, May 26 2023, 14:05:08)  [GCC 9.4.0]
executable: /usr/bin/python3
   machine: Linux-5.15.0-88-generic-x86_64-with-glibc2.29

Python dependencies:
      sklearn: 1.3.2
          pip: 20.0.2
   setuptools: 45.2.0
        numpy: 1.24.4
        scipy: 1.10.1
       Cython: 0.29.14
       pandas: 2.0.1
   matplotlib: 3.3.3
       joblib: 1.2.0
threadpoolctl: 3.2.0

Built with OpenMP: True

threadpoolctl info:
       user_api: openmp
   internal_api: openmp
    num_threads: 8
         prefix: libgomp
       filepath: /home/suraj/.local/lib/python3.8/site-packages/scikit_learn.libs/libgomp-a34b3233.so.1.0.0
        version: None

       user_api: blas
   internal_api: openblas
    num_threads: 8
         prefix: libopenblas
       filepath: /home/suraj/.local/lib/python3.8/site-packages/numpy.libs/libopenblas64_p-r0-15028c96.3.21.so
        version: 0.3.21
threading_layer: pthreads
   architecture: SkylakeX

       user_api: blas
   internal_api: openblas
    num_threads: 8
         prefix: libopenblas
       filepath: /usr/lib/x86_64-linux-gnu/openblas-pthread/libopenblasp-r0.3.8.so
        version: 0.3.8
threading_layer: pthreads
   architecture: Prescott
```

COMMENT:
Looking at the traceback, the import error is coming from SciPy:

```pytb
  File "/home/suraj/.local/lib/python3.8/site-packages/scipy/stats/__init__.py", line 485, in <module>
    from ._stats_py import *
  File "/home/suraj/.local/lib/python3.8/site-packages/scipy/stats/_stats_py.py", line 46, in <module>
    from . import distributions
  File "/home/suraj/.local/lib/python3.8/site-packages/scipy/stats/distributions.py", line 10, in <module>
    from . import _continuous_distns
  File "/home/suraj/.local/lib/python3.8/site-packages/scipy/stats/_continuous_distns.py", line 32, in <module>
    import scipy.stats._boost as _boost
  File "/home/suraj/.local/lib/python3.8/site-packages/scipy/stats/_boost/__init__.py", line 1, in <module>
    from scipy.stats._boost.beta_ufunc import (
SystemError: initialization of beta_ufunc raised unreported exception
Segmentation fault (core dumped)
```

So for sure, we can do anything regarding this part in scikit-learn. You might want to provide your finding upstream on the SciPy issue tracker.

Labels: Bug, Needs Triage