Skip to content

Commit 282f356

Browse files
committed
random walk tutorial
1 parent b3fd849 commit 282f356

File tree

1 file changed

+80
-92
lines changed

1 file changed

+80
-92
lines changed

unconverted/python/random-walk.md

+80-92
Original file line numberDiff line numberDiff line change
@@ -8,9 +8,19 @@ jupyter:
88
format_version: '1.1'
99
jupytext_version: 1.1.1
1010
kernelspec:
11-
display_name: Python 2
11+
display_name: Python 3
1212
language: python
13-
name: python2
13+
name: python3
14+
language_info:
15+
codemirror_mode:
16+
name: ipython
17+
version: 3
18+
file_extension: .py
19+
mimetype: text/x-python
20+
name: python
21+
nbconvert_exporter: python
22+
pygments_lexer: ipython3
23+
version: 3.6.7
1424
plotly:
1525
description: Learn how to use Python to make a Random Walk
1626
display_as: statistics
@@ -26,28 +36,7 @@ jupyter:
2636
title: Random Walk in Python. | plotly
2737
---
2838

29-
#### New to Plotly?
30-
Plotly's Python library is free and open source! [Get started](https://plot.ly/python/getting-started/) by dowloading the client and [reading the primer](https://plot.ly/python/getting-started/).
31-
<br>You can set up Plotly to work in [online](https://plot.ly/python/getting-started/#initialization-for-online-plotting) or [offline](https://plot.ly/python/getting-started/#initialization-for-offline-plotting) mode, or in [jupyter notebooks](https://plot.ly/python/getting-started/#start-plotting-online).
32-
<br>We also have a quick-reference [cheatsheet](https://images.plot.ly/plotly-documentation/images/python_cheat_sheet.pdf) (new!) to help you get started!
33-
34-
35-
#### Imports
36-
The tutorial below imports [NumPy](http://www.numpy.org/), [Pandas](https://plot.ly/pandas/intro-to-pandas-tutorial/), [SciPy](https://www.scipy.org/), and [Random](https://docs.python.org/2/library/random.html).
37-
38-
```python
39-
import plotly.plotly as py
40-
import plotly.graph_objs as go
41-
from plotly.tools import FigureFactory as FF
42-
43-
import numpy as np
44-
import pandas as pd
45-
import scipy
46-
import random
47-
```
48-
49-
####Tips
50-
A `random walk` can be thought of as a random process in which a tolken or a marker is randomly moved around some space, that is, a space with a metric used to compute distance. It is more commonly conceptualized in one dimension ($\mathbb{Z}$), two dimensions ($\mathbb{Z}^2$) or three dimensions ($\mathbb{Z}^3$) in Cartesian space, where $\mathbb{Z}$ represents the set of integers. In the visualizations below, we will be using [scatter plots](https://plot.ly/python/line-and-scatter/) as well as a colorscale to denote the time sequence of the walk.
39+
A [random walk](https://en.wikipedia.org/wiki/Random_walk) can be thought of as a random process in which a token or a marker is randomly moved around some space, that is, a space with a metric used to compute distance. It is more commonly conceptualized in one dimension ($\mathbb{Z}$), two dimensions ($\mathbb{Z}^2$) or three dimensions ($\mathbb{Z}^3$) in Cartesian space, where $\mathbb{Z}$ represents the set of integers. In the visualizations below, we will be using [scatter plots](https://plot.ly/python/line-and-scatter/) as well as a colorscale to denote the time sequence of the walk.
5140

5241

5342
#### Random Walk in 1D
@@ -56,76 +45,96 @@ A `random walk` can be thought of as a random process in which a tolken or a mar
5645
The jitter in the data points along the x and y axes are meant to illuminate where the points are being drawn and what the tendancy of the random walk is.
5746

5847
```python
59-
x = [0]
60-
61-
for j in range(100):
62-
step_x = random.randint(0,1)
63-
if step_x == 1:
64-
x.append(x[j] + 1 + 0.05*np.random.normal())
65-
else:
66-
x.append(x[j] - 1 + 0.05*np.random.normal())
48+
import plotly.graph_objects as go
49+
import numpy as np
6750

68-
y = [0.05*np.random.normal() for j in range(len(x))]
51+
l = 100
52+
steps = np.random.choice([-1, 1], size=l) + 0.05 * np.random.randn(l) # l steps
53+
position = np.cumsum(steps) # integrate the position by summing steps values
54+
y = 0.05 * np.random.randn(l)
6955

70-
trace1 = go.Scatter(
71-
x=x,
56+
fig = go.Figure(data=go.Scatter(
57+
x=position,
7258
y=y,
7359
mode='markers',
7460
name='Random Walk in 1D',
7561
marker=dict(
76-
color=[i for i in range(len(x))],
62+
color=np.arange(l),
7763
size=7,
78-
colorscale=[[0, 'rgb(178,10,28)'], [0.50, 'rgb(245,160,105)'],
79-
[0.66, 'rgb(245,195,157)'], [1, 'rgb(220,220,220)']],
64+
colorscale='Reds',
8065
showscale=True,
8166
)
82-
)
67+
))
8368

84-
layout = go.Layout(
85-
yaxis=dict(
86-
range=[-1, 1]
87-
)
88-
)
89-
90-
data = [trace1]
91-
fig= go.Figure(data=data, layout=layout)
92-
py.iplot(fig, filename='random-walk-1d')
69+
fig.update_layout(yaxis_range=[-1, 1])
70+
fig.show()
9371
```
9472

9573
#### Random Walk in 2D
9674

9775
```python
98-
x = [0]
99-
y = [0]
100-
101-
for j in range(1000):
102-
step_x = random.randint(0,1)
103-
if step_x == 1:
104-
x.append(x[j] + 1 + np.random.normal())
105-
else:
106-
x.append(x[j] - 1 + np.random.normal())
107-
108-
step_y = random.randint(0,1)
109-
if step_y == 1:
110-
y.append(y[j] + 1 + np.random.normal())
111-
else:
112-
y.append(y[j] - 1 + np.random.normal())
113-
114-
trace1 = go.Scatter(
115-
x=x,
116-
y=y,
76+
import plotly.graph_objects as go
77+
import numpy as np
78+
79+
l = 1000
80+
x_steps = np.random.choice([-1, 1], size=l) + 0.2 * np.random.randn(l) # l steps
81+
y_steps = np.random.choice([-1, 1], size=l) + 0.2 * np.random.randn(l) # l steps
82+
x_position = np.cumsum(x_steps) # integrate the position by summing steps values
83+
y_position = np.cumsum(y_steps) # integrate the position by summing steps values
84+
85+
fig = go.Figure(data=go.Scatter(
86+
x=x_position,
87+
y=y_position,
11788
mode='markers',
11889
name='Random Walk',
11990
marker=dict(
120-
color=[i for i in range(len(x))],
91+
color=np.arange(l),
12192
size=8,
12293
colorscale='Greens',
12394
showscale=True
12495
)
125-
)
96+
))
97+
98+
fig.show()
99+
```
100+
101+
#### Random walk and diffusion
126102

127-
data = [trace1]
128-
py.iplot(data, filename='random-walk-2d')
103+
In the two following charts we show the link between random walks and diffusion. We compute a large number `N` of random walks representing for examples molecules in a small drop of chemical. While all trajectories start at 0, after some time the spatial distribution of points is a Gaussian distribution. Also, the average distance to the origin grows as $\sqrt(t)$.
104+
105+
```python
106+
import plotly.graph_objects as go
107+
import numpy as np
108+
109+
l = 1000
110+
N = 10000
111+
steps = np.random.choice([-1, 1], size=(N, l)) + 0.05 * np.random.standard_normal((N, l)) # l steps
112+
position = np.cumsum(steps, axis=1) # integrate all positions by summing steps values along time axis
113+
114+
fig = go.Figure(data=go.Histogram(x=position[:, -1])) # positions at final time step
115+
fig.show()
116+
```
117+
118+
```python
119+
import plotly.graph_objects as go
120+
from plotly.subplots import make_subplots
121+
import numpy as np
122+
123+
l = 1000
124+
N = 10000
125+
t = np.arange(l)
126+
steps = np.random.choice([-1, 1], size=(N, l)) + 0.05 * np.random.standard_normal((N, l)) # l steps
127+
position = np.cumsum(steps, axis=1) # integrate the position by summing steps values
128+
average_distance = np.std(position, axis=0) # average distance
129+
130+
fig = make_subplots(1, 2)
131+
fig.add_trace(go.Scatter(x=t, y=average_distance, name='mean distance'), 1, 1)
132+
fig.add_trace(go.Scatter(x=t, y=average_distance**2, name='mean squared distance'), 1, 2)
133+
fig.update_xaxes(title_text='$t$')
134+
fig.update_yaxes(title_text='$l$', col=1)
135+
fig.update_yaxes(title_text='$l^2$', col=2)
136+
fig.update_layout(showlegend=False)
137+
fig.show()
129138
```
130139

131140
#### Advanced Tip
@@ -157,24 +166,3 @@ $$
157166

158167
Therefore, we expect our random walk to hover around $0$ regardless of how many steps we take in our walk.
159168

160-
```python
161-
from IPython.display import display, HTML
162-
163-
display(HTML('<link href="//fonts.googleapis.com/css?family=Open+Sans:600,400,300,200|Inconsolata|Ubuntu+Mono:400,700" rel="stylesheet" type="text/css" />'))
164-
display(HTML('<link rel="stylesheet" type="text/css" href="http://help.plot.ly/documentation/all_static/css/ipython-notebook-custom.css">'))
165-
166-
! pip install git+https://github.com/plotly/publisher.git --upgrade
167-
import publisher
168-
publisher.publish(
169-
'python-Random-Walk.ipynb', 'python/random-walk/', 'Random Walk | plotly',
170-
'Learn how to use Python to make a Random Walk',
171-
title='Random Walk in Python. | plotly',
172-
name='Random Walk',
173-
language='python',
174-
page_type='example_index', has_thumbnail='false', display_as='statistics', order=10,
175-
ipynb= '~notebook_demo/114')
176-
```
177-
178-
```python
179-
180-
```

0 commit comments

Comments
 (0)