用python先生成随机数据利用seed=207再定义函数再建立数据模型再利用训练集训练模型再使用R2对回归模型进行评价再利用python实现线性回归估计方程再可视化显示

时间: 2024-05-15 17:19:50 浏览: 8
生成随机数据: ```python import numpy as np np.random.seed(207) # 设置随机数种子,保证结果可重现 # 生成随机数据,x为输入,y为输出 x = np.random.rand(100, 1) y = 2 * x + 3 + 0.2 * np.random.randn(100, 1) ``` 定义函数: ```python def linear_regression(x, y): """ 线性回归模型 :param x: 输入,形状为(n_samples, n_features) :param y: 输出,形状为(n_samples, 1) :return: 模型参数,形状为(n_features + 1, 1) """ n_samples, n_features = x.shape x = np.concatenate([x, np.ones((n_samples, 1))], axis=1) # 添加偏置项 # 计算模型参数 w = np.linalg.inv(x.T @ x) @ x.T @ y return w ``` 建立数据模型: ```python w = linear_regression(x, y) ``` 使用训练集训练模型: ```python # 划分训练集和测试集 from sklearn.model_selection import train_test_split x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=42) # 训练模型 w_train = linear_regression(x_train, y_train) ``` 使用R2对回归模型进行评价: ```python from sklearn.metrics import r2_score y_pred = x_test @ w_train[:-1] + w_train[-1] # 预测输出 r2 = r2_score(y_test, y_pred) # 计算R2分数 print("R2 score:", r2) ``` 使用python实现线性回归估计方程: ```python print("估计方程:y = {:.2f}x + {:.2f}".format(w_train[0, 0], w_train[1, 0])) ``` 可视化显示: ```python import matplotlib.pyplot as plt # 绘制训练集散点图 plt.scatter(x_train, y_train, color='blue', label='train data') # 绘制拟合直线 x_min, x_max = x_train.min(), x_train.max() y_min, y_max = x_min * w_train[0, 0] + w_train[1, 0], x_max * w_train[0, 0] + w_train[1, 0] plt.plot([x_min, x_max], [y_min, y_max], color='red', label='fitting line') # 添加标签和标题 plt.xlabel('x') plt.ylabel('y') plt.title('Linear Regression') plt.legend() plt.show() ```

相关推荐

以下这段代码是关于CatBoost模型的超参数调整,但里面好像不是在五倍交叉验证下做的分析,请问应该怎么加上五倍交叉验证呢?import os import time import pandas as pd from catboost import CatBoostRegressor from hyperopt import fmin, hp, partial, Trials, tpe,rand from sklearn.metrics import r2_score, mean_squared_error from sklearn.model_selection import train_test_split from sklearn.model_selection import KFold, cross_val_score as CVS, train_test_split as TTS 自定义hyperopt的参数空间 space = {"iterations": hp.choice("iterations", range(1, 30)), "depth": hp.randint("depth", 16), "l2_leaf_reg": hp.randint("l2_leaf_reg", 222), "border_count": hp.randint("border_count", 222), 'learning_rate': hp.uniform('learning_rate', 0.001, 0.9), } data = pd.read_csv(r"E:\exercise\synthesis\synthesis_dummy_2.csv") #验证随机森林填补缺失值方法是否有效 X = data.iloc[:,1:] y = data.iloc[:,0] Xtrain,Xtest,Ytrain,Ytest = TTS(X_wrapper,y,test_size=0.2,random_state=100) def epoch_time(start_time, end_time): elapsed_secs = end_time - start_time elapsed_mins = elapsed_secs / 60 return elapsed_mins, elapsed_secs 自动化调参并训练 def cat_factory(argsDict): estimator = CatBoostRegressor(loss_function='RMSE', random_seed=22, learning_rate=argsDict['learning_rate'], iterations=argsDict['iterations'], l2_leaf_reg=argsDict['l2_leaf_reg'], border_count=argsDict['border_count'], depth=argsDict['depth'], verbose=0) estimator.fit(Xtrain, Ytrain) val_pred = estimator.predict(Xtest) mse = mean_squared_error(Ytest, val_pred) return mse

最新推荐

recommend-type

Python利用逻辑回归模型解决MNIST手写数字识别问题详解

主要介绍了Python利用逻辑回归模型解决MNIST手写数字识别问题,结合实例形式详细分析了Python MNIST手写识别问题原理及逻辑回归模型解决MNIST手写识别问题相关操作技巧,需要的朋友可以参考下
recommend-type

python 对任意数据和曲线进行拟合并求出函数表达式的三种解决方案

主要介绍了python 对任意数据和曲线进行拟合并求出函数表达式的三种解决方案,本文通过实例代码给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下
recommend-type

BERT预训练模型字向量提取工具–使用BERT编码句子

本工具直接读取BERT预训练模型,从中提取样本文件中所有使用到字向量,保存成向量文件,为后续模型提供embdding。 本工具直接读取预训练模型,不需要其它的依赖,同时把样本中所有 出现的字符对应的字向量全部提取,...
recommend-type

利用Python+matplotlib对泰坦尼克号进行数据分析

主要分析有数据接:https://pan.baidu.com/s/1jn88GiOr7uWA8BDQocFXxg 密码: s0e0不同舱位等级中幸存者和遇难者的乘客比例不同性别的幸存比例幸存和遇难...首先做准备(导入库,读入数据集) import matplotlib.pypl
recommend-type

python3利用Axes3D库画3D模型图

主要为大家详细介绍了python3利用Axes3D库画3D模型图,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
recommend-type

zigbee-cluster-library-specification

最新的zigbee-cluster-library-specification说明文档。
recommend-type

管理建模和仿真的文件

管理Boualem Benatallah引用此版本:布阿利姆·贝纳塔拉。管理建模和仿真。约瑟夫-傅立叶大学-格勒诺布尔第一大学,1996年。法语。NNT:电话:00345357HAL ID:电话:00345357https://theses.hal.science/tel-003453572008年12月9日提交HAL是一个多学科的开放存取档案馆,用于存放和传播科学研究论文,无论它们是否被公开。论文可以来自法国或国外的教学和研究机构,也可以来自公共或私人研究中心。L’archive ouverte pluridisciplinaire
recommend-type

MATLAB柱状图在信号处理中的应用:可视化信号特征和频谱分析

![matlab画柱状图](https://img-blog.csdnimg.cn/3f32348f1c9c4481a6f5931993732f97.png) # 1. MATLAB柱状图概述** MATLAB柱状图是一种图形化工具,用于可视化数据中不同类别或组的分布情况。它通过绘制垂直条形来表示每个类别或组中的数据值。柱状图在信号处理中广泛用于可视化信号特征和进行频谱分析。 柱状图的优点在于其简单易懂,能够直观地展示数据分布。在信号处理中,柱状图可以帮助工程师识别信号中的模式、趋势和异常情况,从而为信号分析和处理提供有价值的见解。 # 2. 柱状图在信号处理中的应用 柱状图在信号处理
recommend-type

HSV转为RGB的计算公式

HSV (Hue, Saturation, Value) 和 RGB (Red, Green, Blue) 是两种表示颜色的方式。下面是将 HSV 转换为 RGB 的计算公式: 1. 将 HSV 中的 S 和 V 值除以 100,得到范围在 0~1 之间的值。 2. 计算色相 H 在 RGB 中的值。如果 H 的范围在 0~60 或者 300~360 之间,则 R = V,G = (H/60)×V,B = 0。如果 H 的范围在 60~120 之间,则 R = ((120-H)/60)×V,G = V,B = 0。如果 H 的范围在 120~180 之间,则 R = 0,G = V,B =
recommend-type

JSBSim Reference Manual

JSBSim参考手册,其中包含JSBSim简介,JSBSim配置文件xml的编写语法,编程手册以及一些应用实例等。其中有部分内容还没有写完,估计有生之年很难看到完整版了,但是内容还是很有参考价值的。