使用自己的数据利用pytorch搭建全连接神经网络进行回归预测

使用自己的数据利用pytorch搭建全连接神经网络进行回归预测

  • 1、导入库
  • 2、数据准备
  • 3、数据拆分
  • 4、数据标准化
  • 5、数据转换
  • 6、模型搭建
  • 7、模型训练
  • 8、模型预测
  • 9、完整代码

1、导入库

引入必要的库,包括PyTorch、Pandas等。

import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, mean_absolute_error
from sklearn.datasets import fetch_california_housingimport torch
import torch.nn as nn
import torch.nn.functional as F
from torch.optim import SGD
import torch.utils.data as Data
import matplotlib.pyplot as plt
import seaborn as sns

2、数据准备

这里使用sklearn自带的加利福尼亚房价数据,首次运行会下载数据集,建议下载之后,处理成csv格式单独保存,再重新读取。

后续完整代码中,数据也是采用先下载,单独保存之后,再重新读取的方式。

# 导入数据
housedata = fetch_california_housing()  # 首次运行会下载数据集
data_x, data_y = housedata.data, housedata.target  # 读取数据和标签
data_df = pd.DataFrame(data=data_x, columns=housedata.feature_names)  # 将数据处理成dataframe格式
data_df['target'] = data_y  # 添加标签列
data_df.to_csv("california_housing.csv")  # 将数据输出为CSV文件
housedata_df = pd.read_csv("california_housing.csv")  # 重新读取数据

3、数据拆分

# 切分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(housedata[:, :-1], housedata[:, -1],test_size=0.3, random_state=42)

4、数据标准化

# 数据标准化处理
scale = StandardScaler()
x_train_std = scale.fit_transform(X_train)
x_test_std = scale.transform(X_test)

5、数据转换

# 将数据集转为张量
X_train_t = torch.from_numpy(x_train_std.astype(np.float32))
y_train_t = torch.from_numpy(y_train.astype(np.float32))
X_test_t = torch.from_numpy(x_test_std.astype(np.float32))
y_test_t = torch.from_numpy(y_test.astype(np.float32))# 将训练数据处理为数据加载器
train_data = Data.TensorDataset(X_train_t, y_train_t)
test_data = Data.TensorDataset(X_test_t, y_test_t)
train_loader = Data.DataLoader(dataset=train_data, batch_size=64, shuffle=True, num_workers=1)

6、模型搭建

# 搭建全连接神经网络回归
class FNN_Regression(nn.Module):def __init__(self):super(FNN_Regression, self).__init__()# 第一个隐含层self.hidden1 = nn.Linear(in_features=8, out_features=100, bias=True)# 第二个隐含层self.hidden2 = nn.Linear(100, 100)# 第三个隐含层self.hidden3 = nn.Linear(100, 50)# 回归预测层self.predict = nn.Linear(50, 1)# 定义网络前向传播路径def forward(self, x):x = F.relu(self.hidden1(x))x = F.relu(self.hidden2(x))x = F.relu(self.hidden3(x))output = self.predict(x)# 输出一个一维向量return output[:, 0]

7、模型训练

# 定义优化器
optimizer = torch.optim.SGD(testnet.parameters(), lr=0.01)
loss_func = nn.MSELoss()  # 均方根误差损失函数
train_loss_all = []# 对模型迭代训练,总共epoch轮
for epoch in range(30):train_loss = 0train_num = 0# 对训练数据的加载器进行迭代计算for step, (b_x, b_y) in enumerate(train_loader):output = testnet(b_x)  # MLP在训练batch上的输出loss = loss_func(output, b_y)  # 均方根损失函数optimizer.zero_grad()  # 每次迭代梯度初始化0loss.backward()  # 反向传播,计算梯度optimizer.step()  # 使用梯度进行优化train_loss += loss.item() * b_x.size(0)train_num += b_x.size(0)train_loss_all.append(train_loss / train_num)

8、模型预测

y_pre = testnet(X_test_t)
y_pre = y_pre.data.numpy()
mae = mean_absolute_error(y_test, y_pre)
print('在测试集上的绝对值误差为:', mae)

9、完整代码

# -*- coding: utf-8 -*-
# @Time : 2023/8/11 15:58
# @Author : huangjian
# @Email : huangjian013@126.com
# @File : FNN_demo.pyimport numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, mean_absolute_error
from sklearn.datasets import fetch_california_housingimport torch
import torch.nn as nn
import torch.nn.functional as F
from torch.optim import SGD
import torch.utils.data as Data
from torchsummary import summary
from torchviz import make_dot
import matplotlib.pyplot as plt
import seaborn as sns# 搭建全连接神经网络回归
class FNN_Regression(nn.Module):def __init__(self):super(FNN_Regression, self).__init__()# 第一个隐含层self.hidden1 = nn.Linear(in_features=8, out_features=100, bias=True)# 第二个隐含层self.hidden2 = nn.Linear(100, 100)# 第三个隐含层self.hidden3 = nn.Linear(100, 50)# 回归预测层self.predict = nn.Linear(50, 1)# 定义网络前向传播路径def forward(self, x):x = F.relu(self.hidden1(x))x = F.relu(self.hidden2(x))x = F.relu(self.hidden3(x))output = self.predict(x)# 输出一个一维向量return output[:, 0]# 导入数据
housedata_df = pd.read_csv("california_housing.csv")
housedata = housedata_df.values
# 切分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(housedata[:, :-1], housedata[:, -1],test_size=0.3, random_state=42)# 数据标准化处理
scale = StandardScaler()
x_train_std = scale.fit_transform(X_train)
x_test_std = scale.transform(X_test)# 将训练数据转为数据表
datacor = np.corrcoef(housedata_df.values, rowvar=0)
datacor = pd.DataFrame(data=datacor, columns=housedata_df.columns, index=housedata_df.columns)
plt.figure(figsize=(8, 6))
ax = sns.heatmap(datacor, square=True, annot=True, fmt='.3f', linewidths=.5, cmap='YlGnBu',cbar_kws={'fraction': 0.046, 'pad': 0.03})
plt.show()# 将数据集转为张量
X_train_t = torch.from_numpy(x_train_std.astype(np.float32))
y_train_t = torch.from_numpy(y_train.astype(np.float32))
X_test_t = torch.from_numpy(x_test_std.astype(np.float32))
y_test_t = torch.from_numpy(y_test.astype(np.float32))# 将训练数据处理为数据加载器
train_data = Data.TensorDataset(X_train_t, y_train_t)
test_data = Data.TensorDataset(X_test_t, y_test_t)
train_loader = Data.DataLoader(dataset=train_data, batch_size=64, shuffle=True, num_workers=1)# 输出网络结构
testnet = FNN_Regression()
summary(testnet, input_size=(1, 8))  # 表示1个样本,每个样本有8个特征# 输出网络结构
testnet = FNN_Regression()
x = torch.randn(1, 8).requires_grad_(True)
y = testnet(x)
myMLP_vis = make_dot(y, params=dict(list(testnet.named_parameters()) + [('x', x)]))# 定义优化器
optimizer = torch.optim.SGD(testnet.parameters(), lr=0.01)
loss_func = nn.MSELoss()  # 均方根误差损失函数
train_loss_all = []# 对模型迭代训练,总共epoch轮
for epoch in range(30):train_loss = 0train_num = 0# 对训练数据的加载器进行迭代计算for step, (b_x, b_y) in enumerate(train_loader):output = testnet(b_x)  # MLP在训练batch上的输出loss = loss_func(output, b_y)  # 均方根损失函数optimizer.zero_grad()  # 每次迭代梯度初始化0loss.backward()  # 反向传播,计算梯度optimizer.step()  # 使用梯度进行优化train_loss += loss.item() * b_x.size(0)train_num += b_x.size(0)train_loss_all.append(train_loss / train_num)# 可视化训练损失函数的变换情况
plt.figure(figsize=(8, 6))
plt.plot(train_loss_all, 'ro-', label='Train loss')
plt.legend()
plt.grid()
plt.xlabel('epoch')
plt.ylabel('Loss')
plt.show()y_pre = testnet(X_test_t)
y_pre = y_pre.data.numpy()
mae = mean_absolute_error(y_test, y_pre)
print('在测试集上的绝对值误差为:', mae)# 可视化测试数据的拟合情况
index = np.argsort(y_test)
plt.figure(figsize=(8, 6))
plt.plot(np.arange(len(y_test)), y_test[index], 'r', label='Original Y')
plt.scatter(np.arange(len(y_pre)), y_pre[index], s=3, c='b', label='Prediction')
plt.legend(loc='upper left')
plt.grid()
plt.xlabel('Index')
plt.ylabel('Y')
plt.show()

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/38018.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

tp6 RabbitMQ

1、composer 安装 AMQP 扩展 composer require php-amqplib/php-amqplib 2、RabbitMQ 配置 在 config 目录下创建 rabbitmq.php 文件 <?php return [host>,port>5672,user>,password>,vhost>,exchange_name > ,queue_name > ,route_key > ,cons…

中国生产了5.07亿台,库存高达近4亿台?国产手机彻底卖不动了?

统计数据显示今年上半年中国的手机产量达到5.07亿台&#xff0c;国内市场手机出货量仅有1.24亿台&#xff0c;都出现了下滑&#xff0c;那么中国手机的产量比销量多出了3.83亿台&#xff0c;这些手机都成为了库存&#xff1f; 中国手机市场确实不如早年那么辉煌&#xff0c;201…

【FAQ】安防监控视频EasyCVR平台分发的FLV视频流在VLC中无法播放

众所周知&#xff0c;TSINGSEE青犀视频汇聚平台EasyCVR可支持多协议方式接入&#xff0c;包括主流标准协议国标GB28181、RTSP/Onvif、RTMP等&#xff0c;以及厂家私有协议与SDK接入&#xff0c;包括海康Ehome、海大宇等设备的SDK等。在视频流的处理与分发上&#xff0c;视频监控…

P12-Retentive NetWork-RetNet挑战Transformer

论文地址:https://arxiv.org/abs/2307.08621 目录 Abstract 一.Introduction 二.Retentive Networks 2.1Retention 2.2Gated Multi-Scale Retention 2.3Overall Architecture of Retention Networks 2.4Relation to and Differences from Previous Methods 三.Experime…

Codeforces Round 892 (Div. 2)(VP)

A //b里放最小值&#xff0c;其他值放c。如果最大值最小值&#xff0c;则无解。 void solve() {int n; cin >> n;vi a(n); liter(x, a) cin >> x; sort(all(a));if (a[0] a[n - 1]){print(-1); return;}vi b, c;for (int i 0; i < sz(a); i){if (a[i] a[0])…

小米基于 Flink 的实时计算资源治理实践

摘要&#xff1a;本文整理自小米高级软件工程师张蛟&#xff0c;在 Flink Forward Asia 2022 生产实践专场的分享。本篇内容主要分为四个部分&#xff1a; 发展现状与规模框架层治理实践平台层治理实践未来规划与展望 点击查看原文视频 & 演讲PPT 一、发展现状与规模 如上图…

【03】基础知识:typescript中的函数

一、typescript 中定义函数的方法 函数声明法 function test1(): string {return 返回类型为string }function test2(): void {console.log(没有返回值的方法) }函数表达式/匿名函数 const test3 function(): number {return 1 }二、typescript 中 函数参数写法 1、typesc…

helm安装harbor + nerdctl 制作push 镜像

参考 文章&#xff1a;Helm部署Harbor_helm harbor_风向决定发型丶的博客-CSDN博客 安装好后使用 nerd containerd对接harbor_containerd 容器 insecure-registries 配置_柠是柠檬的檬的博客-CSDN博客 推送镜像 Containerd 对接私有镜像仓库 Harbor - 知乎 接下来我们来…

麒麟系统相关

创建虚拟机 镜像下载地址 选择合适的镜像&#xff0c;进入引导后注意不要选择默认的第一条&#xff0c;选择第二条进入安装程序。 root密码修改 使用命令 sudo passwd root 开启ssh 配置好网络后发现能ping通&#xff0c;但无法ssh连接&#xff0c;ps -ef | grep ssh 得…

01 qt快速入门

一 qt介绍 1.基本概念 1991年由Qt Company(奇趣)开发的跨平台C++图形用户界面应用程序开发框架,GUI程序和非GUI程序。优点:一套源码在不同的平台通过不同的编译器进行编译,就可以运行到该平台上目标机。面向对象的封装机制来对其接口封装。 GUI —图形用户界面(Graphic…

软件测试面试题【2023整理版(含答案)】

01、您所熟悉的测试用例设计方法都有哪些&#xff1f;请分别以具体的例子来说明这些方法在测试用例设计工作中的应用。 答&#xff1a;有黑盒和白盒两种测试种类&#xff0c;黑盒有等价类划分方法 边界值分析方法 错误推测方法 因果图方法 判定表驱动分析方法 正交实验设…

Vue组件之间的传值汇总

组件之间的传值 1、父传子 props 2、父传子 slot 3、父传子 不建议用 attrs 4、 子传父 ref 5、子传父 emit 6、povide/inject只能在setup的时候用。 7、利用vuex和pinia去实现数据的交互 1、实现代码App.vue <script setup>import TestProps from ./components/T…

stable-diffusion 模型效果+prompt

摘自个人印象笔记&#xff0c;图不完整可查看原笔记&#xff1a;https://app.yinxiang.com/fx/55cda0c6-2af5-4d66-bd86-85da79c5574ePrompt运用规则及技巧 &#xff1a; 1. https://publicprompts.art/&#xff08;最适用于OpenArt 线上模型 https://openart.ai/&#xff09;…

【Vue-Router】别名

后台返回来的路径名不合理&#xff0c;但多个项目在使用中了&#xff0c;不方便改时可以使用别名。可以有多个或一个。 First.vue <template><h1>First Seciton</h1> </template>Second.vue&#xff0c;Third.vue代码同理 UserSettings.vue <tem…

R语言生存分析(机器学习)(2)——Enet(弹性网络)

弹性网络&#xff08;Elastic Net&#xff09;:是一种用于回归分析的统计方法&#xff0c;它是岭回归&#xff08;Ridge Regression&#xff09;和lasso回归&#xff08;Lasso Regression&#xff09;的结合&#xff0c;旨在克服它们各自的一些限制。弹性网络能够同时考虑L1正则…

mysql 索引 区分字符大小写

mysql 建立索引&#xff0c;特别是unique索引&#xff0c;是跟字符集、字符排序规则有关的。 对于utf8mb4_0900_ai_ci来说&#xff0c;0900代表Unicode 9.0的规范&#xff0c;ai表示accent insensitivity&#xff0c;也就是“不区分音调”&#xff0c;而ci表示case insensitiv…

wsl2安装docker引擎(Install Docker Engine on Debian)

安装 1.卸载旧版本 在安装 Docker 引擎之前&#xff0c;您必须首先确保卸载任何冲突的软件包。 发行版维护者在他们的存储库。必须先卸载这些软件包&#xff0c;然后才能安装 Docker 引擎的正式版本。 要卸载的非官方软件包是&#xff1a; docker.iodocker-composedocker-…

问道管理:旅游酒店板块逆市拉升,桂林旅游、华天酒店涨停

游览酒店板块14日盘中逆市拉升&#xff0c;到发稿&#xff0c;桂林游览、华天酒店涨停&#xff0c;张家界涨超8%&#xff0c;君亭酒店涨超5%&#xff0c;众信游览、云南游览涨逾4%。 音讯面上&#xff0c;8月10日&#xff0c;文旅部办公厅发布康复出境团队游览第三批名单&#…

Profibus-DP转modbus RTU网关modbus rtu和tcp的区别

捷米JM-DPM-RTU网关在Profibus总线侧实现主站功能&#xff0c;在Modbus串口侧实现从站功能。可将ProfibusDP协议的设备&#xff08;如&#xff1a;EH流量计、倍福编码器等&#xff09;接入到Modbus网络中&#xff1b;通过增加DP/PA耦合器&#xff0c;也可将Profibus PA从站接入…

【计算机网络】Udp详解

前言 上几文章我们讲解了应用层协议Http和Https&#xff0c;要知道应用层协议有很多&#xff0c;这些都是程序员自己定制的&#xff0c;而真正要传输的时候&#xff0c;是要在操作系统的传输层进行的&#xff0c;今天我们就来学习一下传输层协议Udp的 标识一个通信 要进行跨…