Pre*_*Ven 3 python statistics matplotlib scipy
我有这个代码:
\nimport numpy as np\nfrom scipy import stats\nfrom matplotlib import pyplot as plt\n\nif __name__ == "__main__":\n # Create a list of the number of coin tosses ("Bernoulli trials")\n number_of_trials = [0, 2, 10, 20, 50, 500]\n # Conduct 500 coin tosses and output into a list of 0s and 1s\n # where 0 represents a tail and 1 represents a head\n data = stats.bernoulli.rvs(0.5, size=number_of_trials[-1])\n # Discretise the x-axis into 100 separate plotting points\n x = np.linspace(0, 1, 100)\n # Loops over the number_of_trials list to continually add\n # more coin toss data. For each new set of data, we update\n # our (current) prior belief to be a new posterior. This is\n # carried out using what is known as the Beta-Binomial model.\n # For the time being, we won\xe2\x80\x99t worry about this too much.\n for i, N in enumerate(number_of_trials):\n # Accumulate the total number of heads for this\n # particular Bayesian update\n heads = data[:N].sum()\n # Create an axes subplot for each update\n ax = plt.subplot(len(number_of_trials) / 2, 2, i + 1)\n \n ax.set_title("%s trials, %s heads" % (N, heads))\n # Add labels to both axes and hide labels on y-axis\n plt.xlabel("$P(H)$, Probability of Heads")\n plt.ylabel("Density")\n if i == 0:\n plt.ylim([0.0, 2.0])\n plt.setp(ax.get_yticklabels(), visible=False)\n\n # Create and plot a Beta distribution to represent the\n # posterior belief in fairness of the coin.\n y = stats.beta.pdf(x, 1 + heads, 1 + N - heads)\n plt.plot(x, y, label="observe %d tosses,\\n %d heads" % (N, heads))\n plt.fill_between(x, 0, y, color="#aaaadd", alpha=0.5)\n # Expand plot to cover full width/height and show it\n plt.tight_layout()\n plt.show()\nRun Code Online (Sandbox Code Playgroud)\n我在这一行收到错误:ax = plt.subplot(len(number_of_trials) / 2, 2, i + 1) \nValueError: Number of rows must be a positive integer, not 3.0
我尝试设置int(number_of_trials)但没有成功。
有任何想法吗?
\n您需要将整体投射len(number_of_trials) / 2为int.
ax = plt.subplot(int(len(number_of_trials) / 2), 2, i + 1)
Run Code Online (Sandbox Code Playgroud)
这解决了错误。
| 归档时间: |
|
| 查看次数: |
4696 次 |
| 最近记录: |