import numpy as np
import scipy.io as sio
from scipy.io import loadmat
import scipy.optimize as opt
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
E:\Anaconda\lib\site-packages\seaborn\_decorators.py:36: FutureWarning: Pass the following variables as keyword args: x, y. From version 0.12, the only valid positional argument will be `data`, and passing other arguments without an explicit keyword will result in an error or misinterpretation.
warnings.warn(
Regularized linear regression cost function
X, Xval, Xtest =[np.insert(x.reshape(x.shape[0],1),0, np.ones(x.shape[0]), axis=1)for x in(X, Xval, Xtest)]
deflinear_regression_np(X, y, l=1):# STEP1:初始化参数
theta = np.ones(X.shape[1])# STEP2:调用优化算法拟合参数# your code here (appro ~ 1 lines)
res = opt.minimize(fun=regularized_cost,
x0=theta,
args=(X, y, l),
method='TNC',
jac=regularized_gradient,
options={'disp':True})return res
theta = np.ones(X.shape[0])
final_theta = linear_regression_np(X, y, l=0).get('x')
#特征映射defpoly_features(x, power, as_ndarray=False):#特征映射
data ={'f{}'.format(i): np.power(x, i)for i inrange(1, power +1)}
df = pd.DataFrame(data)return df.values if as_ndarray else df
defnormalize_feature(df):"""Applies function along input axis(default 0) of DataFrame."""return df.apply(lambda column:(column - column.mean())/ column.std())
defprepare_poly_data(*args, power):"""
args: keep feeding in X, Xval, or Xtest
will return in the same order
"""defprepare(x):# 特征映射
df = poly_features(x, power=power)# 归一化处理
ndarr = normalize_feature(df).values
# 添加偏置项return np.insert(ndarr,0, np.ones(ndarr.shape[0]), axis=1)return[prepare(x)for x in args]