<jupyter_start><jupyter_text>Linear RegressionPython InitializationFirst initialize the Python kernel.<jupyter_code>import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline<jupyter_output><empty_output><jupyter_text>Generate DataFirst, let's generate some data: $$y = 3x + 4 + \epsilon$$ $$\epsilon \sim N(0, 0.01)$$<jupyter_code>N = 40
X = np.random.rand(N, 1)
X = np.hstack((X, np.ones((N, 1))))
w = np.array([3, 4])
y = X @ w + np.random.randn(N) * 0.1<jupyter_output><empty_output><jupyter_text>Visualize DataNow, let's visualize the data, which will roughly lie on a line.<jupyter_code>plt.plot(X[:,0], y, 'o');
plt.xlabel('Feature');
plt.ylabel('Target');
plt.title('Synthetic Data');<jupyter_output><empty_output><jupyter_text>Learn Using Closed Form SolutionRecall the closed form solution:$$\mathbf{w} = (\mathbf{X}^T\mathbf{X})^{-1}\mathbf{X}^T\mathbf{y}$$<jupyter_code>w_closed = np.linalg.inv(X.T @ X) @ X.T @ y<jupyter_output><empty_output><jupyter_text>Visualize Closed Form SolutionLet's visualize the closed form solution with a line that is drawn over the data:<jupyter_code>plt.plot(X[:,0], y, 'o')
z = np.array([[0, 1], [1, 1]])
plt.plot(z[:,0], z @ w_closed, 'r');<jupyter_output><empty_output><jupyter_text>Pro-Tip: NumPy Linear Matrix SolverComputing matrix inverses can be numerically unstable and slow. Instead, one can use the Numpy linear matrix solver to solve the following linear system:$$(\mathbf{X}^T\mathbf{X})\mathbf{w} = \mathbf{X}^T\mathbf{y}$$The solution is the same, but it is typically faster and more stable in case $(\mathbf{X}^T\mathbf{X})$ is not invertible.<jupyter_code>w_closed = np.linalg.solve(X.T @ X, X.T @ y)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1609870740305523, 'fraction_numerical': 0.012925969447708578, 'mean_word_length': 6.671171171171171, 'pattern_counts': {'":': 0, '<': 25, '<?xml version=': 0, '>': 25, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '6', 'dir': 'jupyter-structured-clean-dedup', 'id': '544754', 'license': 'MIT', 'n_tokens_mistral': 655, 'n_tokens_neox': 618, 'n_words': 154, 'path': 'notebooks/linear_regression.ipynb', 'repo_name': 'Joshua-Robison/eCornell', 'size': '1702'}