Iris -- 线性回归模型

Iris 数据含有两类数据,其中萼片长、萼片宽、花瓣长、花瓣宽为连续性数据。鸢尾花的种类为分类型数据。

下面是简单的计算并分析(花瓣长与萼片长)。
数据量较小,无缺失值、异常值等,因此未作相关的预处理。

鸢尾花数据节选

import numpy as np
from sklearn import linear_model 
vir_x = vir.iloc[:,0:1] #萼片长
vir_y = vir["花瓣长"]

#线性回归
reg = linear_model.LinearRegression() 
#拟合数据
reg.fit(vir_x,vir_y)
#R²
reg.score(vir_x,vir_y)

计算得出R² = 0.746,说明花瓣长于萼片长相关性较高。

做一个简单绘图

import matplotlib.pyplot as plt

plt.subplots(1,2,figsize =(12,8))

plt.subplot(121)
r2 = reg.score(vir_x,vir_y);
plt.plot(vir_y,reg.predict(vir_x),"o",label = r2)
plt.legend()

plt.subplot(122)
#计算残差
resid = vir_y -reg.predict(vir_x)
#将残差进行标准化处理
z_resid = (resid - np.mean(resid))/np.std(resid)
plt.plot(reg.predict(vir_x),z_resid,"o",label = "残差图")
plt.legend()

绘图如下:
在这里插入图片描述
鸢尾花的数据来源于:鸢尾花

以下是一个使用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) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值