张量流概率-MCMC样本链-类型错误:张量不可破解-Mac M1



我正在尝试运行tensorflow文档中的示例。然而,我得到以下错误:

TypeError: Tensor is unhashable. Instead, use tensor.ref() as the key.

我在下面添加了

  • 回溯
  • conda list的输出
  • conda info的输出

回溯

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/var/folders/hy/57_f4xcx08b0ls2_nwwfjscr0000gn/T/ipykernel_19414/3526934965.py in <module>
6 
7 # Get 1000 states from one chain.
----> 8 states = tfp.mcmc.sample_chain(
9     num_burnin_steps=200,
10     num_results=1000,
~/miniforge3/envs/tf_env/lib/python3.8/site-packages/tensorflow_probability/python/mcmc/sample.py in sample_chain(num_results, current_state, previous_kernel_results, kernel, num_burnin_steps, num_steps_between_results, trace_fn, return_final_kernel_results, parallel_iterations, name)
324         current_state)
325     if previous_kernel_results is None:
--> 326       previous_kernel_results = kernel.bootstrap_results(current_state)
327 
328     if trace_fn is None:
~/miniforge3/envs/tf_env/lib/python3.8/site-packages/tensorflow_probability/python/mcmc/hmc.py in bootstrap_results(self, init_state)
558   def bootstrap_results(self, init_state):
559     """Creates initial `previous_kernel_results` using a supplied `state`."""
--> 560     kernel_results = self._impl.bootstrap_results(init_state)
561     if self.step_size_update_fn is not None:
562       step_size_assign = self.step_size_update_fn(self.step_size, None)  # pylint: disable=not-callable
~/miniforge3/envs/tf_env/lib/python3.8/site-packages/tensorflow_probability/python/mcmc/metropolis_hastings.py in bootstrap_results(self, init_state)
263         name=mcmc_util.make_name(self.name, 'mh', 'bootstrap_results'),
264         values=[init_state]):
--> 265       pkr = self.inner_kernel.bootstrap_results(init_state)
266       if not has_target_log_prob(pkr):
267         raise ValueError(
~/miniforge3/envs/tf_env/lib/python3.8/site-packages/tensorflow_probability/python/mcmc/hmc.py in bootstrap_results(self, init_state)
770           init_target_log_prob,
771           init_grads_target_log_prob,
--> 772       ] = mcmc_util.maybe_call_fn_and_grads(self.target_log_prob_fn, init_state)
773       if self._store_parameters_in_results:
774         return UncalibratedHamiltonianMonteCarloKernelResults(
~/miniforge3/envs/tf_env/lib/python3.8/site-packages/tensorflow_probability/python/mcmc/internal/util.py in maybe_call_fn_and_grads(fn, fn_arg_list, result, grads, check_non_none_grads, name)
231     fn_arg_list = (list(fn_arg_list) if is_list_like(fn_arg_list)
232                    else [fn_arg_list])
--> 233     result, grads = _value_and_gradients(fn, fn_arg_list, result, grads)
234     if not all(r.dtype.is_floating
235                for r in (result if is_list_like(result) else [result])):  # pylint: disable=superfluous-parens
~/miniforge3/envs/tf_env/lib/python3.8/site-packages/tensorflow_probability/python/mcmc/internal/util.py in _value_and_gradients(fn, fn_arg_list, result, grads, name)
190 
191     if result is None:
--> 192       result = fn(*fn_arg_list)
193       if grads is None and tf.executing_eagerly():
194         # Ensure we disable bijector cacheing in eager mode.
~/miniforge3/envs/tf_env/lib/python3.8/site-packages/tensorflow_probability/python/distributions/distribution.py in log_prob(self, value, name, **kwargs)
864         values of type `self.dtype`.
865     """
--> 866     return self._call_log_prob(value, name, **kwargs)
867 
868   def _call_prob(self, value, name, **kwargs):
~/miniforge3/envs/tf_env/lib/python3.8/site-packages/tensorflow_probability/python/distributions/distribution.py in _call_log_prob(self, value, name, **kwargs)
846           value, name="value", dtype_hint=self.dtype)
847       if hasattr(self, "_log_prob"):
--> 848         return self._log_prob(value, **kwargs)
849       if hasattr(self, "_prob"):
850         return tf.math.log(self._prob(value, **kwargs))
~/miniforge3/envs/tf_env/lib/python3.8/site-packages/tensorflow_probability/python/internal/distribution_util.py in _fn(*args, **kwargs)
2092     @functools.wraps(fn)
2093     def _fn(*args, **kwargs):
-> 2094       return fn(*args, **kwargs)
2095 
2096     if _fn.__doc__ is None:
~/miniforge3/envs/tf_env/lib/python3.8/site-packages/tensorflow_probability/python/distributions/mvn_linear_operator.py in _log_prob(self, x)
208   @distribution_util.AppendDocstring(_mvn_sample_note)
209   def _log_prob(self, x):
--> 210     return super(MultivariateNormalLinearOperator, self)._log_prob(x)
211 
212   @distribution_util.AppendDocstring(_mvn_sample_note)
~/miniforge3/envs/tf_env/lib/python3.8/site-packages/tensorflow_probability/python/distributions/transformed_distribution.py in _log_prob(self, y, **kwargs)
399     # For caching to work, it is imperative that the bijector is the first to
400     # modify the input.
--> 401     x = self.bijector.inverse(y, **bijector_kwargs)
402     event_ndims = self._maybe_get_static_event_ndims()
403 
~/miniforge3/envs/tf_env/lib/python3.8/site-packages/tensorflow_probability/python/bijectors/bijector.py in inverse(self, y, name, **kwargs)
975       NotImplementedError: if `_inverse` is not implemented.
976     """
--> 977     return self._call_inverse(y, name, **kwargs)
978 
979   def _compute_inverse_log_det_jacobian_with_caching(
~/miniforge3/envs/tf_env/lib/python3.8/site-packages/tensorflow_probability/python/bijectors/bijector.py in _call_inverse(self, y, name, **kwargs)
944       if not self._is_injective:  # No caching for non-injective
945         return self._inverse(y, **kwargs)
--> 946       mapping = self._lookup(y=y, kwargs=kwargs)
947       if mapping.x is not None:
948         return mapping.x
~/miniforge3/envs/tf_env/lib/python3.8/site-packages/tensorflow_probability/python/bijectors/bijector.py in _lookup(self, x, y, kwargs)
1344     if y is not None:
1345       # We removed y at caching time. Add it back if we lookup successfully.
-> 1346       mapping = self._from_y[y].get(subkey, mapping).merge(y=y)
1347     return mapping
1348 
~/miniforge3/envs/tf_env/lib/python3.8/site-packages/tensorflow_probability/python/bijectors/bijector.py in __getitem__(self, key)
149   def __getitem__(self, key):
150     weak_key = HashableWeakRef(key, lambda w: self.pop(w, None))
--> 151     return super(WeakKeyDefaultDict, self).__getitem__(weak_key)
152 
153   # This is the "DefaultDict" part.
~/miniforge3/envs/tf_env/lib/python3.8/site-packages/tensorflow_probability/python/bijectors/bijector.py in __hash__(self)
179     x = self()
180     if not isinstance(x, np.ndarray):
--> 181       return hash(x)
182     # Note: The following logic can never be reached by the public API because
183     # the bijector base class always calls `convert_to_tensor` before accessing
~/miniforge3/envs/tf_env/lib/python3.8/site-packages/tensorflow/python/framework/ops.py in __hash__(self)
828     if (Tensor._USE_EQUALITY and executing_eagerly_outside_functions() and
829         (g is None or g.building_function)):
--> 830       raise TypeError("Tensor is unhashable. "
831                       "Instead, use tensor.ref() as the key.")
832     else:
TypeError: Tensor is unhashable. Instead, use tensor.ref() as the key.

conda列表

# packages in environment at /Users/maurocamara/miniforge3/envs/tf_env:
#
# Name                    Version                   Build  Channel
absl-py                   0.13.0             pyhd8ed1ab_0    conda-forge
aiohttp                   3.7.4.post0      py38hea4295b_0    conda-forge
anyio                     3.2.1            py38h10201cd_0    conda-forge
appnope                   0.1.2            py38h10201cd_1    conda-forge
argon2-cffi               20.1.0           py38hea4295b_2    conda-forge
astor                     0.8.1              pyh9f0ad1d_0    conda-forge
astunparse                1.6.3              pyhd8ed1ab_0    conda-forge
async-timeout             3.0.1                   py_1000    conda-forge
async_generator           1.10                       py_0    conda-forge
attrs                     21.2.0             pyhd8ed1ab_0    conda-forge
babel                     2.9.1              pyh44b312d_0    conda-forge
backcall                  0.2.0              pyh9f0ad1d_0    conda-forge
backports                 1.0                        py_2    conda-forge
backports.functools_lru_cache 1.6.4              pyhd8ed1ab_0    conda-forge
bleach                    3.3.1              pyhd8ed1ab_0    conda-forge
blinker                   1.4                        py_1    conda-forge
brotlipy                  0.7.0           py38hea4295b_1001    conda-forge
c-ares                    1.17.1               h27ca646_1    conda-forge
ca-certificates           2021.5.30            h4653dfc_0    conda-forge
cached-property           1.5.2                hd8ed1ab_1    conda-forge
cached_property           1.5.2              pyha770c72_1    conda-forge
cachetools                4.2.2              pyhd8ed1ab_0    conda-forge
certifi                   2021.5.30        py38h10201cd_0    conda-forge
cffi                      1.14.6           py38h0957451_0    conda-forge
chardet                   4.0.0            py38h10201cd_1    conda-forge
charset-normalizer        2.0.0              pyhd8ed1ab_0    conda-forge
click                     8.0.1            py38h10201cd_0    conda-forge
cloudpickle               1.6.0                      py_0    conda-forge
cryptography              3.4.7            py38h3c0dae5_0    conda-forge
cycler                    0.10.0                     py_2    conda-forge
dataclasses               0.8                pyhc8e2a94_1    conda-forge
debugpy                   1.3.0            py38h6f2b01f_0    conda-forge
decorator                 5.0.9              pyhd8ed1ab_0    conda-forge
defusedxml                0.7.1              pyhd8ed1ab_0    conda-forge
entrypoints               0.3             pyhd8ed1ab_1003    conda-forge
freetype                  2.10.4               h17b34a0_1    conda-forge
gast                      0.5.0              pyhd8ed1ab_0    conda-forge
google-auth               1.33.1             pyh6c4a22f_0    conda-forge
google-auth-oauthlib      0.4.1                      py_2    conda-forge
google-pasta              0.2.0              pyh8c360ce_0    conda-forge
grpcio                    1.38.1           py38h69ee544_0    conda-forge
h5py                      3.3.0           nompi_py38hb525b2d_100    conda-forge
hdf5                      1.10.6          nompi_h0fc092c_1114    conda-forge
idna                      3.1                pyhd3deb0d_0    conda-forge
importlib-metadata        4.6.1            py38h10201cd_0    conda-forge
ipykernel                 6.0.3            py38h2cb4d76_0    conda-forge
ipython                   7.25.0           py38h2cb4d76_1    conda-forge
ipython_genutils          0.2.0                      py_1    conda-forge
ipywidgets                7.6.3              pyhd3deb0d_0    conda-forge
jbig                      2.1               h3422bc3_2003    conda-forge
jedi                      0.18.0           py38h10201cd_2    conda-forge
jinja2                    3.0.1              pyhd8ed1ab_0    conda-forge
jpeg                      9d                   h27ca646_0    conda-forge
json5                     0.9.5              pyh9f0ad1d_0    conda-forge
jsonschema                3.2.0              pyhd8ed1ab_3    conda-forge
jupyter                   1.0.0            py38h10201cd_6    conda-forge
jupyter_client            6.1.7                      py_0    anaconda
jupyter_console           6.4.0              pyhd8ed1ab_0    conda-forge
jupyter_core              4.7.1            py38h10201cd_0    conda-forge
jupyter_server            1.9.0              pyhd8ed1ab_0    conda-forge
jupyterlab                3.0.16             pyhd8ed1ab_0    conda-forge
jupyterlab_pygments       0.1.2              pyh9f0ad1d_0    conda-forge
jupyterlab_server         2.6.1              pyhd8ed1ab_0    conda-forge
jupyterlab_widgets        1.0.0              pyhd8ed1ab_1    conda-forge
keras-preprocessing       1.1.2              pyhd8ed1ab_0    conda-forge
kiwisolver                1.3.1            py38h1670459_1    conda-forge
krb5                      1.19.1               hd92b7a7_0    conda-forge
lcms2                     2.12                 had6a04f_0    conda-forge
lerc                      2.2.1                h9f76cd9_0    conda-forge
libblas                   3.9.0                9_openblas    conda-forge
libcblas                  3.9.0                9_openblas    conda-forge
libcurl                   7.77.0               h8fe1914_0    conda-forge
libcxx                    12.0.1               h168391b_0    conda-forge
libdeflate                1.7                  h27ca646_5    conda-forge
libedit                   3.1.20191231         hc8eb9b7_2    conda-forge
libev                     4.33                 h642e427_1    conda-forge
libffi                    3.3                  h9f76cd9_2    conda-forge
libgfortran               5.0.0.dev0      11_0_1_hf114ba7_22    conda-forge
libgfortran5              11.0.1.dev0         hf114ba7_22    conda-forge
liblapack                 3.9.0                9_openblas    conda-forge
libnghttp2                1.43.0               hf3018f0_0    conda-forge
libopenblas               0.3.15          openmp_hf330de4_1    conda-forge
libpng                    1.6.37               hf7e6567_2    conda-forge
libprotobuf               3.17.2               hccf11d3_1    conda-forge
libsodium                 1.0.18               h27ca646_1    conda-forge
libssh2                   1.9.0                hb80f160_6    conda-forge
libtiff                   4.3.0                hc6122e1_1    conda-forge
libwebp-base              1.2.0                h27ca646_2    conda-forge
llvm-openmp               12.0.1               hf3c4609_0    conda-forge
lz4-c                     1.9.3                h9f76cd9_0    conda-forge
markdown                  3.3.4              pyhd8ed1ab_0    conda-forge
markupsafe                2.0.1            py38hea4295b_0    conda-forge
matplotlib                3.4.2            py38h150bfb4_0    conda-forge
matplotlib-base           3.4.2            py38hb140015_0    conda-forge
matplotlib-inline         0.1.2              pyhd8ed1ab_2    conda-forge
mistune                   0.8.4           py38hea4295b_1004    conda-forge
multidict                 5.1.0            py38hea4295b_1    conda-forge
nbclassic                 0.3.1              pyhd8ed1ab_1    conda-forge
nbclient                  0.5.3              pyhd8ed1ab_0    conda-forge
nbconvert                 6.1.0            py38h10201cd_0    conda-forge
nbformat                  5.1.3              pyhd8ed1ab_0    conda-forge
ncurses                   6.2                  h9aa5885_4    conda-forge
nest-asyncio              1.5.1              pyhd8ed1ab_0    conda-forge
notebook                  6.4.0              pyha770c72_0    conda-forge
numpy                     1.19.5           py38hbf7bb01_2    conda-forge
oauthlib                  3.1.1              pyhd8ed1ab_0    conda-forge
olefile                   0.46               pyh9f0ad1d_1    conda-forge
openjpeg                  2.4.0                h062765e_1    conda-forge
openssl                   1.1.1k               h27ca646_0    conda-forge
opt_einsum                3.3.0              pyhd8ed1ab_1    conda-forge
packaging                 21.0               pyhd8ed1ab_0    conda-forge
pandocfilters             1.4.2                      py_1    conda-forge
parso                     0.8.2              pyhd8ed1ab_0    conda-forge
pexpect                   4.8.0              pyh9f0ad1d_2    conda-forge
pickleshare               0.7.5                   py_1003    conda-forge
pillow                    8.3.1            py38h02acf36_0    conda-forge
pip                       20.2.4                     py_0    conda-forge
plotly                    5.1.0              pyhd8ed1ab_1    conda-forge
prometheus_client         0.11.0             pyhd8ed1ab_0    conda-forge
prompt-toolkit            3.0.19             pyha770c72_0    conda-forge
prompt_toolkit            3.0.19               hd8ed1ab_0    conda-forge
protobuf                  3.17.2           py38h6f2b01f_0    conda-forge
ptyprocess                0.7.0              pyhd3deb0d_0    conda-forge
pyasn1                    0.4.8                      py_0    conda-forge
pyasn1-modules            0.2.7                      py_0    conda-forge
pycparser                 2.20               pyh9f0ad1d_2    conda-forge
pygments                  2.9.0              pyhd8ed1ab_0    conda-forge
pyjwt                     2.1.0              pyhd8ed1ab_0    conda-forge
pyopenssl                 20.0.1             pyhd8ed1ab_0    conda-forge
pyparsing                 2.4.7              pyh9f0ad1d_0    conda-forge
pyrsistent                0.17.3           py38hea4295b_2    conda-forge
pysocks                   1.7.1            py38h10201cd_3    conda-forge
python                    3.8.10          hf9733c0_1_cpython    conda-forge
python-dateutil           2.8.1                      py_0    anaconda
python-flatbuffers        2.0                pyhd8ed1ab_0    conda-forge
python_abi                3.8                      2_cp38    conda-forge
pytz                      2021.1             pyhd8ed1ab_0    conda-forge
pyu2f                     0.1.5              pyhd8ed1ab_0    conda-forge
pyzmq                     22.1.0           py38h51b17a6_0    conda-forge
readline                  8.1                  hedafd6a_0    conda-forge
requests                  2.26.0             pyhd8ed1ab_0    conda-forge
requests-oauthlib         1.3.0              pyh9f0ad1d_0    conda-forge
requests-unixsocket       0.2.0                      py_0    conda-forge
rsa                       4.7.2              pyh44b312d_0    conda-forge
scipy                     1.7.0            py38hd0c9ec0_0    conda-forge
send2trash                1.7.1              pyhd8ed1ab_0    conda-forge
setuptools                49.6.0           py38h10201cd_3    conda-forge
six                       1.16.0             pyh6c4a22f_0    conda-forge
sniffio                   1.2.0            py38h10201cd_1    conda-forge
sqlite                    3.36.0               h72a2b83_0    conda-forge
tenacity                  8.0.1              pyhd8ed1ab_0    conda-forge
tensorboard               2.4.1              pyhd8ed1ab_0    conda-forge
tensorboard-plugin-wit    1.8.0              pyh44b312d_0    conda-forge
tensorflow                2.4.0rc0                 pypi_0    pypi
tensorflow-addons         0.11.2                   pypi_0    pypi
tensorflow-estimator      2.5.0              pyh81a9013_1    conda-forge
tensorflow-probability    0.7                        py_1    conda-forge
termcolor                 1.1.0                      py_2    conda-forge
terminado                 0.10.1           py38h10201cd_0    conda-forge
testpath                  0.5.0              pyhd8ed1ab_0    conda-forge
tk                        8.6.10               hf7e6567_1    conda-forge
tornado                   6.1              py38hea4295b_1    conda-forge
traitlets                 5.0.5                      py_0    conda-forge
typeguard                 2.12.1             pyhd8ed1ab_0    conda-forge
typing-extensions         3.10.0.0             hd8ed1ab_0    conda-forge
typing_extensions         3.10.0.0           pyha770c72_0    conda-forge
urllib3                   1.26.6             pyhd8ed1ab_0    conda-forge
wcwidth                   0.2.5              pyh9f0ad1d_2    conda-forge
webencodings              0.5.1                      py_1    conda-forge
websocket-client          0.57.0           py38h10201cd_4    conda-forge
werkzeug                  2.0.1              pyhd8ed1ab_0    conda-forge
wheel                     0.36.2             pyhd3deb0d_0    conda-forge
widgetsnbextension        3.5.1            py38h10201cd_4    conda-forge
wrapt                     1.12.1           py38hea4295b_3    conda-forge
xz                        5.2.5                h642e427_1    conda-forge
yarl                      1.6.3            py38hea4295b_2    conda-forge
zeromq                    4.3.4                h9f76cd9_0    conda-forge
zipp                      3.5.0              pyhd8ed1ab_0    conda-forge
zlib                      1.2.11            h31e879b_1009    conda-forge
zstd                      1.5.0                h861e0a7_0    conda-forge

conda信息

active environment : tf_env
active env location : /Users/maurocamara/miniforge3/envs/tf_env
shell level : 1
user config file : /Users/maurocamara/.condarc
populated config files : /Users/maurocamara/miniforge3/.condarc
/Users/maurocamara/.condarc
conda version : 4.10.3
conda-build version : not installed
python version : 3.9.6.final.0
virtual packages : __osx=11.2.3=0
__unix=0=0
__archspec=1=arm64
base environment : /Users/maurocamara/miniforge3  (writable)
conda av data dir : /Users/maurocamara/miniforge3/etc/conda
conda av metadata url : None
channel URLs : https://conda.anaconda.org/conda-forge/osx-arm64
https://conda.anaconda.org/conda-forge/noarch
package cache : /Users/maurocamara/miniforge3/pkgs
/Users/maurocamara/.conda/pkgs
envs directories : /Users/maurocamara/miniforge3/envs
/Users/maurocamara/.conda/envs
platform : osx-arm64
user-agent : conda/4.10.3 requests/2.26.0 CPython/3.9.6 Darwin/20.3.0 OSX/11.2.3
UID:GID : 501:20
netrc file : None
offline mode : False

当我尝试在conda环境中复制相同的代码时,这不会显示任何错误。

根据此已测试的内部版本配置,可能存在版本不兼容问题,因为回溯错误显示Python 3.8,但conda信息显示您在conda中安装了Python 3.9.6。请通过将TensorFlow升级到最新版本重试。

pip install --upgrade tensorflow

请在此处检查复制的代码:

!pip install tensorflow_probability
import tensorflow as tf
import tensorflow_probability as tfp
tfd = tfp.distributions
target = tfd.MultivariateNormalDiag(scale_diag=[1., 2.])
# Get 1000 states from one chain.
states = tfp.mcmc.sample_chain(
num_burnin_steps=200,
num_results=1000,
current_state=tf.constant([0., 0.]),
trace_fn=None,
kernel=tfp.mcmc.HamiltonianMonteCarlo(
target_log_prob_fn=target.log_prob,
step_size=0.05,
num_leapfrog_steps=20))
print(states.shape)
#==> (1000, 2)
ess = tfp.mcmc.effective_sample_size(states, filter_beyond_positive_pairs=True)
print(ess.shape)
#==> Shape (2,) Tensor
mean, variance = tf.nn.moments(states, axes=0)
standard_error = tf.sqrt(variance / ess)

输出:

(1000, 2)
(2,)

相关内容

  • 没有找到相关文章

最新更新