风也温柔

计算机科学知识库

线性回归算法java实现 线性回归和岭回归代码详解及Demo

  最近有小伙伴问我说,有没有的代码详解,前面博客讲的有点偏理论了。接受了小伙伴的意见,以后大管就理论和代码穿插着聊吧。今天咱就来聊一聊中线性回归和[岭回归]5的代码详解吧。

  ..

  使用的方法是最小线性二乘回归,线性回归拟合系数w = (w1,…,wp)的线性模型,以最小化数据集中观测目标与线性逼近预测目标之间的残差平方和。

  调用函数:

  ..(=True, =False, =True, =None)

  参数:

  :bool, , True 当选择true时使用截距,设置为False时,不使用截距。

  :bool,, False 是否要进行规范化(默认忽略),当为false时,默认关闭规范化,当把规范化开启时则回归前对回归量X进行归一化处理线性回归算法java实现 线性回归和岭回归代码详解及Demo,即减去均值,然后除以l2-范数。如果您希望标准化,请使用.预处理。在使用=False调用对估计量的拟合之前调用。

  :bool, , True 如果为真,输入的X会被复制;否则,它可能被覆盖。

  :int or None, (=None)用于要计算作业的数量,默认为None,当大于1时或者计算量足够大时开启加速。None意味着为1,-1表示使用所有的处理器。

  属性:

  coef_:array of shape (, ) or (, )线性回归的系数,如果输入为2维的,那输出也是2维数组(, ),如果输入是一维的,

  那输出就是长度为的一维数组。

  rank_:int 当输入X是稠密的时为矩阵X的秩

  :array of shape (min(X, y),) 矩阵X的奇异值线性回归算法java实现,当X为稠密的时可用。

  :float or array of shape of (,) 线性模型中的独立项(线性模型为一次时的截距)。如果 = False,则将其设置为0.0。

  示例代码:

   import numpy as np

    >>> from sklearn.linear_model import LinearRegression
    >>> X = np.array([[1, 1], [1, 2], [2, 2], [2, 3]])
    >>> # y = 1 * x_0 + 2 * x_1 + 3
    >>> y = np.dot(X, np.array([1, 2])) + 3
    >>> reg = LinearRegression().fit(X, y)
    >>> reg.score(X, y)
    1.0
    >>> reg.coef_
    array([1., 2.])
    >>> reg.intercept_
    3.0000...
    >>> reg.predict(np.array([[3, 5]]))

  中文分词算法java实现_kmeans算法java实现_线性回归算法java实现

  fit(self, X, y[, ]) 训练模型 :

  X{array-like, } of shape (, ) 训练数据集

  -like of shape (,) or (, ) 标签值。如果有必要,会转换成X的形状。

  -like of shape (,), =None 默认为false,每个样本独立的权值。

  (self[, deep]) 获取此模型的参数 :, =True 如果为真,将返回此估计器的参数以及包含的作为估计器的子对象,返回值: of to any 参数名映射到它们的值

  (self, X) 使用此线性模型来预测值 : or , shape (, ) 输入样本,返回值为预测的值。

  score(self, X, y[, ]) 返回预测的决定系数R^2。系数R^2定义为(1 - u/v),其中u为残差平方和(( - ) 2).sum(), v为总平方和(( - .mean() 2).sum()。最好的分数是1.0,也可能是负数(因为模型可能会任意变差)。如果一个常数模型总是预测y的期望值,而不考虑输入特性,则会得到R^2的0.0分。X:array-like of shape (, ) 测试样本,y:array-like of shape (,) or (, ) 样本X的真实值,-like of shape (,), =None 样本的权重,返回值:score(float) R^2系数。

  (self, **) 设置此估计器的参数。该方法既适用于简单的估计器,也适用于嵌套对象(如管道)。后者具有__的参数,因此可以更新嵌套对象的每个组件。

  **(dict) 估计的参数,返回值,估计的实例。

   import matplotlib.pyplot as plt

    import numpy as np
    from sklearn import datasets, linear_model
    from sklearn.metrics import mean_squared_error, r2_score
    # Load the diabetes dataset
    diabetes_X, diabetes_y = datasets.load_diabetes(return_X_y=True)
    # Use only one feature
    diabetes_X = diabetes_X[:, np.newaxis, 2]
     
    # Split the data into training/testing sets
    diabetes_X_train = diabetes_X[:-20]
    diabetes_X_test = diabetes_X[-20:]
     
    # Split the targets into training/testing sets
    diabetes_y_train = diabetes_y[:-20]
    diabetes_y_test = diabetes_y[-20:]
     
    # Create linear regression object
    regr = linear_model.LinearRegression()
     
    <p>

    # Train the model using the training sets
    regr.fit(diabetes_X_train, diabetes_y_train)
     
    # Make predictions using the testing set
    diabetes_y_pred = regr.predict(diabetes_X_test)
     
    # The coefficients
    print(&#39;Coefficients: \n&#39;, regr.coef_)
    # The mean squared error
    print(&#39;Mean squared error: %.2f&#39;
          % mean_squared_error(diabetes_y_test, diabetes_y_pred))
    # The coefficient of determination: 1 is perfect prediction
    print(&#39;Coefficient of determination: %.2f&#39;
          % r2_score(diabetes_y_test, diabetes_y_pred))
     
    # Plot outputs
    plt.scatter(diabetes_X_test, diabetes_y_test,  color=&#39;black&#39;)
    plt.plot(diabetes_X_test, diabetes_y_pred, color=&#39;blue&#39;, linewidth=3)
     
    plt.xticks(())
    plt.yticks(())
     

</p>
  最后的输出结果:

  kmeans算法java实现_线性回归算法java实现_中文分词算法java实现

  : [938.]

  Mean error: 2548.07

   of : 0.47

  ..Ridge

  中文分词算法java实现_线性回归算法java实现_kmeans算法java实现

  该模型解决了损失函数为线性最小二乘函数、正则化为l2范数的回归模型

  最小化目标函数:||y - Xw||^2_2 + alpha * ||w||^2_2。

  调用函数

  ..Ridge(alpha=1.0, =True, =False, =True, =None, tol=0.001, ='auto', =None)

  参数

  alpha{float, of shape (,)}, =1.0 正则化强度;必须是正的浮点型。正则化改进了问题的条件,减少了估计的方差。值越大正则化强度越强。在其他线性模型如逻辑回归或线性svc中,对应的是C^-1。如果传递了一个数组,则假定惩罚是特定于目标的。因此它们在数量上必须一致

  :bool, , True 当选择true时使用截距,设置为False时,不使用截距。

  :bool,, False 是否要进行规范化(默认忽略),当为false时,默认关闭规范化,当把规范化开启时则回归前对回归量X进行归一化处理,即减去均值,然后除以l2-范数。如果您希望标准化,请使用.预处理。在使用=False调用对估计量的拟合之前调用。

  :bool, , True 如果为真,输入的X会被复制;否则,它可能被覆盖。

  , =None 共轭梯度求解器的最大迭代次数。对于“”和“lsqr”求解器,默认值由sci ..确定。对于“sag”求解器,默认值是1000。

  , =1e-3 设置解的精度,默认是1e-3

  {‘auto’, ‘svd’, ‘’, ‘lsqr’, ‘’, ‘sag’, ‘saga’}, =’auto’ 选择求解的方式

  默认为auto’根据数据类型自动选择求解器

  svd '使用X的奇异值分解来计算脊线系数。对于奇异矩阵比‘’更稳定。

  用的是标准的scipy.函数

  “”使用了sci ...cg中的共轭梯度求解器。作为一种迭代算法线性回归算法java实现,该求解器比‘’更适用于大规模数据(可能设置为tol和)。

  “lsqr”使用专用的正则化最小二乘例程sci ...lsqr。它是最快的,并使用迭代过程。

  sag使用的是随机平均梯度下降法,saga使用的是改进版的无偏算法saga。这两种方法都使用迭代过程,并且在和都很大的情况下,通常比其他求解器更快。请注意,“sag”和“saga”的快速收敛只能保证在大致相同的尺度上。您可以使用来自.的标量对数据进行预处理。

  , , =None 当数据变换时使用的伪随机数生成器的种子。如果是int, 是随机数生成器使用的种子;如果实例,是随机数生成器;如果没有,随机数生成器就是np.使用的实例。当求解器为 ' sag '时使用。

  属性

   of shape (,) or (, ) 输出权重向量

   or of shape (,) 线性模型中的独立项(线性模型为一次时的截距)。如果 = False,则将其设置为0.0。

   or of shape (,) 每个目标的实际迭代次数。仅适用于sag和lsqr解决方案。其他解决程序将返回None。

   >>> from sklearn.linear_model import Ridge

    >>> import numpy as np
    >>> n_samples, n_features = 10, 5
    >>> rng = np.random.RandomState(0)
    >>> y = rng.randn(n_samples)
    >>> X = rng.randn(n_samples, n_features)
    
    >>> clf = Ridge(alpha=1.0)
    >>> clf.fit(X, y)

  fit(self, X, y, =None) 训练模型 :X {array-like, } of shape (, ) 训练数据集,

  y:array-like of shape (,) or (, ) 标签值。如果有必要,会转换成X的形状,

  :array-like of shape (,), =None 默认为false,每个样本独立的权值

  (self[, deep]) 获取此模型的参数 :, =True 如果为真,将返回此估计器的参数以及包含的作为估计器的子对象返回值: of to any 参数名映射到它们的值。

  (self, X) 使用此线性模型来预测值 ,X: or , shape (, ) 输入样本,返回值为预测的值。

  score(self, X, y[, ]) 返回预测的决定系数R^2。

  系数R^2定义为(1 - u/v),其中u为残差平方和(( - ) 2).sum(), v为总平方和(( - .mean() 2).sum()。最好的分数是1.0,也可能是负数(因为模型可能会任意变差)。如果一个常数模型总是预测y的期望值,而不考虑输入特性,则会得到R^2的0.0分。X:array-like of shape (, ) 测试样本,y:array-like of shape (,) or (, ) 样本X的真实值,:array-like of shape (,), =None 样本的权重返回值:返回值:score(float) R^2系数。

  (self, **) 设置此估计器的参数。该方法既适用于简单的估计器,也适用于嵌套对象(如管道)。后者具有__的参数,因此可以更新嵌套对象的每个组件。

  **(dict) 估计的参数,返回值,估计的实例。

  下面我们使用它来写一段代码来看一看正则化强度与权重的变化关系:

   import matplotlib.pyplot as plt

    import numpy as np
     
    from sklearn.datasets import make_regression
    from sklearn.linear_model import Ridge
    from sklearn.metrics import mean_squared_error
     
    clf = Ridge()
     
    X, y, w = make_regression(n_samples=10, n_features=10, coef=True,
                              random_state=1, bias=3.5)
     
    coefs = []
    errors = []
     
    alphas = np.logspace(-6, 6, 200)
    <p>![kmeans算法java实现_中文分词算法java实现_线性回归算法java实现][4]

     
    # Train the model with different regularisation strengths
    for a in alphas:
        clf.set_params(alpha=a)
        clf.fit(X, y)
        coefs.append(clf.coef_)
        errors.append(mean_squared_error(clf.coef_, w))
     
    # Display results
    plt.figure(figsize=(20, 6))
     
    plt.subplot(121)
    ax = plt.gca()
    ax.plot(alphas, coefs)
    ax.set_xscale(&#39;log&#39;)
    plt.xlabel(&#39;alpha&#39;)
    plt.ylabel(&#39;weights&#39;)
    plt.title(&#39;Ridge coefficients as a function of the regularization&#39;)
    plt.axis(&#39;tight&#39;)
     
    plt.subplot(122)
    ax = plt.gca()
    ax.plot(alphas, errors)
    ax.set_xscale(&#39;log&#39;)
    plt.xlabel(&#39;alpha&#39;)
    plt.ylabel(&#39;error&#39;)
    plt.title(&#39;Coefficient error as a function of the regularization&#39;)
    plt.axis(&#39;tight&#39;)
     

</p>
  输出结果为:

  文章来源:https://zhuanlan.zhihu.com/p/138557863