Scan to open on your phone
Point a camera at the QR code - it opens this exact paste, no app needed.
https://codepastes.com/sml1untitledPython
# ==============================================================================
# PROGRAM 7: Polynomial regression
# Question: Fit several degrees to noisy quadratic data. Compare the curves and
# training MSE.
# ==============================================================================
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_squared_error
np.random.seed(0)
X = np.linspace(-4, 4, 25).reshape(-1, 1)
y_true = 0.5 * X**2 + X + 2
y = y_true + np.random.normal(scale=1.5, size=X.shape)
plt.figure(figsize=(18, 10))
for i, degree in enumerate((1, 2, 5, 10, 15, 20), 1):
P = PolynomialFeatures(degree).fit_transform(X)
pred = LinearRegression().fit(P, y).predict(P)
mse = mean_squared_error(y, pred)
plt.subplot(2, 3, i)
plt.scatter(X, y, color='gray', label='Generated Data')
plt.plot(X, y_true, color='green', label='True Function')
plt.plot(X, pred, color='red', label=f'Degree {degree} Fit')
plt.title(f'Degree {degree} | MSE: {mse:.2f}')
plt.legend()
plt.tight_layout()
plt.show()
# ==============================================================================
# PROGRAM 8: Titanic classification with SVM
# Question: Fill missing values, encode categories, scale the features, and
# compare two kernels.
# ==============================================================================
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder, StandardScaler
from sklearn.svm import SVC
from sklearn import metrics
features = ['pclass', 'sex', 'age', 'sibsp', 'parch', 'fare', 'embarked']
df = sns.load_dataset('titanic')[features + ['survived']].copy()
df['age'] = df['age'].fillna(df['age'].median())
df['embarked'] = df['embarked'].fillna(df['embarked'].mode()[0])
for col in ('sex', 'embarked'):
df[col] = LabelEncoder().fit_transform(df[col])
Xtr, Xte, ytr, yte = train_test_split(df[features], df['survived'],
test_size=0.2, random_state=42)
scaler = StandardScaler().fit(Xtr)
Xtr, Xte = scaler.transform(Xtr), scaler.transform(Xte)
fig, axes = plt.subplots(1, 2, figsize=(12, 5))
for ax, name, color in zip(axes, ('Linear', 'RBF'), ('Blues', 'Greens')):
pred = SVC(kernel=name.lower(), random_state=42).fit(Xtr, ytr).predict(Xte)
print(f'===== SVM with {name} Kernel =====')
print('Accuracy:', metrics.accuracy_score(yte, pred))
print('Precision:', metrics.precision_score(yte, pred))
print('Recall:', metrics.recall_score(yte, pred))
print('F1 Score:', metrics.f1_score(yte, pred))
sns.heatmap(metrics.confusion_matrix(yte, pred),
annot=True, fmt='d', cmap=color, ax=ax)
ax.set(title=f'{name} Kernel', xlabel='Predicted', ylabel='Actual')
plt.tight_layout()
plt.show()
# ==============================================================================
# PROGRAM 9: Housing price spline regression
# Question: Fit a straight line and a piecewise-linear spline to price versus
# living area.
# ==============================================================================
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression, Ridge
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import SplineTransformer
df = pd.read_csv('Housing.csv')
print(df.head())
X, y = df[['sqft_living']].to_numpy(), df['price'].to_numpy()
grid = np.linspace(500, 14000, 1000).reshape(-1, 1)
# Note: If asked for a knot at 2,000 sq ft, replace `spline = ...` with:
# knots = np.array([[X.min()], [2000], [X.max()]])
# spline = SplineTransformer(degree=1, knots=knots)
spline = SplineTransformer(n_knots=3, degree=1)
model = make_pipeline(spline, Ridge(alpha=1e-3))
curve = model.fit(X, y).predict(grid)
line = LinearRegression().fit(X, y).predict(grid)
plt.plot(grid, curve, color='red', label='B-spline')
plt.plot(grid, line, color='green', linewidth=2, label='Linear Regression fit')
sns.scatterplot(data=df, x='sqft_living', y='price')
plt.legend()
plt.show()
# ==============================================================================
# PROGRAM 10: Ridge and LASSO regression
# Question: Compare test scores and coefficient plots on the diabetes dataset
# for two alpha values.
# ==============================================================================
import matplotlib.pyplot as plt
from sklearn.datasets import load_diabetes
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Ridge, Lasso
from sklearn.metrics import r2_score, mean_squared_error
X, y = load_diabetes(return_X_y=True)
Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=0.2, random_state=42)
scaler = StandardScaler().fit(Xtr)
Xtr, Xte = scaler.transform(Xtr), scaler.transform(Xte)
for alpha, sep in [(1, '='), (10, '= ')]:
plt.figure(figsize=(10, 5))
for name, Model, style in [('Ridge', Ridge, 'bo-'), ('LASSO', Lasso, 'ro-')]:
model = Model(alpha=alpha).fit(Xtr, ytr)
pred = model.predict(Xte)
prefix = '\n' if name == 'LASSO' else ''
print(f'{prefix}===== {name} Regression =====')
print('R2 Score:', r2_score(yte, pred))
print('MSE:', mean_squared_error(yte, pred))
print('Coefficients:', model.coef_)
plt.plot(model.coef_, style, label=f'{name} Coefficients')
plt.axhline(0, color='gray', linestyle='--')
plt.xlabel('Feature Index')
plt.ylabel('Coefficient Value')
plt.title(f'Effect of Regularization: Ridge vs LASSO Alpha {sep}{alpha}')
plt.legend()
plt.show()
# ==============================================================================
# PROGRAM 11: Gaussian mixture model with EM
# Question: Generate three clusters, estimate their means and covariances, and
# plot the assignments.
# ==============================================================================
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import make_blobs
from sklearn.mixture import GaussianMixture
means = np.array([[0, 0], [5, 5], [0, 5]])
X, y = make_blobs(600, centers=means, cluster_std=[0.8, 1, 0.6], random_state=42)
gmm = GaussianMixture(3, random_state=42).fit(X)
print('=== True Means === ')
print(means)
print('\n=== Estimated Means ===')
print(gmm.means_)
print('\n=== Estimated Covariances ===')
for i, cov in enumerate(gmm.covariances_, 1):
print(f'Cluster {i} covariance matrix:\n{cov}\n')
fig, axes = plt.subplots(1, 2, figsize=(10, 5))
plots = [(y, means, 'Actual Clusters', 'True Means'),
(gmm.predict(X), gmm.means_, 'GMM Predicted Clusters (EM Results)',
'Estimated Means')]
for ax, (labels, centers, title, name) in zip(axes, plots):
ax.set_title(title)
ax.scatter(*X.T, c=labels, s=30, cmap='viridis')
ax.scatter(*centers.T, c='red', marker='x', s=200, label=name)
ax.legend()
plt.show()
# ==============================================================================
# PROGRAM 12: Fisher LDA and logistic regression
# Question: Generate two imbalanced classes, compute covariance, and plot the
# Fisher projection. Fit balanced and unbalanced logistic regression
# models and evaluate their performance.
# ==============================================================================
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn import metrics
np.random.seed(0)
X0 = np.random.multivariate_normal([0, 0], [[1, 0.6], [0.6, 1.5]], 900)
X1 = np.random.multivariate_normal([2, 1.5], [[0.8, 0.2], [0.2, 0.6]], 100)
X = np.vstack([X0, X1])
y = np.repeat([0, 1], [len(X0), len(X1)])
features = ['x1', 'x2']
print('Class distribution:\n', pd.Series(y, name='y').value_counts(normalize=True))
print('Covariance matrix: \n', pd.DataFrame(np.cov(X.T), features, features))
# Fisher LDA: add both class scatter matrices, then normalize the direction
mu0, mu1 = X0.mean(axis=0), X1.mean(axis=0)
Sw = sum(len(group) * np.cov(group.T, bias=True) for group in (X0, X1))
w = np.linalg.pinv(Sw) @ (mu1 - mu0)
w /= np.linalg.norm(w)
fig, ax = plt.subplots()
for label in (0, 1):
ax.hist(X[y == label] @ w, bins=30, alpha=0.6, label=f'Class {label}')
ax.set(title='Fisher LDA Projection (1D)', xlabel='Projected value', ylabel='Count')
ax.legend()
ax.grid(True)
plt.show()
fig, ax = plt.subplots()
line = np.outer(np.linspace(-6, 6, 100), w) + X.mean(axis=0)
ax.scatter(*X.T, c=y, cmap='bwr', s=10)
ax.plot(*line.T, color='black', linewidth=2, label='LDA direction')
ax.set(title='Scatter of Features with LDA Direction', xlabel='x1', ylabel='x2')
ax.legend()
ax.grid(True)
plt.show()
# Part 2 of 2: Logistic regression and evaluation
Xtr, Xte, ytr, yte = train_test_split(X, y, stratify=y, test_size=0.3, random_state=1)
scaler = StandardScaler().fit(Xtr)
Xtr, Xte = scaler.transform(Xtr), scaler.transform(Xte)
balanced, unbalanced = [
LogisticRegression(class_weight=weight, solver='liblinear', random_state=0).fit(Xtr, ytr)
for weight in ('balanced', None)
]
preds = {'balanced': balanced.predict(Xte), 'unbalanced': unbalanced.predict(Xte)}
for name, pred in preds.items():
print(f'{name.capitalize()} model performance:\n')
print(metrics.classification_report(yte, pred, digits=4))
for name, pred in preds.items():
print(f'Confusion matrix ({name}):\n', metrics.confusion_matrix(yte, pred))
auc = metrics.roc_auc_score(yte, balanced.predict_proba(Xte)[:, 1])
print(f'ROC AUC (balanced model): {auc:.4f}')
coef = balanced.coef_[0]
original = coef / scaler.scale_
intercept = balanced.intercept_[0] - np.sum(scaler.mean_ * original)
print('Logistic regression coefficients (balanced model):\n')
print(pd.DataFrame({'feature': features, 'coef_scaled': coef,
'coef_original': original, 'odds_ratio': np.exp(original)}))
print('Intercept (original scale):', intercept)
p, r, f, n = metrics.precision_recall_fscore_support(
yte, preds['balanced'], labels=[0, 1])
print('Metrics by class (balanced logistic): \n', pd.DataFrame({
'class': [0, 1], 'precision': p, 'recall': r, 'f1': f, 'support': n}))
print('Summary:')
print(' Total samples:', len(X))
print(' Class 0 count:', len(X0))
print(' Class 1 count:', len(X1))
print(' LDA direction (unit vector):', w)
print(' Mean class 0:', mu0)
print(' Mean class 1:', mu1)
10,766 chars · codepastes.com