python实现线性回归模型鸢尾花
时间: 2023-09-09 15:09:52 浏览: 179
鸢尾花线性回归+鸢尾花数据集 Python实现
以下是一个使用Python实现线性回归模型的示例,用于预测鸢尾花的花瓣长度。
首先,我们需要导入必要的库。
```python
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
```
然后,我们加载鸢尾花数据集。
```python
iris = load_iris()
X = iris.data[:,2].reshape(-1, 1) # 花瓣长度
y = iris.target
```
接下来,我们将数据集分为训练集和测试集。
```python
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
```
我们使用线性回归模型对训练集进行拟合。
```python
model = LinearRegression()
model.fit(X_train, y_train)
```
现在,我们可以使用模型对测试集进行预测并计算其准确性。
```python
y_pred = model.predict(X_test)
accuracy = model.score(X_test, y_test)
print("准确率:", accuracy)
```
最后,我们可以使用训练好的模型对新的数据进行预测。
```python
new_data = np.array([1.5]).reshape(-1, 1)
prediction = model.predict(new_data)
print("预测值:", prediction)
```
完整代码如下:
```python
import numpy as np
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split
iris = load_iris()
X = iris.data[:,2].reshape(-1, 1) # 花瓣长度
y = iris.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
model = LinearRegression()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
accuracy = model.score(X_test, y_test)
print("准确率:", accuracy)
new_data = np.array([1.5]).reshape(-1, 1)
prediction = model.predict(new_data)
print("预测值:", prediction)
```
阅读全文