下载地址:https://archive.ics.uci.edu/ml/machine-learning-databases/housing/housing.data
打开方式: 直接用excel可以打开,转存为csv等
模型训练
from sklearn.linear_model import Lasso
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import load_bostonboston = load_boston()
scaler = StandardScaler()X = scaler.fit_transform(boston["data"])
print('X',X)
Y = boston["target"]
print('Y', Y)
names = boston["feature_names"]
print('names',names)
LASSO惩罚回归
from sklearn.linear_model import Lasso
from sklearn.preprocessing import StandardScaler
from sklearn.datasets import load_boston
import numpy as np#输出线性方程的辅助函数
def pretty_print_linear(coefs, names = None, sort = False):if names is None:names = ["X%s" % x for x in range(len(coefs))]lst = zip(coefs, names)if sort:lst = sorted(lst, key = lambda x:-np.abs(x[0]))return " + ".join("%s * %s" % (np.round(coef, 3), name) for coef, name in lst)
boston = load_boston()
scaler = StandardScaler()
X = scaler.fit_transform(boston["data"])
Y = boston["target"]
names = boston["feature_names"]lasso = Lasso(alpha=.3)
lasso.fit(X, Y)print("lasso model:", pretty_print_linear(lasso.coef_, names, sort = True))