python - 概率分布模型
问题描述
我正在尝试运行python
在此数据科学网站上用作示例的脚本:
https ://www.datascience.com/blog/introduction-to-bayesian-inference-learn-data-science-tutorials
import numpy as np
from scipy.misc import factorial
import matplotlib.pyplot as plt
%matplotlib inline
plt.rcParams['figure.figsize'] = (16,7)
def likelihood(theta, n, x):
"""
likelihood function for a binomial distribution
n: [int] the number of experiments
x: [int] the number of successes
theta: [float] the proposed probability of success
"""
return (factorial(n) / (factorial(x) * factorial(n - x))) \
* (theta ** x) * ((1 - theta) ** (n - x))
# The number of impressions for our facebook-yellow-dress campaign
n_impressions = 10
# The number of clicks for our facebook-yellow-dress campaign
n_clicks = 7
# Observed click through rate
ctr = n_clicks / n_impressions
# 0 to 1, all possible click through rates
possible_theta_values = map(lambda x: x/100., range(100))
# Evaluate the likelihood function for possible click through rates
likelihoods = map(lambda theta: likelihood(theta, n, x)\
, possible_theta_values)
# Pick the best theta
mle = possible_theta_values[np.argmax(likelihoods)]
# Plot
f, ax = plt.subplots(1)
ax.plot(possible_theta_values, likelihoods)
ax.axvline(mle, linestyle = "--")
ax.set_xlabel("Theta")
ax.set_ylabel("Likelihood")
ax.grid()
ax.set_title("Likelihood of Theta for New Campaign")
plt.show()
我正在使用 Spyder。我得到的错误包括:
%matplotlib inline
^
SyntaxError: invalid syntax
也
mle = possible_theta_values[np.argmax(likelihoods)]
TypeError: 'map' object is not subscriptable
和
likelihoods = list(map(lambda theta: likelihood(theta, ctr, x)\
NameError: name 'x' is not defined
我尝试了一个在这里找到的解决方案: Python map object is not subscriptable
# Evaluate the likelihood function for possible click through rates
likelihoods = list(map(lambda theta: likelihood(theta, n_clicks, ctr)\
, possible_theta_values))
但它给出了错误
TypeError: object of type 'map' has no len()
请问如何修复脚本以在 Spyder 中运行?
解决方案
对代码进行少量修改以使其正常工作。map
由于您提到的原因,我不得不将您的可迭代对象转换为列表以使您的代码正常工作: TypeError: 'map' object is not subscriptable
。我还必须明确定义x
数组才能在计算时使用它likelihoods
。
# 0 to 1, all possible click through rates
possible_theta_values = list(map(lambda x: x/100., range(100)))
n = n_impressions
x = n_clicks
# Evaluate the likelihood function for possible click through rates
likelihoods = list(map(lambda theta: likelihood(theta, n, x)\
, possible_theta_values))
推荐阅读
- javascript - 在页面上以编程方式插入 React “root” dom
- python - 如何更改到一个甚至不存在的新目录?
- java - 检索帐户时出错 java.lang.IllegalStateException:没有当前的触碰付款帐户
- python - 对数据框中的值执行功能并替换
- javascript - Facebook 嵌入视频播放器 api 不在本地 html 文件中呈现 iframe 视频输出
- python - 如何让 Jupyter Notebook 内核在 Kubernetes 中抛出内存不足错误
- django - saveloan() 得到了一个意外的关键字参数“loanname”
- php - 如何在 symfony 中编辑上传的图像
- javascript - 在 sweetalert onOpen 函数中使用路由器推送 - Vue2
- security - 是后门类型的漏洞还是恶意软件?