【Machine Learning】5.特征工程和多项式回归

2023-10-27

特征工程,使用线性回归机制来拟合非常复杂甚至非线性(存在 x n x^n xn)的函数。

1. 导入

import numpy as np
import matplotlib.pyplot as plt
from lab_utils_multi import zscore_normalize_features, run_gradient_descent_feng
np.set_printoptions(precision=2)  # reduced display precision on numpy arrays

2.多项式特征

这是线性回归时使用的
f w , b = w 0 x 0 + w 1 x 1 + . . . + w n − 1 x n − 1 + b (1) f_{\mathbf{w},b} = w_0x_0 + w_1x_1+ ... + w_{n-1}x_{n-1} + b \tag{1} fw,b=w0x0+w1x1+...+wn1xn1+b(1)

先看看按照以前的线性回归方法的效果

# create target data
x = np.arange(0, 20, 1)
y = 1 + x**2
X = x.reshape(-1, 1)

model_w,model_b = run_gradient_descent_feng(X,y,iterations=1000, alpha = 1e-2)

plt.scatter(x, y, marker='x', c='r', label="Actual Value"); plt.title("no feature engineering")
plt.plot(x,X@model_w + model_b, label="Predicted Value");  plt.xlabel("X"); plt.ylabel("y"); plt.legend(); plt.show()

在这里插入图片描述
明显不行,我们需要多项式特征,因此我们进行特征工程,调整x的次数

# create target data
x = np.arange(0, 20, 1)
y = 1 + x**2

# Engineer features 
X = x**2      #<-- added engineered feature

X = X.reshape(-1, 1)  #X should be a 2-D Matrix
model_w,model_b = run_gradient_descent_feng(X, y, iterations=10000, alpha = 1e-5)

Iteration         0, Cost: 7.32922e+03
Iteration      1000, Cost: 2.24844e-01
Iteration      2000, Cost: 2.22795e-01
Iteration         0, Cost: 7.32922e+03
Iteration      1000, Cost: 2.24844e-01
Iteration      2000, Cost: 2.22795e-01
Iteration      3000, Cost: 2.20764e-01
Iteration      4000, Cost: 2.18752e-01
Iteration      5000, Cost: 2.16758e-01
Iteration      3000, Cost: 2.20764e-01
Iteration      4000, Cost: 2.18752e-01
Iteration      5000, Cost: 2.16758e-01
Iteration      6000, Cost: 2.14782e-01
Iteration      7000, Cost: 2.12824e-01
Iteration      8000, Cost: 2.10884e-01
Iteration      6000, Cost: 2.14782e-01
Iteration      7000, Cost: 2.12824e-01
Iteration      8000, Cost: 2.10884e-01
Iteration      9000, Cost: 2.08962e-01
w,b found by gradient descent: w: [1.], b: 0.0490
Iteration      9000, Cost: 2.08962e-01
w,b found by gradient descent: w: [1.], b: 0.0490


plt.scatter(x, y, marker='x', c='r', label="Actual Value"); plt.title("Added x**2 feature")
plt.plot(x, np.dot(X,model_w) + model_b, label="Predicted Value"); plt.xlabel("x"); plt.ylabel("y"); plt.legend(); plt.show()


拟合出来的式子是 y = 1 ∗ x 0 2 + 0.049 y=1*x_0^2+0.049 y=1x02+0.049
在这里插入图片描述

3.特征选择

Above, we knew that an x 2 x^2 x2 term was required. It may not always be obvious which features are required. One could add a variety of potential features to try and find the most useful. For example, what if we had instead tried : y = w 0 x 0 + w 1 x 1 2 + w 2 x 2 3 + b y=w_0x_0 + w_1x_1^2 + w_2x_2^3+b y=w0x0+w1x12+w2x23+b ?
试一下别的,看拟合程度会不会更高

# create target data
x = np.arange(0, 20, 1)
y = x**2

# engineer features .
X = np.c_[x, x**2, x**3]   #<-- added engineered feature

model_w,model_b = run_gradient_descent_feng(X, y, iterations=10000, alpha=1e-7)

plt.scatter(x, y, marker='x', c='r', label="Actual Value"); plt.title("x, x**2, x**3 features")
plt.plot(x, X@model_w + model_b, label="Predicted Value"); plt.xlabel("x"); plt.ylabel("y"); plt.legend(); plt.show()


Iteration         0, Cost: 1.14029e+03
Iteration      1000, Cost: 3.28539e+02
Iteration      2000, Cost: 2.80443e+02
Iteration         0, Cost: 1.14029e+03
Iteration      1000, Cost: 3.28539e+02
Iteration      2000, Cost: 2.80443e+02
Iteration      3000, Cost: 2.39389e+02
Iteration      4000, Cost: 2.04344e+02
Iteration      5000, Cost: 1.74430e+02
Iteration      3000, Cost: 2.39389e+02
Iteration      4000, Cost: 2.04344e+02
Iteration      5000, Cost: 1.74430e+02
Iteration      6000, Cost: 1.48896e+02
Iteration      7000, Cost: 1.27100e+02
Iteration      8000, Cost: 1.08495e+02
Iteration      6000, Cost: 1.48896e+02
Iteration      7000, Cost: 1.27100e+02
Iteration      8000, Cost: 1.08495e+02
Iteration      9000, Cost: 9.26132e+01
w,b found by gradient descent: w: [0.08 0.54 0.03], b: 0.0106

在这里插入图片描述
拟合出来的式子: 0.08 x + 0.54 x 2 + 0.03 x 3 + 0.0106 0.08x + 0.54x^2 + 0.03x^3 + 0.0106 0.08x+0.54x2+0.03x3+0.0106

梯度下降通过强调其相关参数为我们选择“正确”的特征,较小的权重值意味着不太重要/正确的特征

4.多项式特征与线性特征的关联

我们进行多项式回归,也是在选择和y线性关联程度最高的特征

# create target data
x = np.arange(0, 20, 1)
y = x**2

# engineer features .
X = np.c_[x, x**2, x**3]   #<-- added engineered feature
X_features = ['x','x^2','x^3']
fig,ax=plt.subplots(1, 3, figsize=(12, 3), sharey=True)
for i in range(len(ax)):
    ax[i].scatter(X[:,i],y)
    ax[i].set_xlabel(X_features[i])
ax[0].set_ylabel("y")
plt.show()

在这里插入图片描述

5. 特征缩放 Scaling features

# create target data
x = np.arange(0,20,1)
X = np.c_[x, x**2, x**3]
print(f"Peak to Peak range by column in Raw        X:{np.ptp(X,axis=0)}")

# add mean_normalization 
X = zscore_normalize_features(X)     
print(f"Peak to Peak range by column in Normalized X:{np.ptp(X,axis=0)}")

Peak to Peak range by column in Raw        X:[  19  361 6859]
Peak to Peak range by column in Normalized X:[3.3  3.18 3.28]
Peak to Peak range by column in Raw        X:[  19  361 6859]
Peak to Peak range by column in Normalized X:[3.3  3.18 3.28]
x = np.arange(0,20,1)
y = x**2

X = np.c_[x, x**2, x**3]
X = zscore_normalize_features(X) 

model_w, model_b = run_gradient_descent_feng(X, y, iterations=100000, alpha=1e-1)

plt.scatter(x, y, marker='x', c='r', label="Actual Value"); plt.title("Normalized x x**2, x**3 feature")
plt.plot(x,X@model_w + model_b, label="Predicted Value"); plt.xlabel("x"); plt.ylabel("y"); plt.legend(); plt.show()

Iteration         0, Cost: 9.42147e+03
Iteration         0, Cost: 9.42147e+03
Iteration     10000, Cost: 3.90938e-01
Iteration     10000, Cost: 3.90938e-01
Iteration     20000, Cost: 2.78389e-02
Iteration     20000, Cost: 2.78389e-02
Iteration     30000, Cost: 1.98242e-03
Iteration     30000, Cost: 1.98242e-03
Iteration     40000, Cost: 1.41169e-04
Iteration     40000, Cost: 1.41169e-04
Iteration     50000, Cost: 1.00527e-05
Iteration     50000, Cost: 1.00527e-05
Iteration     60000, Cost: 7.15855e-07
Iteration     60000, Cost: 7.15855e-07
Iteration     70000, Cost: 5.09763e-08
Iteration     70000, Cost: 5.09763e-08
Iteration     80000, Cost: 3.63004e-09
Iteration     80000, Cost: 3.63004e-09
Iteration     90000, Cost: 2.58497e-10
Iteration     90000, Cost: 2.58497e-10
w,b found by gradient descent: w: [5.27e-05 1.13e+02 8.43e-05], b: 123.5000
w,b found by gradient descent: w: [5.27e-05 1.13e+02 8.43e-05], b: 123.5000

在这里插入图片描述

6.复杂函数的拟合

x = np.arange(0,20,1)
y = np.cos(x/2)

X = np.c_[x, x**2, x**3,x**4, x**5, x**6, x**7, x**8, x**9, x**10, x**11, x**12, x**13]
X = zscore_normalize_features(X) 

model_w,model_b = run_gradient_descent_feng(X, y, iterations=1000000, alpha = 1e-1)

plt.scatter(x, y, marker='x', c='r', label="Actual Value"); plt.title("Normalized x x**2, x**3 feature")
plt.plot(x,X@model_w + model_b, label="Predicted Value"); plt.xlabel("x"); plt.ylabel("y"); plt.legend(); plt.show()

Iteration         0, Cost: 2.24887e-01
Iteration         0, Cost: 2.24887e-01
Iteration    100000, Cost: 2.31061e-02
Iteration    100000, Cost: 2.31061e-02
Iteration    200000, Cost: 1.83619e-02
Iteration    200000, Cost: 1.83619e-02
Iteration    300000, Cost: 1.47950e-02
Iteration    300000, Cost: 1.47950e-02
Iteration    400000, Cost: 1.21114e-02
Iteration    400000, Cost: 1.21114e-02
Iteration    500000, Cost: 1.00914e-02
Iteration    500000, Cost: 1.00914e-02
Iteration    600000, Cost: 8.57025e-03
Iteration    600000, Cost: 8.57025e-03
Iteration    700000, Cost: 7.42385e-03
Iteration    700000, Cost: 7.42385e-03
Iteration    800000, Cost: 6.55908e-03
Iteration    800000, Cost: 6.55908e-03
Iteration    900000, Cost: 5.90594e-03
Iteration    900000, Cost: 5.90594e-03
w,b found by gradient descent: w: [-1.61e+00 -1.01e+01  3.00e+01 -6.92e-01 -2.37e+01 -1.51e+01  2.09e+01
 -2.29e-03 -4.69e-03  5.51e-02  1.07e-01 -2.53e-02  6.49e-02], b: -0.0073
w,b found by gradient descent: w: [-1.61e+00 -1.01e+01  3.00e+01 -6.92e-01 -2.37e+01 -1.51e+01  2.09e+01
 -2.29e-03 -4.69e-03  5.51e-02  1.07e-01 -2.53e-02  6.49e-02], b: -0.0073

在这里插入图片描述

7.课后题

  1. 特征缩放的时候要减去平均值
    在这里插入图片描述
  2. 代价不能较快的减少证明学习率偏大,代价反而增大证明学习率太大
    在这里插入图片描述
  3. 当特征之间的具体数值差距过大的时候,需要用到特征缩放

在这里插入图片描述
4. 数量乘价格才是销售总价

在这里插入图片描述

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

【Machine Learning】5.特征工程和多项式回归 的相关文章

  • 关于Spark报错不能连接到Server的解决办法(Failed to connect to master master_hostname:7077)

    问题产生 Spark集群 即可以基于Mesos或YARN来部署 也可以用自带的集群管理器 部署于standalone模式下 笔者在部署standalone模式时 首先 通过如下命令 启动了Master sbin start master s
  • 机器学习 之 python实现 多元线性回归 梯度下降 普适算法与矩阵算法

    介于网上的多元线性回归梯度下降算法多为固定数量的因变量 如三元一次函数 y 1 x 1
  • 正则化(Regularization)

    过拟合问题 Overfitting 当我们对一个问题建立线性回归模型或逻辑回归模型时 不恰当的选择特征会导致过拟合问题 过拟合问题是指当我们选择了很多的特征值时 模型对数据集的每一个example都符合的很好 但是对新的example却预测
  • 预测数值型数据:回归

    本文传送机 用线性回归找到最佳拟合直线 局部加权线性回归 通过缩减系数来 理解 数据 岭回归 lasso 前向逐步回归 用线性回归找到最佳拟合直线 线性回归 优点 结果易于理解 计算上不复杂 缺点 对非线性的数据拟合不好 适用数据类型 数值
  • 感知机(Perceptron)-----最详细记录感知机

    1 前言 感知机是1957年 由Rosenblatt提出会 是神经网络和支持向量机的基础 感知机是有生物学上的一个启发 他的参照对象和理论依据可以参照下图 我们的大脑可以认为是一个神经网络 是一个生物的神经网络 在这个生物的神经网络里边呢
  • 【基于协同过滤算法的电影推荐】

    目录 1 协同过滤算法 1 1 CF与 User Item 推荐算法区别 1 2 UserCF 1 3 ItemCF 2 评价指标 3 基于userCF与itemCF电影推荐 3 1 MovieLens数据集 3 2 userCF代码实现
  • 机器学习之梯度提升树(机器学习技法)

    梯度提升树模型 Gradient Boosted Decision Tree 与随机森林的对比 前面提到的随机森林使用Bagging的方式融合起来 也就是使用bootstrapping进行抽样得到不同的样本再加上不同的特征选择训练出不同的决
  • 【机器学习详解】SVM解二分类,多分类,及后验概率输出

    转载请注明出处 http blog csdn net luoshixian099 article details 51073885 CSDN 勿在浮沙筑高台 color Blue CSDN 21247 22312 28014 27801 3
  • 从零开始的Python机器学习指南(二)——监督学习之OLS回归

    介绍 本博客将结合样例介绍监督学习 Supervised Learning SL下的第一大分支 回归 Regression 开始前的准备 开始前 请先确保你的python环境中有以下包 pandas numpy sklearn 本文的所有代
  • 对numpy.c_的理解

    文章目录 文档描述 关于python科学计算 pandas numpy 中axis 轴 的理解 理解 文档描述 来自官方文档的叙述 这里只简单翻译一部分 numpy c numpy c
  • 牛顿法(Newton’s method)

    牛顿法通常都是用来寻找一个根 同时也可以理解为最大化目标函数的局部二次近似 设我们的目标函数为f x 那么一个关于x0的二次近似就有 我们用f进行匹配 可以得到 如果b lt 0 g的最大值为a 得到更新规则 这是牛顿法在最优化方面的表述
  • 深度学习知识体系学习大全 牛!!

    搬来了大牛的博客 点击直接前往 https www yuque com angsweet machine learning jian jie 配一张大牛的思维导图 具体内容点进去都能看到 数学 机器学习 语言 算法 深度学习 书籍推荐 东西
  • 基于产品的RFM模型的k-means聚类分析

    首先我们可以看看数据集的数据形态 导入rfm数据 查看数据的统计学参数 df pd read csv rfm csv df describe 在实施Kmeans聚类之前 我们必须检查这些关键k means假设 变量对称分布 不倾斜 具有相同
  • Structural Time Series modeling in TensorFlow Probability

    在邯郸学步后 想要深入用好Tensorflow中的STS model 还是要静下心来 好好阅读点材料 f t f 1
  • 机器学习简介

    介绍 机器学习是人工智能 AI 的一个子领域 机器学习的目标通常是理解数据的结构并将该数据拟合到人们可以理解和利用的模型中 尽管机器学习是计算机科学的一个领域 但它与传统的计算方法不同 在传统计算中 算法是计算机用来计算或解决问题的显式编程
  • 二值分类模型的评价指标

    二值分类模型的评价指标主要有 Precision Recall F Score ROC and AUC ROC Receiver Operating Characteristic ROC曲线的横坐标为false positive rate
  • 【数据预处理】Pandas缺失的数据处理

    目录 缺少数据基础 何时 为何 数据丢失 被视为 缺失 的值 日期时间 插入缺失数据 缺少数据的计算 Sum Prod of Empties Nans GroupBy中的NA值 清理 填写缺失数据 填充缺失值 fillna 用PandasO
  • Mxnet在Windows10, vs2015平台的编译及开发-CPU版本

    环境 基础配置 Windows10 cmake3 11 1 vs2015 QT5 11 1 mxnet配置 OpenBLAS v0 2 9 Win64 int32 opencv3 4 1 相关资源百度云链接 https pan baidu
  • 【特征工程】特征选择与特征学习

    特征选择与特征学习 在机器学习的具体实践任务中 选择一组具有代表性的特征用于构建模型是非常重要的问题 特征选择通常选择与类别相关性强 且特征彼此间相关性弱的特征子集 具体特征选择算法通过定义合适的子集评价函数来体现 在现实世界中 数据通常是
  • Several Machine Learning Problems

    Classification Classification algorithms are algorithms that learn topredict theclass orcategory of an instance of data

随机推荐