Looking at "Seeing the World Through the Language of Mathematics" with Python... Vol. 2 Dice and Probability
Chapter 1: "Judging from Uncertain Information"
Author of the book: Dr. Hirosi Ooguri
This is a Python coding record of Chapter 1, "Judging from Uncertain Information" from the book "Seeing the World Through the Language of Mathematics".
I will try rolling the dice in Python for Section 1, "First, Let's Try Rolling the Dice."
This is a practice in random number generation and visualization.
Now, let's open the book and set off on a mathematical journey 🚀

Introduction
This blog series introduces the "joy of mathematics" learned from the book "Seeing the World Through the Language of Mathematics" (Gentosha) in a "Python coding" format.
【Citation Notation】
This article cites text and data published in the book listed in the source, and the published text and data have been modified as appropriate.
【Source】
"Seeing the World Through the Language of Mathematics", 3rd printing, Author: Hirosi Ooguri, Gentosha

1. First, let's try rolling the dice
Learning Points
We will simulate rolling dice in Python to experience probability.
We will also experience the fun of visualization.
Import the libraries used in this article.
## インポート
import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt
plt.rcParams['font.family'] = 'Meiryo' # または import japanize_matplotlib
Roll a die, where each side is equally likely to appear, 1000 times
I will try [Method B] from page 17 of the book: "Calculate probability by actually rolling the dice."
I will generate 1000 "random numbers" where the values 1 through 6 appear with the same probability.
I will assume this is "the same as rolling a die where each side appears with the same probability 1000 times."
I will use the numpy.random generator for random number generation.
If you chant the following magic spell...
rng = np.random.default_rng()
You will be able to generate various random numbers with "rng".
This time, I will use rng.choice() to generate integers from 1 to 6 with equal probability.
### どの目も同じくらい出やすいサイコロを1000回振る試行
## 設定
# 試行回数
N = 1000
# 乱数生成器
rng = np.random.default_rng()
## サイコロを振って可視化
# サイコロを振る
samples = rng.choice(a=[1, 2, 3, 4, 5, 6], size=N)
# 出た目の数をカウント
uniques, counts = np.unique(samples, return_counts=True)
# 棒グラフの描画
p = plt.bar(uniques, height=counts/N, alpha=0.7)
# 棒の上に出た目の比率を表示
plt.bar_label(p, labels=counts/N)
plt.xlabel('サイコロの目', fontsize=12)
plt.ylabel('確率', fontsize=12);【Execution Results】
Although I set the conditions for equal probability, the probability of each outcome varies in the range of 0.159 to 0.177.
This is the nature of random numbers! Perhaps this is the realized value of probability!

The probability value for each side changes every time you run it.
Please try running the code yourself!
By the way, if you want to generate the same random values every time, set a "random seed."
The following code sets a random seed of "42."
rng = np.random.default_rng(seed=42)

Experimenting with the probability of a biased die
On page 16 of the book, there is an example of a "biased die" where the number 1 appeared 496 times out of 1000 rolls.
We will perform a dice simulation under the condition that the probability of rolling a 1 is 0.496, and the probabilities of the other numbers are equal.
### 1の目の出る確率が 0.496、それ以外の目は等確率のサイコロを1000回振る試行
## 設定
# 試行回数
N = 1000
# 乱数生成器
rng = np.random.default_rng()
## サイコロを振って可視化
# サイコロを振る
samples = rng.choice(a=[1, 2, 3, 4, 5, 6], p=[0.496] + [(1-0.496)/5]*5, size=N)
# 出た目の数をカウント
uniques, counts = np.unique(samples, return_counts=True)
# 棒グラフの描画
p = plt.bar(uniques, height=counts/N, alpha=0.7)
# 棒の上に出た目の比率を表示
plt.bar_label(p, labels=counts/N)
plt.xlabel('サイコロの目', fontsize=12)
plt.ylabel('確率', fontsize=12);【Execution Results】
It seems the number 1 does not come out to exactly 0.496.
The other numbers have a probability of approximately 0.1, but there is some variation.

The probability value for each number changes every time you run it.
Please try running the code yourself!

Rolling two dice that are equally likely to show any number, 1000 times
This is the experiment from page 17 of the book, "Now let's think about what happens when we roll two dice."
Since the two dice do not influence each other, the outcomes occur "independently."
The probability of rolling double ones is $${1/6 \times 1/6 = 1/36 \approx 0.0278}$$.
### どの目も同じくらい出やすいサイコロを2個、1000回振る試行
## 設定
# 試行回数
N = 1000
# 乱数生成器
rng = np.random.default_rng()
## サイコロを振って可視化
# サイコロを2個、1000回振る
samples1 = rng.choice(a=[1, 2, 3, 4, 5, 6], size=N)
samples2 = rng.choice(a=[1, 2, 3, 4, 5, 6], size=N)
# 2つの出た目の確率を算出 ※pandasのcrosstabでクロス集計表を作成
cross_tab = pd.crosstab(
samples1, samples2, rownames=['サイコロ1'], colnames=['サイコロ2']
) / N
# ヒートマップの描画
fig, ax = plt.subplots(figsize=(7, 6))
sns.heatmap(cross_tab, annot=True, fmt='.4f', cmap='Blues', ax=ax)
plt.title(f'出目が均等な2つのサイコロの出目確率 1/36={1/36:.4f}');【Execution Results】
This is a 2D heat map of the probability values.
It looks like there is quite a bit of variation.
This is "THE Probability".

The probability value for each number changes every time you run it.
Please try running the code yourself!
Visualization is fun, isn't it? ♬
The End
Series Articles
Next Article
Previous Article
Table of Contents
Blog Introduction
I am writing seven series articles on note.
Please come and take a look!
1. Relaxed Statistics
This is a blog that roughly explores probability and statistics using the Statistical Test Grade 2 problem collection as a guide.
Feel free to read it like a casual conversation. Please come and take a look.
It corresponds to the Statistical Test Grade 2 Official Problem Collection CBT Version.
Sample code for Python and EXCEL is also available.
2. Experiment! Fun Bayesian Modeling 1 & 2 with PyMC Ver. 5
I will draw and analyze the Bayesian models used in psychological research from the books "Fun Bayesian Modeling" and "Fun Bayesian Modeling 2" using PyMC Ver. 5.
Like this book, many Bayesian models are written in R + Stan.
I will explore the possibilities of PyMC and strive to make Bayesian modeling easy to practice.
Since these are familiar and easy-to-visualize themes, please try running them with PyMC and let's enjoy it together!
3. Experiment! Bayesian Modeling from Iwanami Data Science Vol. 1 with PyMC Ver. 5
I will draw and analyze the Bayesian models by four Bayesians from the book "Experiment! Iwanami Data Science Vol. 1" using PyMC Ver. 5.
This book is a great resource for learning the basics of Bayesian programming.
I feel like I've become friends with Bayesian methods by happily running PyMC models.
Everyone, please try running them with PyMC and let's play and learn together!
4. Fun Transcription: Bayesian, Python, etc.
I will blog about the results of my "book transcription activities" for Bayesian, Python, and other topics.
I am mainly working on translations into Python.
I hope this serves as sample code for fellow learners who are also transcribing code. 🍀
5. Introduction to Time Series Analysis for Psychology with R and Stan, using Python and PyMC Ver. 5
I will practice the time series analysis from the book "Introduction to Time Series Analysis for Psychology with R and Stan" using Python and PyMC Ver. 5.
This book is packed with themes on time series analysis!
I realized the depth of time series analysis.
I will enjoy learning time series analysis with my favorite language, Python.
6. Writing about Data Science-like things
I write columns on statistics, data analysis, AI, machine learning, and Python on an irregular basis.
There are many articles related to statistics and data science books.
Series on "Statistics," "Python," "Mathematics and Python," and "R" have been created.
7. Python Machine Learning Programming Practice Log
I wrote articles about my various thoughts while studying the book "Python Machine Learning Programming: PyTorch & scikit-learn Edition."
This book is a textbook for scikit-learn and PyTorch.
Please feel free to try it out if you like.
Thank you for reading until the end.
いいなと思ったら応援しよう!
応援ありがとうございます。これからもがんばって記事を作成します!