Linear regression¶

This lecture is adapted from Morten Hjorth-Jensen's notes on linear regression.

Linear regression is a useful first example of machine learning. Its fitted coefficients can be found analytically, so we can introduce models, data, loss functions, regularization, and numerical conditioning without first needing an optimization algorithm. The model is linear in its coefficients; its dependence on the input can be nonlinear.

Some important concepts are:

  • Data. We have $n$ observations $D=\{(x_i,y_i)\}_{i=0}^{n-1}$. Each input $x_i$ can be a scalar or a vector of features. For regression, the output $y_i$ is a numerical quantity. For credit-card default, (x_i) might include income, debt, and payment history, while (y_i) says whether the customer defaults. For handwriting recognition, (x_i) contains the image’s pixel values and (y_i) identifies the digit or letter. For tumor diagnosis, (x_i) contains measured properties such as size and smoothness, while (y_i) says whether the tumor is benign or malignant. These are classification examples because (y_i) is a category; in our nuclear regression example, (x_i=A_i) and (y_i) is a numerical binding energy per nucleon.

  • Model and noise. We approximate the numerical output by $y_i=\widetilde y(x_i)+\varepsilon_i$. For least squares, we minimize squared residuals; no particular distribution for $\varepsilon_i$ is needed to calculate the fit. Independent, zero-mean Gaussian errors with common variance $\sigma^2$ are an additional assumption used for a likelihood interpretation and some uncertainty estimates.

  • Loss function. The mean squared error (MSE) is $$C_{\rm MSE}=\frac{1}{n}\sum_{i=0}^{n-1}[y_i-\widetilde y(x_i)]^2.$$ The mean absolute error (MAE) instead uses $|y_i-\widetilde y(x_i)|$. If measurement errors $\sigma_i$ are known, the usual chi-squared statistic is $\chi^2=\sum_i[(y_i-\widetilde y_i)/\sigma_i]^2$. With a common $\sigma$, $\chi^2=nC_{\rm MSE}/\sigma^2$.

    For binary classification, a common loss is the negative log-likelihood (binary cross-entropy), where $p_i$ is the predicted probability of class 1 and $y_i\in\{0,1\}$: $$C_{\rm BCE}=-\frac{1}{n}\sum_i\big[y_i\log p_i+(1-y_i)\log(1-p_i)\big].$$ We minimize this loss when fitting a classifier.

  • Covariance and correlation. Let $x_{ij}$ be feature $j$ of observation $i$, and let $\bar x_j=n^{-1}\sum_i x_{ij}$. The population covariance of features $j$ and $k$ in this data set is $$C_{jk}=\frac{1}{n}\sum_i(x_{ij}-\bar x_j)(x_{ik}-\bar x_k).$$ Its diagonal entries are variances. When both variances are nonzero, the correlation is $\rho_{jk}=C_{jk}/\sqrt{C_{jj}C_{kk}}$. When estimating a population variance from a sample, one often uses $1/(n-1)$ instead of $1/n$.

Linear regression model¶

We represent the prediction as a linear combination of chosen basis functions $g_j(x)$: $$\widetilde y(x_i)=\sum_{j=0}^{p-1}g_j(x_i)\beta_j.$$ The unknowns are the coefficients $\beta_j$. The basis functions might be powers $x^j$, Legendre or Chebyshev polynomials, or (for periodic data) real Fourier functions such as $\cos(2\pi jx/L)$ and $\sin(2\pi jx/L)$. Thus the fitted function can be nonlinear in $x$ while remaining linear in $\boldsymbol\beta$.

The design matrix $X\in\mathbb R^{n\times p}$ has one row per observation and one column per basis function: $$X_{ij}=g_j(x_i),\qquad \widetilde{\boldsymbol y}=X\boldsymbol\beta.$$ Here $n$ is the number of observations and $p$ is the number of fitted coefficients. Usually $n>p$; if $p>n$, the unregularized problem is underdetermined. Even when $n\ge p$, the columns must be linearly independent for a unique least-squares coefficient vector.

We choose the coefficients to minimize $$C(\boldsymbol\beta)=\frac{1}{n}\|\boldsymbol y-X\boldsymbol\beta\|_2^2,\qquad \boldsymbol\beta^*\in\operatorname*{arg\,min}_{\boldsymbol\beta\in\mathbb R^p}C(\boldsymbol\beta).$$ The design matrix is determined by the observed inputs and our choice of basis functions.

Differentiating the mean squared error gives $$\nabla_{\boldsymbol\beta}C=\frac{2}{n}X^T(X\boldsymbol\beta-\boldsymbol y).$$ Setting the gradient to zero yields the normal equations $$X^TX\boldsymbol\beta^*=X^T\boldsymbol y.$$ If $X$ has full column rank, $X^TX$ is invertible and the unique solution is $$\boldsymbol\beta^*=(X^TX)^{-1}X^T\boldsymbol y, \qquad \widetilde{\boldsymbol y}=X(X^TX)^{-1}X^T\boldsymbol y.$$ If $X$ is rank deficient, the normal equations still have solutions, but the coefficients need not be unique. We then use a pseudoinverse to select the minimum-norm solution.

For full-column-rank $X$, the matrix $P=X(X^TX)^{-1}X^T$ is an orthogonal projector onto the space spanned by the columns of $X$: $P^T=P$ and $P^2=P$. Therefore the fitted values are $\widetilde{\boldsymbol y}=P\boldsymbol y$. For rank-deficient $X$, the corresponding projector is $P=XX^+$, where $X^+$ is the Moore–Penrose pseudoinverse. We will derive $X^+$ from the SVD of $X$ below and see why it gives both the least-squares fit and the smallest possible coefficient norm.

The Hessian of the cost is $$\nabla^2_{\boldsymbol\beta}C=\frac{2}{n}X^TX.$$ For any vector $v$, $v^TX^TXv=\|Xv\|_2^2\ge0$. Thus the Hessian is positive semidefinite, and every least-squares solution is a global minimum. It is positive definite only if $X$ has full column rank; only then is the coefficient vector unique. If columns are linearly dependent, $X^TX$ is singular and the ordinary inverse in the preceding formula does not exist. A pseudoinverse or regularization can handle that case.

Why the SVD gives us the pseudoinverse¶

If $X$ is rectangular or has linearly dependent columns, we cannot use the ordinary inverse of $X^TX$. We still want the coefficients that best fit the data, and, if several coefficient vectors fit equally well, we want the one with the smallest length $\|\boldsymbol\beta\|_2$. The SVD provides that solution.

We take the SVD of $X$ itself, not of $X^TX$. For $X\in\mathbb R^{n\times p}$ of rank $r$, the compact SVD is $$X=U_r\Sigma_rV_r^T,$$ where $U_r\in\mathbb R^{n\times r}$ and $V_r\in\mathbb R^{p\times r}$ have orthonormal columns ($U_r^TU_r=V_r^TV_r=I_r$). The diagonal matrix $\Sigma_r=\operatorname{diag}(\sigma_1,\ldots,\sigma_r)$ contains only the positive singular values. Thus $\Sigma_r^{-1}$ exists even when $X^TX$ is singular.

We minimize $\|\boldsymbol y-X\boldsymbol\beta\|_2^2$. Setting its gradient to zero gives the normal equations $X^TX\boldsymbol\beta=X^T\boldsymbol y$. Substitute $X=U_r\Sigma_rV_r^T$: $$X^TX=V_r\Sigma_r^2V_r^T,\qquad X^T\boldsymbol y=V_r\Sigma_rU_r^T\boldsymbol y,$$ so $$V_r\Sigma_r^2V_r^T\boldsymbol\beta=V_r\Sigma_rU_r^T\boldsymbol y.$$ Multiplying by $V_r^T$ and dividing by the positive singular values yields $$\Sigma_r^2V_r^T\boldsymbol\beta=\Sigma_rU_r^T\boldsymbol y, \qquad V_r^T\boldsymbol\beta=\Sigma_r^{-1}U_r^T\boldsymbol y.$$

This determines the part of $\boldsymbol\beta$ in the span of $V_r$. We may also add any vector $z$ with $Xz=0$; it does not change the prediction. Thus every least-squares coefficient vector has the form $$\boldsymbol\beta=V_r\Sigma_r^{-1}U_r^T\boldsymbol y+z,\qquad z\in\ker X.$$ The two terms are orthogonal. Therefore $\|\boldsymbol\beta\|_2$ is smallest when $z=0$. This choice defines the Moore–Penrose pseudoinverse: $$\boxed{X^+=V_r\Sigma_r^{-1}U_r^T},\qquad \boxed{\boldsymbol\beta^*=X^+\boldsymbol y}.$$

The fitted values are $$\widetilde{\boldsymbol y}=X\boldsymbol\beta^*=XX^+\boldsymbol y=U_rU_r^T\boldsymbol y.$$ Hence $XX^+$ projects $\boldsymbol y$ onto the column space of $X$. The fit equals the original data only if $\boldsymbol y$ already lies in that space.

If $X$ has full column rank ($r=p$), this result reduces to the familiar expression $$X^+=(X^TX)^{-1}X^T.$$ Working directly with the SVD of $X$ is also more stable numerically: when $X$ has full column rank, forming $X^TX$ squares its condition number. The positive eigenvalues of $X^TX$ are $\sigma_j^2$, with another $p-r$ eigenvalues equal to zero when $r<p$.

Ridge regression¶

Ridge regression adds an $L_2$ penalty to the squared-error cost. With the normalization used here, $$C_{\rm Ridge}(\boldsymbol\beta)=\frac{1}{n}\|\boldsymbol y-X\boldsymbol\beta\|_2^2 +\frac{\lambda}{n}\|\boldsymbol\beta\|_2^2,\qquad\lambda>0.$$ The stationarity condition is $$(X^TX+\lambda I_p)\boldsymbol\beta_{\rm Ridge}=X^T\boldsymbol y,$$ so $\boldsymbol\beta_{\rm Ridge}=(X^TX+\lambda I_p)^{-1}X^T\boldsymbol y$. Because $X^TX$ is positive semidefinite, adding $\lambda I_p$ makes this matrix positive definite and invertible. This written cost penalizes every coefficient, including an intercept if it is included in $\boldsymbol\beta$; many practical implementations leave the intercept unpenalized.

With the compact SVD, $$\boldsymbol\beta_{\rm Ridge} =V_r\,\operatorname{diag}\!\left(\frac{\sigma_j}{\sigma_j^2+\lambda}\right)U_r^T\boldsymbol y.$$ Compared with the unregularized factor $1/\sigma_j$, directions with $\sigma_j^2\ll\lambda$ are strongly suppressed. Ridge continuously shrinks these directions; it does not set their coefficients exactly to zero. The choice of $\lambda$ is a hyperparameter decision, usually assessed with validation data.

Lasso regression¶

Lasso uses an $L_1$ penalty: $$C_{\rm Lasso}(\boldsymbol\beta)=\frac{1}{n}\|\boldsymbol y-X\boldsymbol\beta\|_2^2 +\frac{\lambda}{n}\sum_{j=0}^{p-1}|\beta_j|,\qquad\lambda>0.$$ The absolute value has derivative $\operatorname{sign}(\beta_j)$ when $\beta_j\ne0$, but no ordinary derivative at zero. At zero we use a subgradient $s_j\in[-1,1]$. The optimality condition is $$0=2X^T(X\boldsymbol\beta-\boldsymbol y)+\lambda\boldsymbol s,$$ where $s_j=\operatorname{sign}(\beta_j)$ for nonzero $\beta_j$ and $s_j\in[-1,1]$ at zero. Lasso can set coefficients exactly to zero; for a general design matrix it is solved numerically rather than by one matrix inverse. As with Ridge, the formula above penalizes the intercept if one is included in $\boldsymbol\beta$.

Example: an empirical fit to nuclear binding-energy data¶

The liquid-drop model motivates the study of nuclear binding energies. A schematic formula for the total binding energy depends on both neutron number $N$ and proton number $Z$, with $A=N+Z$: $$B_{\rm LD}(N,Z)=a_0+a_1A-a_2A^{2/3}-a_3\frac{Z^2}{A^{1/3}}-a_4\frac{(N-Z)^2}{A}.$$ Its terms represent volume, surface, Coulomb, and asymmetry contributions. This expression cannot be fitted term by term from $A$ alone because $Z$ and $N$ are also needed.

The supplied file NucleousEnergy.dat has two columns: $A$ and a binding-energy value on the per-nucleon scale (MeV per nucleon). For this introductory regression example, we instead fit an empirical function of $A$ only: $$\widetilde b(A)=\beta_0+\beta_1A+\beta_2A^{2/3}+\beta_3A^{-1/3}+\beta_4A^{-1}.$$ These five functions define the columns of our design matrix. This fit is useful for demonstrating linear regression, but its $\beta_j$ are not the physical liquid-drop coefficients $a_j$.

InĀ [1]:
import numpy as np
import matplotlib.pyplot as plt

# The file contains A and binding energy per nucleon.
x, y = np.loadtxt('NucleousEnergy.dat').T
plt.plot(x, y, '.', markersize=3)
plt.xlabel(r'$A=N+Z$')
plt.ylabel('Binding energy per nucleon (MeV)')
plt.show()
No description has been provided for this image

We will need scikit-learn package

InĀ [5]:
%pip install scikit-learn
Requirement already satisfied: scikit-learn in /Users/haule/miniconda3-clean/envs/work311/lib/python3.11/site-packages (1.9.1)
Requirement already satisfied: numpy>=1.24.1 in /Users/haule/miniconda3-clean/envs/work311/lib/python3.11/site-packages (from scikit-learn) (2.3.5)
Requirement already satisfied: scipy>=1.10.0 in /Users/haule/miniconda3-clean/envs/work311/lib/python3.11/site-packages (from scikit-learn) (1.17.1)
Requirement already satisfied: joblib>=1.4.0 in /Users/haule/miniconda3-clean/envs/work311/lib/python3.11/site-packages (from scikit-learn) (1.5.3)
Requirement already satisfied: narwhals>=2.0.1 in /Users/haule/miniconda3-clean/envs/work311/lib/python3.11/site-packages (from scikit-learn) (2.15.0)
Requirement already satisfied: threadpoolctl>=3.5.0 in /Users/haule/miniconda3-clean/envs/work311/lib/python3.11/site-packages (from scikit-learn) (3.8.0)
Note: you may need to restart the kernel to use updated packages.
InĀ [6]:
# Each column is one basis function evaluated at all observed A values.
X = np.column_stack((np.ones_like(x), x, x**(2/3), x**(-1/3), 1/x))
InĀ [7]:
from sklearn.linear_model import LinearRegression

# X already contains a column of ones, so do not fit another intercept.
lg = LinearRegression(fit_intercept=False)
clf = lg.fit(X, y)
yt = clf.predict(X)

We can obtain the same coefficients with NumPy. The formula derived above uses $(X^TX)^{-1}$ when $X$ has full column rank, but forming $X^TX$ and explicitly inverting it can magnify numerical errors. np.linalg.lstsq computes the least-squares solution more reliably.

InĀ [8]:
Beta = np.linalg.lstsq(X, y, rcond=None)[0]
ytilde = X @ Beta
InĀ [9]:
plt.plot(x, yt, label='scikit-learn fit')
plt.plot(x, y, '.', markersize=3, label='Data')
plt.plot(x, ytilde, '--', label='NumPy least-squares fit')
plt.xlabel(r'$A=N+Z$')
plt.ylabel('Binding energy per nucleon (MeV)')
plt.legend()
plt.show()
No description has been provided for this image
InĀ [10]:
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score

print('scikit-learn coefficients:', clf.coef_)
print('NumPy coefficients:       ', Beta)
print('Largest prediction difference:', np.max(np.abs(yt - ytilde)))
print('In-sample MSE:', mean_squared_error(y, yt))
print('In-sample MAE:', mean_absolute_error(y, yt))
print('In-sample R²:', r2_score(y, yt))
scikit-learn coefficients: [ 5.29439975e+00 -2.96611194e-02  2.01719003e-01  1.08078025e+01
 -4.03097597e+01]
NumPy coefficients:        [ 5.29439975e+00 -2.96611194e-02  2.01719003e-01  1.08078025e+01
 -4.03097597e+01]
Largest prediction difference: 0.0
In-sample MSE: 0.022022882954618375
In-sample MAE: 0.05478750964867796
In-sample R²: 0.9549351910143222

The mean squared error is $\mathrm{MSE}=n^{-1}\sum_i(y_i-\widetilde y_i)^2$; the mean absolute error is $\mathrm{MAE}=n^{-1}\sum_i|y_i-\widetilde y_i|$. The printed scores above use the observations that were also used to fit the model. They describe the fit to the available data, not predictive accuracy on unseen observations.

To estimate prediction quality for held-out observations, we can split the data, fit on the training subset, and evaluate on the test subset. Because this is a random split across mass numbers, it mainly tests interpolation within the available range of $A$, not extrapolation to much lighter or heavier nuclei.

Another metric, mean squared logarithmic error, compares $\log(1+y_i)$ with $\log(1+\widetilde y_i)$ and requires nonnegative targets and predictions. It is not needed for this example. A robust alternative for fitting in the presence of outliers is the Huber loss, which is quadratic near zero residual and grows linearly for large residuals.

InĀ [11]:
from sklearn.model_selection import train_test_split

X_train, X_test, y_train, y_test = train_test_split(
    X, y, test_size=0.2, random_state=42
)
test_model = LinearRegression(fit_intercept=False).fit(X_train, y_train)
print('Training MSE:', mean_squared_error(y_train, test_model.predict(X_train)))
print('Held-out MSE:', mean_squared_error(y_test, test_model.predict(X_test)))
print('Held-out R²:', r2_score(y_test, test_model.predict(X_test)))
Training MSE: 0.025115710153731225
Held-out MSE: 0.012498172538313044
Held-out R²: 0.9436756855138202

A brief introduction to pandas¶

pandas provides labeled data structures for Python. A DataFrame is a two-dimensional table, while a Series is a one-dimensional labeled array. The following examples show indexing, simple statistics, and plotting. They are separate from the nuclear-regression example above.

InĀ [12]:
import pandas as pd
from IPython.display import display
data = {'First Name': ["Frodo", "Bilbo", "Aragorn II", "Samwise"],
        'Last Name': ["Baggins", "Baggins","Elessar","Gamgee"],
        'Place of birth': ["Shire", "Shire", "Eriador", "Shire"],
        'Date of Birth T.A.': [2968, 2890, 2931, 2980]
        }
data_pandas = pd.DataFrame(data)
display(data_pandas)

print('Standard Python print:', data)
First Name Last Name Place of birth Date of Birth T.A.
0 Frodo Baggins Shire 2968
1 Bilbo Baggins Shire 2890
2 Aragorn II Elessar Eriador 2931
3 Samwise Gamgee Shire 2980
Standard Python print: {'First Name': ['Frodo', 'Bilbo', 'Aragorn II', 'Samwise'], 'Last Name': ['Baggins', 'Baggins', 'Elessar', 'Gamgee'], 'Place of birth': ['Shire', 'Shire', 'Eriador', 'Shire'], 'Date of Birth T.A.': [2968, 2890, 2931, 2980]}

We import pandas as pd, the usual abbreviation. A DataFrame can use default numbered row labels or labels that we provide. Here we replace the default row labels with character names.

InĀ [13]:
data_pandas = pd.DataFrame(data,index=['Frodo','Bilbo','Aragorn','Sam'])
display(data_pandas)
First Name Last Name Place of birth Date of Birth T.A.
Frodo Frodo Baggins Shire 2968
Bilbo Bilbo Baggins Shire 2890
Aragorn Aragorn II Elessar Eriador 2931
Sam Samwise Gamgee Shire 2980

We can select the row labeled Aragorn:

InĀ [14]:
display(data_pandas.loc['Aragorn'])
First Name            Aragorn II
Last Name                Elessar
Place of birth           Eriador
Date of Birth T.A.          2931
Name: Aragorn, dtype: object

We can add another row with pd.concat:

InĀ [15]:
new_hobbit = {'First Name': ['Peregrin'],
              'Last Name': ['Took'],
              'Place of birth': ['Shire'],
              'Date of Birth T.A.': [2990]}
data_pandas = pd.concat([data_pandas, pd.DataFrame(new_hobbit, index=['Pippin'])])
display(data_pandas)
First Name Last Name Place of birth Date of Birth T.A.
Frodo Frodo Baggins Shire 2968
Bilbo Bilbo Baggins Shire 2890
Aragorn Aragorn II Elessar Eriador 2931
Sam Samwise Gamgee Shire 2980
Pippin Peregrin Took Shire 2990

For numerical data, DataFrames support column statistics and array operations. The next example creates a $10\times5$ array and compares pandas results with direct NumPy calculations.

InĀ [16]:
import pandas as pd
from IPython.display import display

np.random.seed(100)
rows, cols = 10, 5
a = np.random.randn(rows, cols)
df = pd.DataFrame(a)
display(df)

our_mean = np.mean(a, axis=0)
print('pandas mean:\n', df.mean())
print('NumPy mean: ', our_mean)

# pandas std() uses ddof=1: the sample variance has denominator rows-1.
# This convention differs from the population standard deviation (ddof=0).
our_s = np.sqrt(np.sum((a - our_mean)**2, axis=0)/(rows - 1))
print('pandas sample standard deviation:\n', df.std())
print('Our sample standard deviation:', our_s)
0 1 2 3 4
0 -1.749765 0.342680 1.153036 -0.252436 0.981321
1 0.514219 0.221180 -1.070043 -0.189496 0.255001
2 -0.458027 0.435163 -0.583595 0.816847 0.672721
3 -0.104411 -0.531280 1.029733 -0.438136 -1.118318
4 1.618982 1.541605 -0.251879 -0.842436 0.184519
5 0.937082 0.731000 1.361556 -0.326238 0.055676
6 0.222400 -1.443217 -0.756352 0.816454 0.750445
7 -0.455947 1.189622 -1.690617 -1.356399 -1.232435
8 -0.544439 -0.668172 0.007315 -0.612939 1.299748
9 -1.733096 -0.983310 0.357508 -1.613579 1.470714
pandas mean:
 0   -0.175300
1    0.083527
2   -0.044334
3   -0.399836
4    0.331939
dtype: float64
NumPy mean:  [-0.1753003   0.08352721 -0.04433397 -0.39983565  0.33193917]
pandas sample standard deviation:
 0    1.069584
1    0.965548
2    1.018232
3    0.793167
4    0.918992
dtype: float64
Our sample standard deviation: [1.06958439 0.96554792 1.01823155 0.79316689 0.91899236]

We can rename rows and columns, select a column, and summarize the table:

InĀ [17]:
df.columns = ['First', 'Second', 'Third', 'Fourth', 'Fifth']
df.index = np.arange(1, 11)

display(df)
print('Mean of Second:', df['Second'].mean())
df.info()
print(df.describe())
First Second Third Fourth Fifth
1 -1.749765 0.342680 1.153036 -0.252436 0.981321
2 0.514219 0.221180 -1.070043 -0.189496 0.255001
3 -0.458027 0.435163 -0.583595 0.816847 0.672721
4 -0.104411 -0.531280 1.029733 -0.438136 -1.118318
5 1.618982 1.541605 -0.251879 -0.842436 0.184519
6 0.937082 0.731000 1.361556 -0.326238 0.055676
7 0.222400 -1.443217 -0.756352 0.816454 0.750445
8 -0.455947 1.189622 -1.690617 -1.356399 -1.232435
9 -0.544439 -0.668172 0.007315 -0.612939 1.299748
10 -1.733096 -0.983310 0.357508 -1.613579 1.470714
Mean of Second: 0.08352721390288316
<class 'pandas.core.frame.DataFrame'>
Index: 10 entries, 1 to 10
Data columns (total 5 columns):
 #   Column  Non-Null Count  Dtype  
---  ------  --------------  -----  
 0   First   10 non-null     float64
 1   Second  10 non-null     float64
 2   Third   10 non-null     float64
 3   Fourth  10 non-null     float64
 4   Fifth   10 non-null     float64
dtypes: float64(5)
memory usage: 480.0 bytes
           First     Second      Third     Fourth      Fifth
count  10.000000  10.000000  10.000000  10.000000  10.000000
mean   -0.175300   0.083527  -0.044334  -0.399836   0.331939
std     1.069584   0.965548   1.018232   0.793167   0.918992
min    -1.749765  -1.443217  -1.690617  -1.613579  -1.232435
25%    -0.522836  -0.633949  -0.713163  -0.785061   0.087887
50%    -0.280179   0.281930  -0.122282  -0.382187   0.463861
75%     0.441264   0.657041   0.861676  -0.205231   0.923602
max     1.618982   1.541605   1.361556   0.816847   1.470714
InĀ [18]:
import matplotlib as mpl

mpl.rcParams['font.family'] = 'serif'

# Plot the cumulative sums, one line per column.
df.cumsum().plot(lw=2.0, figsize=(10, 6))
plt.show()

df.plot.bar(figsize=(10, 6), rot=15)
plt.show()
No description has been provided for this image
No description has been provided for this image

Here is the same $4\times4$ matrix as a NumPy array and as a DataFrame:

InĀ [19]:
b = np.arange(16).reshape((4,4))
print(b)
df1 = pd.DataFrame(b)
print(df1)
[[ 0  1  2  3]
 [ 4  5  6  7]
 [ 8  9 10 11]
 [12 13 14 15]]
    0   1   2   3
0   0   1   2   3
1   4   5   6   7
2   8   9  10  11
3  12  13  14  15

A Series is a one-dimensional labeled array. It shares many indexing and vectorized-operation features with a DataFrame, but it is a separate data structure, not a subclass of DataFrame. For labeled arrays with more than two dimensions, xarray is another useful package.