用sklearn实现线性回归和岭回归

此文为ai创作,今天写文章的时候发现创作助手限时免费,想测试一下,于是就有了这篇文章,看的出来,效果还可以,一行没改。

线性回归

在sklearn中,可以使用线性回归模型做多变量回归。下面是一个示例:

假设我们有以下数据集,其中X是输入特征,y是输出:

复制代码
X = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
y = [6, 15, 24, 33]

我们可以使用sklearn中的LinearRegression模型来训练一个多变量线性回归模型:

python 复制代码
from sklearn.linear_model import LinearRegression

# 创建线性回归模型对象
model = LinearRegression()

# 训练模型
model.fit(X, y)

# 预测
new_X = [[2, 4, 6], [3, 5, 7]]
predictions = model.predict(new_X)
print(predictions)

输出:

复制代码
[ 9. 12.]

这样,我们就得到了一个多变量回归模型,并使用新数据进行了预测。

岭回归

岭回归是一种线性回归算法,它通过L2正则化来解决过拟合问题。在sklearn中,可以使用Ridge类来实现岭回归。

下面是一个简单的例子:

python 复制代码
from sklearn.linear_model import Ridge
from sklearn.datasets import load_boston
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error

# 加载数据集
boston = load_boston()
X = boston.data
y = boston.target

# 划分数据集
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, random_state=42)

# 实例化岭回归模型,设置 alpha 值
ridge = Ridge(alpha=1.0)

# 训练模型
ridge.fit(X_train, y_train)

# 预测
y_pred = ridge.predict(X_test)

# 评估模型
mse = mean_squared_error(y_test, y_pred)
print("MSE:", mse)

在以上代码中,通过使用load_boston函数加载波士顿房价数据集,使用train_test_split将数据集拆分为训练集和测试集。然后,使用Ridge实例化岭回归模型,并将alpha值设置为1。最后,使用fit方法训练模型并使用predict方法进行预测。

以上是一个简单的岭回归实现。你可以根据自己的需要调整alpha值和其他参数来提高模型的性能。

相关推荐
花酒锄作田10 小时前
使用 pkgutil 实现动态插件系统
python
前端付豪14 小时前
LangChain链 写一篇完美推文?用SequencialChain链接不同的组件
人工智能·python·langchain
曲幽15 小时前
FastAPI实战:打造本地文生图接口,ollama+diffusers让AI绘画更听话
python·fastapi·web·cors·diffusers·lcm·ollama·dreamshaper8·txt2img
老赵全栈实战15 小时前
Pydantic配置管理最佳实践(一)
python
阿尔的代码屋21 小时前
[大模型实战 07] 基于 LlamaIndex ReAct 框架手搓全自动博客监控 Agent
人工智能·python
AI探索者2 天前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者2 天前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh2 天前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅2 天前
Python函数入门详解(定义+调用+参数)
python
曲幽2 天前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama