-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathappendixC.qmd
More file actions
324 lines (240 loc) · 7.77 KB
/
Copy pathappendixC.qmd
File metadata and controls
324 lines (240 loc) · 7.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
# Tips on Converting to Python {#sec-appendixC}
Translating R code into Python can be a smooth transition with the right
approach. Let's start with the basics, from installing packages to
loading libraries, and compare the equivalents between R and Python,
including the popular tidyverse in R and its counterparts in Python.
## Packages and Libraries
1. **Installing Packages:**
- **R:**
``` r
install.packages("package_name")
```
- **Python (using pip):**
``` python
!pip install package_name
```
- **Python (using conda):**
``` python
!conda install package_name
```
2. **Loading Libraries:**
- **R:**
``` r
library(package_name)
```
- **Python:**
``` python
import package_name
```
## Comparing tidyverse with its Python Equivalents
- **tidyverse (R):** tidyverse is a collection of R packages designed
for data science, including dplyr for data manipulation, ggplot2 for
data visualization, tidyr for data tidying, etc.
``` r
library(tidyverse)
```
- **Python Equivalents:**
- **pandas:** Similar to dplyr, pandas provides powerful data
manipulation tools.
``` python
import pandas as pd
```
- **matplotlib/seaborn:** Comparable to ggplot2, these libraries
are used for data visualization.
``` python
import matplotlib.pyplot as plt
import seaborn as sns
```
- **numpy:** While not a direct equivalent to tidyr, numpy offers
functionalities for array manipulation and numerical computing,
which can be handy for data tidying tasks.
``` python
import numpy as np
```
- **scikit-learn:** Provides tools for data preprocessing,
modelling, and evaluation, resembling some functionalities of
tidyverse packages like modelr.
``` python
from sklearn import ...
```
- **tidyverse-like package:** There isn't a single package in
Python that encompasses the entire functionality of tidyverse,
but you can combine pandas, matplotlib/seaborn, numpy, and
scikit-learn to achieve similar results.
By understanding these equivalences and leveraging the rich ecosystem of
Python libraries, you can effectively translate your R code into Python,
ensuring a smooth transition while retaining the analytical power and
flexibility you need for your projects.
## Creating Data Making Statistics
1. **Creating Basic Data:**
- **R:**
``` r
# Create a data frame
data <- data.frame(
x = c(1, 2, 3, 4, 5),
y = c(2, 3, 4, 5, 6)
)
```
- **Python (using pandas):**
``` python
import pandas as pd
# Create a DataFrame
data = pd.DataFrame({
'x': [1, 2, 3, 4, 5],
'y': [2, 3, 4, 5, 6]
})
```
2. **Basic Statistics:**
- **R:**
``` r
# Summary statistics
summary(data)
```
- **Python (using pandas):**
``` python
# Summary statistics
print(data.describe())
```
## Building a Linear Regression Model
- **R:**
``` r
# Load the lm function from the stats package
library(stats)
# Fit a linear regression model
lm_model <- lm(y ~ x, data = data)
# Summary of the model
summary(lm_model)
```
- **Python (using statsmodels):**
``` python
import statsmodels.api as sm
# Add a constant term for intercept
X = sm.add_constant(data['x'])
# Fit a linear regression model
lm_model = sm.OLS(data['y'], X).fit()
# Summary of the model
print(lm_model.summary())
```
- **Python (using scikit-learn):**
``` python
from sklearn.linear_model import LinearRegression
# Initialize the model
lm_model = LinearRegression()
# Fit the model
lm_model.fit(data[['x']], data['y'])
# Coefficients
print("Intercept:", lm_model.intercept_)
print("Coefficient:", lm_model.coef_)
```
While the syntax and libraries may differ slightly, the overall process
remains conceptually similar. By understanding these comparisons, you
can effectively transition between R and Python for data analysis and
modelling tasks.
## Example of a Model Workflow
1. **Data Preprocessing**:
``` python
import pandas as pd
from sklearn.preprocessing import StandardScaler
data = pd.read_csv('data.csv')
data.fillna(method='ffill', inplace=True)
scaler = StandardScaler()
scaled_data = scaler.fit_transform(
data[['feature1', 'feature2', 'feature3']]
)
```
2. **Model Selection and Training**:
``` python
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
X = data[['feature1', 'feature2', 'feature3']]
y = data['DALYs']
X_train,
X_test,
y_train,
y_test = train_test_split(X, y, test_size=0.2, random_state=42)
model = LinearRegression()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
print(f'Mean Squared Error: {mse}')
```
3. **Time Series Forecasting Example**:
``` python
from fbprophet import Prophet
ts_data = data[['date', 'DALYs']]
ts_data.rename(columns={'date': 'ds', 'DALYs': 'y'}, inplace=True)
model = Prophet()
model.fit(ts_data)
future = model.make_future_dataframe(periods=365)
forecast = model.predict(future)
model.plot(forecast)
```
4. **The SIR Model Example**:
Set-up the environment for running python in RStudio by loading the
`{reticulate}` package and the following commands:
``` r
library(reticulate)
```
This is to configurate python and for installing necessary packages:
``` python
py_config()
# type <pip3 install scipy> on terminal
# type <pip3 install matplotlib> on terminal
```
``` python
import matplotlib
matplotlib.use('TkAgg') # Ensure you have an interactive backend
import matplotlib.pyplot as plt
import scipy.integrate as spi
import numpy as np
```
Set-up the parameters:
``` python
beta = 1.4247
gamma = 0.14286
TS = 1.0
ND = 70.0
S0 = 1 - 1e-6
I0 = 1e-6
INPUT = (S0, I0, 0.0)
```
Define differential equations:
``` python
def diff_eqs(INP, t):
Y = np.zeros((3))
V = INP
Y[0] = - beta * V[0] * V[1]
Y[1] = beta * V[0] * V[1] - gamma * V[1]
Y[2] = gamma * V[1]
return Y
t_start = 0.0; t_end = ND; t_inc = TS
t_range = np.arange(t_start, t_end + t_inc, t_inc)
RES = spi.odeint(diff_eqs, INPUT, t_range)
```
``` python
#Plotting
# Ensure interactive mode is on and plot
plt.ion()
plt.subplot(211)
plt.plot(RES[:, 0], '-g', label='Susceptibles')
plt.plot(RES[:, 2], '-k', label='Recovereds')
plt.legend(loc=0)
plt.title('SIR Model')
plt.xlabel('Time')
plt.ylabel('Susceptibles and Recovereds')
plt.subplot(212)
plt.plot(RES[:, 1], '-r', label='Infectious')
plt.xlabel('Time')
plt.ylabel('Infectious')
plt.show()
```
{#fig-appendixC_pysir
fig-alt="SIR Model with Python" fig-align="center"}
The code for this example is adapted from: [Modeling Infectious Diseases
in Humans and Animals Matt J. Keeling & Pejman
Rohani](https://homepages.warwick.ac.uk/~masfz/ModelingInfectiousDiseases/Chapter2/Program_2.1/index.html).
By following these steps, you can analyze DALYs and infectious diseases,
drawing trends, understanding relationships, and predicting future
outcomes effectively.