当数据过多时,无法将数据一次性加载到内存中,进行模型训练,
因此可以使用随机梯度下降回归器或分类器,作为线性预测器
该方法每次只是用一个观察点来进行参数优化,因此代码使用ridge或lasso回归到达可比较的结果之前,采用了更多的迭代,但只需要较少的内存和时间。
- 使用SGD优化时,需要测试不同的代价函数性能,一些SGD对异常点抵抗力较强,例如分类的modfied_huer和回归的huber
- SGD对变量尺度敏感,需要标准化特征,限制在【-1,1】或者【0,1】
- 使用SGD时,总是需要处理数据块。为了有效训练,首先使用StandardScaler从首批可用的数据中导出平均值和方差来做标准化。整个数据集的分布情况不同,但初始估计得到的变换可以发展成一个可工作的学习步骤。
from sklearn.linear_model import SGDRegressor
from sklearn.preprocessing import StandardScaler
SGD = SGDRegressor(loss='squared_loss', penalty='l2', alpha=0.0001, l1_ratio=0.15, n_iter=2000)
# l1_ratio=0 corresponds to L2 penalty, l1_ratio=1 to L1
# alpha constant that multiplies the regularization term. Defaults to 0.0001
scaling = StandardScaler()
scaling.fit(polyX)
scaled_X = scaling.transform(polyX)
print ('CV MSE: %.3f' % abs(np.mean(cross_val_score(SGD, scaled_X, y, scoring='neg_mean_squared_error', cv=crossvalidation, n_jobs=1))))
![]()
均方差均值为13.066
对数据做迭代,展示算法如何优化参数
from sklearn.metrics import mean_squared_error
from sklearn.cross_validation import train_test_split
X_train, X_test, y_train, y_test = train_test_split(scaled_X, y, test_size=0.20, random_state=2)
SGD = SGDRegressor(loss='squared_loss', penalty='l2', alpha=0.0001, l1_ratio=0.15)
improvements = list()
for z in range(1000):
SGD.partial_fit(X_train, y_train)
improvements.append(mean_squared_error(y_test, SGD.predict(X_test)))
#作图
import matplotlib.pyplot as plt
plt.subplot(1,2,1)
plt.plot(range(1,11),np.abs(improvements[:10]),'o--')
plt.xlabel('Partial fit initial iterations')
plt.ylabel('Test set mean squared error')
plt.subplot(1,2,2)
plt.plot(range(100,1000,100),np.abs(improvements[100:1000:100]),'o--')
plt.xlabel('Partial fit ending iterations')
plt.show()

plt.plot(range(1,1000),improvements[1:1000])

整体的错误率是下降的。
1万+



被折叠的 条评论
为什么被折叠?



