Как создать автономный исполняемый файл python с пакетом pymc3? - PullRequest
0 голосов
/ 20 сентября 2019

Я создал математическую модель в Python.Я хочу сделать автономный исполняемый файл Python для моей модели.Скрипт python использует несколько библиотек python, таких как numpy, pandas, pymc3.Я попытался сделать исполняемый файл python, используя pyinstaller, а также auto-py-to-exe.В обоих случаях не удалось создать исполняемый файл.Ошибка возникает при импорте модуля pymc3 (библиотека theano).Моя основная модель зависит от модуля pymc3.Я не могу обойти этот модуль.Может ли кто-нибудь помочь мне разобраться с этой проблемой?

Вот сообщение об ошибке, которое я получаю, когда запускаю файл .exe,

WARNING (theano.tensor.blas): Using NumPy C-API based implementation for BLAS functions.
c:\python\lib\site-packages\PyInstaller\loader\pyimod03_importers.py:621: MatplotlibDeprecationWarning:
The MATPLOTLIBDATA environment variable was deprecated in Matplotlib 3.1 and will be removed in 3.3.
  exec(bytecode, module.__dict__)
Traceback (most recent call last):
  File "sample.py", line 46, in <module>
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "c:\python\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 621, in exec_module
    exec(bytecode, module.__dict__)
  File "site-packages\pymc3\__init__.py", line 11, in <module>
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "c:\python\lib\site-packages\PyInstaller\loader\pyimod03_importers.py", line 621, in exec_module
    exec(bytecode, module.__dict__)
  File "site-packages\pymc3\stats.py", line 20, in <module>
  File "site-packages\pkg_resources\__init__.py", line 481, in get_distribution
  File "site-packages\pkg_resources\__init__.py", line 357, in get_provider
  File "site-packages\pkg_resources\__init__.py", line 900, in require
  File "site-packages\pkg_resources\__init__.py", line 786, in resolve
pkg_resources.DistributionNotFound: The 'scipy' distribution was not found and is required by the application
[13796] Failed to execute script sample

Вот скрипт python,

class modelFit:
    # Initialises the attributes
    def __init__(self, x, y):
        self.x = x
        self.y = y

    # Performs the Bayes estimation
    def coeffEstimation(self):
        X = np.array(self.x)
        Y = np.array(self.y)

        with pm.Model() as linearRegModel:
            # Define priors
            #regCoeff = pm.HalfNormal('regCoeff', sd = 20, shape=X.shape[1])
            regCoeff = pm.Uniform('regCoeff', lower = 0, upper = 100, shape=X.shape[1])

            # Standard deviation
            sigma = pm.HalfNormal('sigma', sd = 5)

            # Estimate of mean
            mean = pm.math.dot(X, regCoeff)

            # Likelihood estimate
            likelihood = pm.Normal('Y_estimated', mu = mean, sd = sigma, observed = Y)

            # Sampler
            step = pm.NUTS()

            # Posterior distribution
            linearTrace = pm.sample(draws = 500, chains = 1,
                                    tune = 500, nuts_kwargs=dict(target_accept=0.95))

        with open('Summary.txt', 'w') as f:
            print(pm.summary(linearTrace).round(3), file=f)
            diverging = linearTrace['diverging']
            print('Number of Divergent Chains: {}'.format(diverging.nonzero()[0].size), file=f)
            divergingPer = diverging.nonzero()[0].size / len(linearTrace) * 100
            print('Percentage of Divergent Chains: {:.1f}'.format(divergingPer), file=f)

        print('Bayesian Inference Done! Exporting the results, Please hold on!')
        return(linearTrace)


import theano.tensor.shared_randomstreams
import scipy
import pymc3 as pm
import numpy as np
import pandas as pd
dataLocation = './input/'
inputData = pd.read_excel(dataLocation + 'input.xlsx')
sizeInputData = inputData.shape
x = inputData.iloc[:,1:sizeInputData[1]]
y = inputData.iloc[:,0]


# Executes the Bayes method
linReg = modelFit(x, y)
regTrace = linReg.coeffEstimation()
...