第一部分
import time
from sklearn.linear_model import Lasso
start = time.perf_counter()
end = time.perf_counter()
print(f"程序耗时为{(end - start).__round__(20)}")
第二部分
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression, Ridge, Lasso
X = np.random.randn(50, 200)
w = np.random.randn(200)
index = np.arange(200)
np.random.shuffle(index)
w[index[0:190]] = 0
y = X.dot(w)
lr = LinearRegression(fit_intercept=False)
ridge = Ridge(alpha=1, fit_intercept=False)
lasso = Lasso(alpha=0.2, fit_intercept=False)
lr.fit(X, y)
ridge.fit(X, y)
lasso.fit(X, y)
lr_w = lr.coef_
ridge_w = ridge.coef_
lasso_w = lasso.coef_
plt.figure(figsize=(9, 6))
ax = plt.subplot(2, 2, 1)
ax.plot(w)
ax.set_title(True)
ax = plt.subplot(2, 2, 2)
ax.plot(lr_w)
ax.set_title("Lr")
ax = plt.subplot(2, 2, 3)
ax.plot(ridge_w)
ax.set_title("Ridge")
ax = plt.subplot(2, 2, 4)
ax.plot(lasso_w)
ax.set_title("Lasso")
plt.show()
第三部分
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression, Ridge, Lasso
from sklearn.neighbors import KNeighborsRegressor
import sklearn.datasets as datasets
import time
from sklearn.model_selection import train_test_split
faces = datasets.fetch_olivetti_faces()
data = faces.get("images")
X = data[:, :32].reshape(400, -1)
y = data[:, 32:].reshape(400, -1)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=10)
estimators = {}
estimators["KNN"] = KNeighborsRegressor(n_neighbors=5)
estimators["Lr"] = LinearRegression()
estimators["Ridge"] = Ridge(alpha=1)
estimators["Lasso"] = Lasso(alpha=1)
predict_ = {}
for key, model in estimators.items():
model.fit(X_train, y_train)
y_ = model.predict(X_test)
predict_[key] = y_
plt.figure(figsize=(6 * 2, 10 * 2))
for i in range(10):
ax = plt.subplot(10, 6, 1 + i * 6)
face_up = X_test[i].reshape(32, 64)
face_down = y_test[i].reshape(32, 64)
ax.imshow(np.concatenate([face_up, face_down], axis=0), cmap="gray")
ax.axis("off")
if i == 0:
ax.set_title("True")
ax = plt.subplot(10, 6, 2 + i * 6)
ax.imshow(face_up, cmap="gray")
ax.axis("off")
if i == 0:
ax.set_title("Face_up")
for j, key in enumerate(predict_):
ax = plt.subplot(10, 6, 3 + j + i * 6)
y_ = predict_[key]
face_down_ = y_[i].reshape(32, 64)
ax.imshow(np.concatenate([face_up, face_down_], axis=0), cmap="gray")
ax.axis("off")
if i == 0:
ax.set_title(key)
start = time.perf_counter()
end = time.perf_counter()
print(f"程序耗时为{(end - start).__round__(20)}")