国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

使用自己的數(shù)據(jù)利用pytorch搭建全連接神經(jīng)網(wǎng)絡(luò)進行回歸預(yù)測

這篇具有很好參考價值的文章主要介紹了使用自己的數(shù)據(jù)利用pytorch搭建全連接神經(jīng)網(wǎng)絡(luò)進行回歸預(yù)測。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點擊"舉報違法"按鈕提交疑問。

1、導(dǎo)入庫

引入必要的庫,包括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_housing

import 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、數(shù)據(jù)準備

這里使用sklearn自帶的加利福尼亞房價數(shù)據(jù),首次運行會下載數(shù)據(jù)集,建議下載之后,處理成csv格式單獨保存,再重新讀取。

后續(xù)完整代碼中,數(shù)據(jù)也是采用先下載,單獨保存之后,再重新讀取的方式。文章來源地址http://www.zghlxwxcb.cn/news/detail-641643.html

# 導(dǎo)入數(shù)據(jù)
housedata = fetch_california_housing()  # 首次運行會下載數(shù)據(jù)集
data_x, data_y = housedata.data, housedata.target  # 讀取數(shù)據(jù)和標簽
data_df = pd.DataFrame(data=data_x, columns=housedata.feature_names)  # 將數(shù)據(jù)處理成dataframe格式
data_df['target'] = data_y  # 添加標簽列
data_df.to_csv("california_housing.csv")  # 將數(shù)據(jù)輸出為CSV文件
housedata_df = pd.read_csv("california_housing.csv")  # 重新讀取數(shù)據(jù)

3、數(shù)據(jù)拆分

# 切分訓(xùn)練集和測試集
X_train, X_test, y_train, y_test = train_test_split(housedata[:, :-1], housedata[:, -1],test_size=0.3, random_state=42)

4、數(shù)據(jù)標準化

# 數(shù)據(jù)標準化處理
scale = StandardScaler()
x_train_std = scale.fit_transform(X_train)
x_test_std = scale.transform(X_test)

5、數(shù)據(jù)轉(zhuǎn)換

# 將數(shù)據(jù)集轉(zhuǎn)為張量
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))

# 將訓(xùn)練數(shù)據(jù)處理為數(shù)據(jù)加載器
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、模型搭建

# 搭建全連接神經(jīng)網(wǎng)絡(luò)回歸
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)
        # 回歸預(yù)測層
        self.predict = nn.Linear(50, 1)

    # 定義網(wǎng)絡(luò)前向傳播路徑
    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、模型訓(xùn)練

# 定義優(yōu)化器
optimizer = torch.optim.SGD(testnet.parameters(), lr=0.01)
loss_func = nn.MSELoss()  # 均方根誤差損失函數(shù)
train_loss_all = []

# 對模型迭代訓(xùn)練,總共epoch輪
for epoch in range(30):
    train_loss = 0
    train_num = 0
    # 對訓(xùn)練數(shù)據(jù)的加載器進行迭代計算
    for step, (b_x, b_y) in enumerate(train_loader):
        output = testnet(b_x)  # MLP在訓(xùn)練batch上的輸出
        loss = loss_func(output, b_y)  # 均方根損失函數(shù)
        optimizer.zero_grad()  # 每次迭代梯度初始化0
        loss.backward()  # 反向傳播,計算梯度
        optimizer.step()  # 使用梯度進行優(yōu)化
        train_loss += loss.item() * b_x.size(0)
        train_num += b_x.size(0)
    train_loss_all.append(train_loss / train_num)

8、模型預(yù)測

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.py

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_housing

import 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


# 搭建全連接神經(jīng)網(wǎng)絡(luò)回歸
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)
        # 回歸預(yù)測層
        self.predict = nn.Linear(50, 1)

    # 定義網(wǎng)絡(luò)前向傳播路徑
    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]


# 導(dǎo)入數(shù)據(jù)
housedata_df = pd.read_csv("california_housing.csv")
housedata = housedata_df.values
# 切分訓(xùn)練集和測試集
X_train, X_test, y_train, y_test = train_test_split(housedata[:, :-1], housedata[:, -1],test_size=0.3, random_state=42)

# 數(shù)據(jù)標準化處理
scale = StandardScaler()
x_train_std = scale.fit_transform(X_train)
x_test_std = scale.transform(X_test)

# 將訓(xùn)練數(shù)據(jù)轉(zhuǎn)為數(shù)據(jù)表
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()

# 將數(shù)據(jù)集轉(zhuǎn)為張量
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))

# 將訓(xùn)練數(shù)據(jù)處理為數(shù)據(jù)加載器
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)

# 輸出網(wǎng)絡(luò)結(jié)構(gòu)
testnet = FNN_Regression()
summary(testnet, input_size=(1, 8))  # 表示1個樣本,每個樣本有8個特征

# 輸出網(wǎng)絡(luò)結(jié)構(gòu)
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)]))

# 定義優(yōu)化器
optimizer = torch.optim.SGD(testnet.parameters(), lr=0.01)
loss_func = nn.MSELoss()  # 均方根誤差損失函數(shù)
train_loss_all = []

# 對模型迭代訓(xùn)練,總共epoch輪
for epoch in range(30):
    train_loss = 0
    train_num = 0
    # 對訓(xùn)練數(shù)據(jù)的加載器進行迭代計算
    for step, (b_x, b_y) in enumerate(train_loader):
        output = testnet(b_x)  # MLP在訓(xùn)練batch上的輸出
        loss = loss_func(output, b_y)  # 均方根損失函數(shù)
        optimizer.zero_grad()  # 每次迭代梯度初始化0
        loss.backward()  # 反向傳播,計算梯度
        optimizer.step()  # 使用梯度進行優(yōu)化
        train_loss += loss.item() * b_x.size(0)
        train_num += b_x.size(0)
    train_loss_all.append(train_loss / train_num)

# 可視化訓(xùn)練損失函數(shù)的變換情況
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)

# 可視化測試數(shù)據(jù)的擬合情況
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()

到了這里,關(guān)于使用自己的數(shù)據(jù)利用pytorch搭建全連接神經(jīng)網(wǎng)絡(luò)進行回歸預(yù)測的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實不符,請點擊違法舉報進行投訴反饋,一經(jīng)查實,立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費用

相關(guān)文章

  • 【PyTorch框架】——框架安裝&使用流程&搭建PyTorch神經(jīng)網(wǎng)絡(luò)氣溫預(yù)測

    【PyTorch框架】——框架安裝&使用流程&搭建PyTorch神經(jīng)網(wǎng)絡(luò)氣溫預(yù)測

    目錄 一、引言 二、使用流程——最簡單例子試手 三、分類任務(wù)——氣溫預(yù)測 ? 總結(jié): Torch可以當作是能在GPU中計算的矩陣,就是ndarray的GPU版!TensorFlow和PyTorch可以說是當今最流行的框架!PyTorch用起來簡單,好用!而TensoFlow用起來沒那么自由!caffe比較老,不可處理文本數(shù)據(jù)

    2024年02月05日
    瀏覽(22)
  • Pytorch:手把手教你搭建簡單的全連接網(wǎng)絡(luò)

    Pytorch:手把手教你搭建簡單的全連接網(wǎng)絡(luò)

    ?紅色的點就是我在sinx函數(shù)上取的已知點作為網(wǎng)絡(luò)的訓(xùn)練點。 ?訓(xùn)練過程如上,時間我這里設(shè)置的比較簡單,除了分鐘,之后的時間沒有按照60進制規(guī)定。 可以看到收斂的還是比較好的。 這里紅色的點為訓(xùn)練用的數(shù)據(jù),藍色為我們的預(yù)測曲線,可以看到整體上擬合的是比較好

    2024年02月07日
    瀏覽(25)
  • 學(xué)習(xí)pytorch13 神經(jīng)網(wǎng)絡(luò)-搭建小實戰(zhàn)&Sequential的使用

    學(xué)習(xí)pytorch13 神經(jīng)網(wǎng)絡(luò)-搭建小實戰(zhàn)&Sequential的使用

    B站小土堆pytorch視頻學(xué)習(xí) https://pytorch.org/docs/stable/generated/torch.nn.Sequential.html#torch.nn.Sequential sequential 將模型結(jié)構(gòu)組合起來 以逗號分割,按順序執(zhí)行,和compose使用方式類似。 箭頭指向部分還需要一層flatten層,展開輸入shape為一維 tensorboard 展示圖文件, 雙擊每層網(wǎng)絡(luò),可查看層

    2024年02月07日
    瀏覽(21)
  • PyTorch入門學(xué)習(xí)(十二):神經(jīng)網(wǎng)絡(luò)-搭建小實戰(zhàn)和Sequential的使用

    目錄 一、介紹 二、先決條件 三、代碼解釋 一、介紹 在深度學(xué)習(xí)領(lǐng)域,構(gòu)建復(fù)雜的神經(jīng)網(wǎng)絡(luò)模型可能是一項艱巨的任務(wù),尤其是當您有許多層和操作需要組織時。幸運的是,PyTorch提供了一個方便的工具,稱為Sequential API,它簡化了神經(jīng)網(wǎng)絡(luò)架構(gòu)的構(gòu)建過程。在本文中,將探

    2024年02月05日
    瀏覽(18)
  • 人工智能(pytorch)搭建模型12-pytorch搭建BiGRU模型,利用正態(tài)分布數(shù)據(jù)訓(xùn)練該模型

    人工智能(pytorch)搭建模型12-pytorch搭建BiGRU模型,利用正態(tài)分布數(shù)據(jù)訓(xùn)練該模型

    大家好,我是微學(xué)AI,今天給大家介紹一下人工智能(pytorch)搭建模型12-pytorch搭建BiGRU模型,利用正態(tài)分布數(shù)據(jù)訓(xùn)練該模型。本文將介紹一種基于PyTorch的BiGRU模型應(yīng)用項目。我們將首先解釋BiGRU模型的原理,然后使用PyTorch搭建模型,并提供模型代碼和數(shù)據(jù)樣例。接下來,我們將

    2024年02月09日
    瀏覽(91)
  • 【PyTorch】使用PyTorch創(chuàng)建卷積神經(jīng)網(wǎng)絡(luò)并在CIFAR-10數(shù)據(jù)集上進行分類

    【PyTorch】使用PyTorch創(chuàng)建卷積神經(jīng)網(wǎng)絡(luò)并在CIFAR-10數(shù)據(jù)集上進行分類

    在深度學(xué)習(xí)的世界中,圖像分類任務(wù)是一個經(jīng)典的問題,它涉及到識別給定圖像中的對象類別。CIFAR-10數(shù)據(jù)集是一個常用的基準數(shù)據(jù)集,包含了10個類別的60000張32x32彩色圖像。在本博客中,我們將探討如何使用PyTorch框架創(chuàng)建一個簡單的卷積神經(jīng)網(wǎng)絡(luò)(CNN)來對CIFAR-10數(shù)據(jù)集中

    2024年01月24日
    瀏覽(32)
  • 使用pytorch處理自己的數(shù)據(jù)集

    使用pytorch處理自己的數(shù)據(jù)集

    目錄 1 返回本地文件中的數(shù)據(jù)集 2 根據(jù)當前已有的數(shù)據(jù)集創(chuàng)建每一個樣本數(shù)據(jù)對應(yīng)的標簽 3 tensorboard的使用 4 transforms處理數(shù)據(jù) tranfroms.Totensor的使用 transforms.Normalize的使用 transforms.Resize的使用 transforms.Compose使用 5 dataset_transforms使用 1 返回本地文件中的數(shù)據(jù)集 在這個操作中,當

    2024年02月06日
    瀏覽(21)
  • 【Pytorch】神經(jīng)網(wǎng)絡(luò)搭建

    【Pytorch】神經(jīng)網(wǎng)絡(luò)搭建

    在之前我們學(xué)習(xí)了如何用Pytorch去導(dǎo)入我們的數(shù)據(jù)和數(shù)據(jù)集,并且對數(shù)據(jù)進行預(yù)處理。接下來我們就需要學(xué)習(xí)如何利用Pytorch去構(gòu)建我們的神經(jīng)網(wǎng)絡(luò)了。 目錄 基本網(wǎng)絡(luò)框架Module搭建 卷積層 從conv2d方法了解原理 從Conv2d方法了解使用 池化層 填充層 非線性層 線性層 Pytorch里面有一

    2023年04月17日
    瀏覽(19)
  • 人工智能(pytorch)搭建模型10-pytorch搭建脈沖神經(jīng)網(wǎng)絡(luò)(SNN)實現(xiàn)及應(yīng)用

    人工智能(pytorch)搭建模型10-pytorch搭建脈沖神經(jīng)網(wǎng)絡(luò)(SNN)實現(xiàn)及應(yīng)用

    大家好,我是微學(xué)AI,今天給大家介紹一下人工智能(pytorch)搭建模型10-pytorch搭建脈沖神經(jīng)網(wǎng)絡(luò)(SNN)實現(xiàn)及應(yīng)用,脈沖神經(jīng)網(wǎng)絡(luò)(SNN)是一種基于生物神經(jīng)系統(tǒng)的神經(jīng)網(wǎng)絡(luò)模型,它通過模擬神經(jīng)元之間的電信號傳遞來實現(xiàn)信息處理。與傳統(tǒng)的人工神經(jīng)網(wǎng)絡(luò)(ANN)不同,SNN 中的

    2024年02月08日
    瀏覽(95)
  • PyTorch 神經(jīng)網(wǎng)絡(luò)搭建模板

    在 PyTorch 中, Dataset 和 DataLoader 是用來處理數(shù)據(jù)的重要工具。它們的作用分別如下: Dataset : Dataset 用于存儲數(shù)據(jù)樣本及其對應(yīng)的標簽。在使用神經(jīng)網(wǎng)絡(luò)訓(xùn)練時,通常需要將原始數(shù)據(jù)集轉(zhuǎn)換為 Dataset 對象,以便能夠通過 DataLoader 進行批量讀取數(shù)據(jù),同時也可以方便地進行數(shù)據(jù)

    2023年04月08日
    瀏覽(16)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包