In the previous sections we learned about PCA. We worked out an example from scratch to emphasis the mechanics behind PCA.

In this section we revisit the *food-texture* data set and briefly showcase PCA.

Consider the food-texture data set (download here). In this section we revisit the food-texture data set and briefly showcase PCA by applying the Python machinery.

In [1]:

```
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
from sklearn.decomposition import PCA
```

In [2]:

```
food = pd.read_csv("https://userpage.fu-berlin.de/soga/data/raw-data/food-texture.csv")
# exclude first column
food = food.iloc[:, 1:]
food.head()
```

Out[2]:

Oil | Density | Crispy | Fracture | Hardness | |
---|---|---|---|---|---|

0 | 16.5 | 2955 | 10 | 23 | 97 |

1 | 17.7 | 2660 | 14 | 9 | 139 |

2 | 16.2 | 2870 | 12 | 17 | 143 |

3 | 16.7 | 2920 | 10 | 31 | 95 |

4 | 16.3 | 2975 | 11 | 26 | 143 |

In [3]:

```
# center and scale the data
food_scaled = (food - food.mean()) / food.std()
food_scaled.head()
# Calculate the PCA
food_pca = PCA().fit(food_scaled)
```

`components_`

attribute. The name relates to the term *rotation matrix* and emphasis that a matrix-multiplication of the data-matrix with the rotation matrix returns the coordinates of the data in the rotated coordinate system, and thus the principal component scores.

In [4]:

```
print(f"Rotation matrix:\n{food_pca.components_}")
```

The standard deviation can be obtained from the attribute `explained_variance_`

attribute.

In [5]:

```
print(f"Standard deviation of each principal component:\n{np.sqrt(food_pca.explained_variance_)}")
```

`explained_variance_`

attribute.

In [6]:

```
print(f"Variance explained by each principal component:\n{food_pca.explained_variance_}")
```

In [7]:

```
print(f"Proportion of variance explained by each principal component:\n{food_pca.explained_variance_ratio_}")
```

We see that the first principal component explains 61% of the variance in the data, the second principal component explains 26% of the variance, and so forth.

Finally, we are interested in the principal component scores, which correspond to the projection of the original data on the directions of the principal component. The principal component scores can be extracted as follows. We will print only the first 10 rows here.

In [8]:

```
scores = food_pca.transform(food_scaled)
print(f"Principal component scores:\n{scores[:10, :]}")
```

The columns of the matrix correspond to principal component score vectors. That is, the k^th^ column is the k^th^ principal component score vector.

The biplot{target="_blank"} is a very popular way for visualization of results from PCA, as it combines both, the principal component scores and the loading vectors in a single biplot display. We can create a biplot graph in Python as follows:

In [9]:

```
# biplot
fig, ax = plt.subplots(figsize=(8, 8))
ax.scatter(
scores[:, 0],
scores[:, 1],
color="none",
edgecolor="k",
alpha=0.5,
)
for i in range(food_pca.components_.shape[1]):
ax.arrow(
0,
0,
food_pca.components_[0, i],
food_pca.components_[1, i],
head_width=0.1,
head_length=0.1,
linewidth=2,
color="red",
)
ax.text(
food_pca.components_[0, i] + 0.1,
food_pca.components_[1, i] + 0.1,
food.columns[i],
color="red",
ha="center",
va="center",
)
for i in range(scores.shape[0]):
ax.text(
scores[i, 0] + 0.2,
scores[i, 1],
food.index[i],
color="blue",
ha="center",
va="center",
)
ax.set_xlabel("PC1")
ax.set_ylabel("PC2")
ax.set_title("Biplot")
plt.show()
```

**Oil** on the first component is $-0.45$, and its loading on the second principal component $0.48$ (the label "Oil" is centered at the point ($-0.45$, $0.48$)).

**Citation**

The E-Learning project SOGA-Py was developed at the Department of Earth Sciences by Annette Rudolph, Joachim Krois and Kai Hartmann. You can reach us via mail by soga[at]zedat.fu-berlin.de.

You may use this project freely under the Creative Commons Attribution-ShareAlike 4.0 International License.

Please cite as follow: *Rudolph, A., Krois, J., Hartmann, K. (2023): Statistics and Geodata Analysis
using Python (SOGA-Py). Department of Earth Sciences, Freie Universitaet Berlin.*