sklearn波士顿房价数据集绘制走势图
时间: 2023-09-06 17:10:14 浏览: 84
要绘制波士顿房价数据集的走势图,可以使用matplotlib库。以下是一个简单的示例代码:
```python
from sklearn.datasets import load_boston
import matplotlib.pyplot as plt
# 加载数据集
boston = load_boston()
# 获取数据集中的价格数据
prices = boston.target
# 绘制价格走势图
plt.plot(prices)
plt.ylabel('Price')
plt.show()
```
运行代码后,将会显示一个价格走势图,其中横轴表示样本编号,纵轴表示房价。你可以根据自己的需求调整图表的样式,例如添加标题、修改坐标轴范围等等。
相关问题
如何使用sklearn中波士顿房价预测数据集
1. 导入波士顿房价预测数据集
```python
from sklearn.datasets import load_boston
boston = load_boston()
```
2. 查看数据集的基本信息
```python
print(boston.DESCR) # 查看数据集的描述信息
print(boston.feature_names) # 查看数据集的特征名称
print(boston.data.shape) # 查看数据集的数据维度
```
3. 数据预处理
```python
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
# 划分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(boston.data, boston.target, test_size=0.2, random_state=42)
# 特征标准化
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
```
4. 构建模型
```python
from sklearn.linear_model import LinearRegression
# 构建线性回归模型
model = LinearRegression()
# 训练模型
model.fit(X_train_scaled, y_train)
# 预测测试集结果
y_pred = model.predict(X_test_scaled)
```
5. 模型评估
```python
from sklearn.metrics import mean_squared_error, r2_score
# 计算均方误差
mse = mean_squared_error(y_test, y_pred)
# 计算R2系数
r2 = r2_score(y_test, y_pred)
print('均方误差:', mse)
print('R2系数:', r2)
```
6. 可视化结果
```python
import matplotlib.pyplot as plt
# 绘制预测值和真实值的散点图
plt.scatter(y_test, y_pred)
plt.xlabel('True Values')
plt.ylabel('Predictions')
plt.show()
```
sklearn鸢尾花数据集三维图
要绘制sklearn鸢尾花数据集的三维图,你需要使用matplotlib和mpl_toolkits.mplot3d库。以下是一个简单的例子:
```python
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sklearn.datasets import load_iris
iris = load_iris()
X = iris.data
y = iris.target
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(X[:, 0], X[:, 1], X[:, 2], c=y)
ax.set_xlabel('Sepal length')
ax.set_ylabel('Sepal width')
ax.set_zlabel('Petal length')
plt.show()
```
这将绘制一个三维散点图,其中x,y和z轴分别表示萼片长度,萼片宽度和花瓣长度。每个数据点的颜色表示它所属的类别。