ML之LiR&2PolyR:使用线性回归LiR、二次多项式回归2PolyR模型在披萨数据集上拟合(train)、价格回归预测(test)


康乃馨沉静
康乃馨沉静 2022-09-19 15:27:48 51273
分类专栏: 资讯

ML之LiR&2PolyR:使用线性回归LiR、二次多项式回归2PolyR模型在披萨数据集上拟合(train)、价格回归预测(test)

目录

输出结果

设计思路

核心代码


输出结果

设计思路

 

核心代码

  1. poly2 = PolynomialFeatures(degree=2)
  2. X_train_poly2 = poly2.fit_transform(X_train)
  3. r_poly2 = LinearRegression()
  4. r_poly2.fit(X_train_poly2, y_train)
  5. poly2 = r_poly2.predict(xx_poly2)
  1. class PolynomialFeatures(BaseEstimator, TransformerMixin):
  2. """Generate polynomial and interaction features.
  3. Generate a new feature matrix consisting of all polynomial combinations
  4. of the features with degree less than or equal to the specified degree.
  5. For example, if an input sample is two dimensional and of the form
  6. [a, b], the degree-2 polynomial features are [1, a, b, a^2, ab, b^2].
  7. Parameters
  8. ----------
  9. degree : integer
  10. The degree of the polynomial features. Default = 2.
  11. interaction_only : boolean, default = False
  12. If true, only interaction features are produced: features that are
  13. products of at most ``degree`` *distinct* input features (so not
  14. ``x[1] ** 2``, ``x[0] * x[2] ** 3``, etc.).
  15. include_bias : boolean
  16. If True (default), then include a bias column, the feature in which
  17. all polynomial powers are zero (i.e. a column of ones - acts as an
  18. intercept term in a linear model).
  19. Examples
  20. --------
  21. >>> X = np.arange(6).reshape(3, 2)
  22. >>> X
  23. array([[0, 1],
  24. [2, 3],
  25. [4, 5]])
  26. >>> poly = PolynomialFeatures(2)
  27. >>> poly.fit_transform(X)
  28. array([[ 1., 0., 1., 0., 0., 1.],
  29. [ 1., 2., 3., 4., 6., 9.],
  30. [ 1., 4., 5., 16., 20., 25.]])
  31. >>> poly = PolynomialFeatures(interaction_only=True)
  32. >>> poly.fit_transform(X)
  33. array([[ 1., 0., 1., 0.],
  34. [ 1., 2., 3., 6.],
  35. [ 1., 4., 5., 20.]])
  36. Attributes
  37. ----------
  38. powers_ : array, shape (n_output_features, n_input_features)
  39. powers_[i, j] is the exponent of the jth input in the ith output.
  40. n_input_features_ : int
  41. The total number of input features.
  42. n_output_features_ : int
  43. The total number of polynomial output features. The number of output
  44. features is computed by iterating over all suitably sized combinations
  45. of input features.
  46. Notes
  47. -----
  48. Be aware that the number of features in the output array scales
  49. polynomially in the number of features of the input array, and
  50. exponentially in the degree. High degrees can cause overfitting.
  51. See :ref:`examples/linear_model/plot_polynomial_interpolation.py
  52. <sphx_glr_auto_examples_linear_model_plot_polynomial_interpolation.
  53. py>`
  54. """
  55. def __init__(self, degree=2, interaction_only=False, include_bias=True):
  56. self.degree = degree
  57. self.interaction_only = interaction_only
  58. self.include_bias = include_bias
  59. -meta"> @staticmethod
  60. def _combinations(n_features, degree, interaction_only, include_bias):
  61. comb = combinations if interaction_only else combinations_w_r
  62. start = int(not include_bias)
  63. return chain.from_iterable(comb(range(n_features), i) for
  64. i in range(start, degree + 1))
  65. -meta"> @property
  66. def powers_(self):
  67. check_is_fitted(self, 'n_input_features_')
  68. combinations = self._combinations(self.n_input_features_, self.
  69. degree,
  70. self.interaction_only,
  71. self.include_bias)
  72. return np.vstack(np.bincount(c, minlength=self.n_input_features_) for
  73. c in combinations)
  74. def get_feature_names(self, input_features=None):
  75. """
  76. Return feature names for output features
  77. Parameters
  78. ----------
  79. input_features : list of string, length n_features, optional
  80. String names for input features if available. By default,
  81. "x0", "x1", ... "xn_features" is used.
  82. Returns
  83. -------
  84. output_feature_names : list of string, length n_output_features
  85. """
  86. powers = self.powers_
  87. if input_features is None:
  88. input_features = ['x%d' % i for i in range(powers.shape[1])]
  89. feature_names = []
  90. for row in powers:
  91. inds = np.where(row)[0]
  92. if len(inds):
  93. name = " ".join(
  94. "%s^%d" % (input_features[ind], exp) if exp != 1 else
  95. input_features[ind] for
  96. (ind, exp) in zip(inds, row[inds]))
  97. else:
  98. name = "1"
  99. feature_names.append(name)
  100. return feature_names
  101. def fit(self, X, y=None):
  102. """
  103. Compute number of output features.
  104. Parameters
  105. ----------
  106. X : array-like, shape (n_samples, n_features)
  107. The data.
  108. Returns
  109. -------
  110. self : instance
  111. """
  112. n_samples, n_features = check_array(X).shape
  113. combinations = self._combinations(n_features, self.degree,
  114. self.interaction_only,
  115. self.include_bias)
  116. self.n_input_features_ = n_features
  117. self.n_output_features_ = sum(1 for _ in combinations)
  118. return self
  119. def transform(self, X):
  120. """Transform data to polynomial features
  121. Parameters
  122. ----------
  123. X : array-like, shape [n_samples, n_features]
  124. The data to transform, row by row.
  125. Returns
  126. -------
  127. XP : np.ndarray shape [n_samples, NP]
  128. The matrix of features, where NP is the number of polynomial
  129. features generated from the combination of inputs.
  130. """
  131. check_is_fitted(self, ['n_input_features_', 'n_output_features_'])
  132. X = check_array(X, dtype=FLOAT_DTYPES)
  133. n_samples, n_features = X.shape
  134. if n_features != self.n_input_features_:
  135. raise ValueError("X shape does not match training shape")
  136. allocate output data
  137. XP = np.empty((n_samples, self.n_output_features_), dtype=X.dtype)
  138. combinations = self._combinations(n_features, self.degree,
  139. self.interaction_only,
  140. self.include_bias)
  141. for i, c in enumerate(combinations):
  142. :i]XP[ = X[:c].prod(1)
  143. return XP

网站声明:如果转载,请联系本站管理员。否则一切后果自行承担。

本文链接:https://www.xckfsq.com/news/show.html?id=3281
赞同 0
评论 0 条
康乃馨沉静L0
粉丝 0 发表 6 + 关注 私信
上周热门
如何使用 StarRocks 管理和优化数据湖中的数据?  2944
【软件正版化】软件正版化工作要点  2863
统信UOS试玩黑神话:悟空  2823
信刻光盘安全隔离与信息交换系统  2718
镜舟科技与中启乘数科技达成战略合作,共筑数据服务新生态  1251
grub引导程序无法找到指定设备和分区  1217
华为全联接大会2024丨软通动力分论坛精彩议程抢先看!  163
点击报名 | 京东2025校招进校行程预告  162
2024海洋能源产业融合发展论坛暨博览会同期活动-海洋能源与数字化智能化论坛成功举办  160
华为纯血鸿蒙正式版9月底见!但Mate 70的内情还得接着挖...  157
本周热议
我的信创开放社区兼职赚钱历程 40
今天你签到了吗? 27
信创开放社区邀请他人注册的具体步骤如下 15
如何玩转信创开放社区—从小白进阶到专家 15
方德桌面操作系统 14
我有15积分有什么用? 13
用抖音玩法闯信创开放社区——用平台宣传企业产品服务 13
如何让你先人一步获得悬赏问题信息?(创作者必看) 12
2024中国信创产业发展大会暨中国信息科技创新与应用博览会 9
中央国家机关政府采购中心:应当将CPU、操作系统符合安全可靠测评要求纳入采购需求 8

加入交流群

请使用微信扫一扫!