Python 如何使用Scikit-learn生成随机回归问题

Python 如何使用Scikit-learn生成随机回归问题

Python的Scikit-learn提供了make_regression()函数,可以帮助我们生成随机回归问题。在本教程中,我们将学习如何生成随机回归问题以及具有稀疏不相关设计的随机回归问题。

随机回归问题

要使用Python的Scikit-learn生成随机回归问题,可以按照以下步骤进行:

步骤 1 - 导入sklearn.datasets.make_regression和matplotlib库,这些库是执行程序所必需的。

步骤 2 - 提供样本数量和其他参数。

步骤 3 - 使用matplotlib库设置输出图形的大小和样式。

步骤 4 - 使用matplotlib绘制回归问题。

示例

在下面的示例中,我们将生成具有500个样本的回归问题。

# Importing libraries
from sklearn.datasets import make_regression
from matplotlib import pyplot as plt
from matplotlib import style
import seaborn as sns

# Set the figure size
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

# Creating and plotting the regression problem
style.use("Solarize_Light2")

r_data, r_values = make_regression(n_samples=500, n_features=1, n_informative=2, noise=1)

plt.scatter(r_data[:,0],r_values,cmap='rocket');
plt.show()

输出

它将产生以下输出−

Python 如何使用Scikit-learn生成随机回归问题

稀疏不相关设计的随机回归问题

Python Scikit-learn为我们提供了make_sparse_uncorrelated()函数,通过它我们可以生成一个具有不相关设计的随机回归问题。

要实现这个目标,我们可以按照以下步骤进行操作−

步骤 1 − 导入必要的sklearn.datasets.make_sparse_uncorrelated和matplotlib库来执行程序。

步骤 2 − 提供样本数和其他参数。

步骤 3 − 使用matplotlib库设置输出图形的大小和样式。

步骤 4 − 使用matplotlib绘制回归问题。

示例

在下面的示例中,我们将生成一个具有500个样本和4个特征的回归问题。参数n_features的默认值为10。

# Importing libraries
from sklearn.datasets import make_sparse_uncorrelated
from matplotlib import pyplot as plt
from matplotlib import style

# Set the figure size
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

# Creating the regression problem with sparse uncorrelated design
X, y = make_sparse_uncorrelated(n_samples=500, n_features=4)

# Plotting the dataset
style.use("Solarize_Light2")
plt.figure(figsize=(7.50, 3.50))
plt.title("Random regression problem with sparse uncorrelated design", fontsize="12")
plt.scatter(X[:,0],y,edgecolor="k");
plt.show()

输出

将会产生以下输出−

Python 如何使用Scikit-learn生成随机回归问题

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程