zoukankan      html  css  js  c++  java
  • 关于线性回归的矩阵格式

      直接上代码:

     1 x = np.array([1,2,3,4]).reshape(-1,1)
     2 y = np.array([2,4,6,8]).reshape(-1,1)
     3 line = LinearRegression()
     4 line.fit(x, y)
     5 y_predict = line.predict(x)
     6 plt.plot(x, y_predict, "b-")
     7 print("x
    ", x)
     8 print("
    y
    ", y)
     9 print("line.coef_: ", line.coef_)
    10 print("line.intercept_: ", line.intercept_)

      x [[1] [2] [3] [4]] y [[2] [4] [6] [8]] line.coef_: [[2.]] line.intercept_: [0.]

      完美,这是非常标准的线性回归的参数形式;看到coef和intercept也是和我们预期是相符的。

      下面的是转置之后的数据处理:

     1 x = np.array([1,2,3,4]).reshape(-1,1)
     2 y = np.array([2,4,6,8]).reshape(-1,1)
     3 line = LinearRegression()
     4 line.fit(x.T, y.T)
     5 y_predict = line.predict(x.T)
     6 plt.plot(x.T, y_predict, "r.")
     7 print("x.T
    ", x.T)
     8 print("
    y.T
    ", y.T)
     9 print("line.coef_: ", line.coef_)
    10 print("line.intercept_: ", line.intercept_)

     

      x.T [[1 2 3 4]] y.T [[2 4 6 8]] line.coef_: [[0. 0. 0. 0.] [0. 0. 0. 0.] [0. 0. 0. 0.] [0. 0. 0. 0.]] line.intercept_: [2. 4. 6. 8.]

    从图上可以看到,学习的结果转变成了四个点(如果plot的参数改为"r-"则什么也不会画出来,因为仅仅是四个点)。学习的结果也和预期完全不一样,权重W为0,截距是y值。

    下面继续,我本意是希望x代表月份,y代表销售额,我手头有多个产品的月份-销售额数据,想要一次性把多个多个产品的权重求出来。但是,

     1 x = np.array([[1,2,3,4],[1,2,3,4]])
     2 y = np.array([[2,4,6,8],[4,6,8,10]])
     3 line = LinearRegression()
     4 line.fit(x, y)
     5 y_predict = line.predict(x)
     6 #plt.plot(x.T, y_predict.T)
     7 print("x
    ", x)
     8 print("
    y
    ", y)
     9 print("line.coef_: ", line.coef_)
    10 print("line.intercept_: ", line.intercept_) 

      x [[1 2 3 4] [1 2 3 4]] y [[ 2 4 6 8] [ 4 6 8 10]] line.coef_: [[0. 0. 0. 0.] [0. 0. 0. 0.] [0. 0. 0. 0.] [0. 0. 0. 0.]] line.intercept_: [3. 5. 7. 9.]

      乱了,这里全乱了,尤其是W,怎么成了一个4*4的格式,因为这个是两个产品的月份,我其实期待的是一个两行一列的数据结构。

      这里其实就要回到初心了,要明白线性回归本质是矩阵计算,目标Y是一个2*4矩阵,x是一个2*4的矩阵,Y=X.dot(W),这意味着,W要是一个4*4的矩阵,这样X和W相乘才能够保证Y的shape是2*4。

      回想一下第一个例子,之所以W实现了1*1,是因为X是4*1,y是4*1,所以W的shape是1*1。

      这样,对于线性回归而言我们只能一次性分析一行,无法实现一次性学习多个。

  • 相关阅读:
    深入浅出新一代云网络——VPC中的那些功能与基于OpenStack Neutron的实现(三)-路由与隧道
    从这两年的云计算行业安全黑板报来看看云安全现状
    深入浅出新一代云网络——VPC中的那些功能与基于OpenStack Neutron的实现(二)-带宽控制
    云环境下的安全服务架构
    深入浅出新一代云网络——VPC中的那些功能与基于OpenStack Neutron的实现(一)-简述与端口转发
    OpenStack修复影响宿主机的QEMU漏洞CVE-2017-2615
    OpenStack Newton版本Ceph集成部署记录
    团队博客汇总
    谷歌浏览器将任意网页转成中文
    password_hash加密
  • 原文地址:https://www.cnblogs.com/xiashiwendao/p/11181032.html
Copyright © 2011-2022 走看看