Issue
I'm trying to run a python
script that is used as an example on this data science site:
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()
I'm using Spyder. The errors that I am getting include:
%matplotlib inline
^
SyntaxError: invalid syntax
as well as
mle = possible_theta_values[np.argmax(likelihoods)]
TypeError: 'map' object is not subscriptable
and
likelihoods = list(map(lambda theta: likelihood(theta, ctr, x)\
NameError: name 'x' is not defined
I tried a solution that I found here: 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))
But it gave the error
TypeError: object of type 'map' has no len()
How can I fix the script to run in Spyder please?
Solution
Minor modifications in the code to make it work. I had to convert your map
iterable objects to lists to make your code work for the reasons you mentioned : TypeError: 'map' object is not subscriptable
. I also had to define explicitly the x
array to be able to use it while calculating 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))
Answered By - Sheldore
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.