中文亚洲精品无码_熟女乱子伦免费_人人超碰人人爱国产_亚洲熟妇女综合网

當(dāng)前位置: 首頁 > news >正文

個人網(wǎng)站建立步驟網(wǎng)站外包

個人網(wǎng)站建立步驟,網(wǎng)站外包,專業(yè)的平面設(shè)計網(wǎng)站有哪些,怎么建設(shè)屬于自己的網(wǎng)站使用自己的數(shù)據(jù)利用pytorch搭建全連接神經(jīng)網(wǎng)絡(luò)進行回歸預(yù)測 1、導(dǎo)入庫2、數(shù)據(jù)準(zhǔn)備3、數(shù)據(jù)拆分4、數(shù)據(jù)標(biāo)準(zhǔn)化5、數(shù)據(jù)轉(zhuǎn)換6、模型搭建7、模型訓(xùn)練8、模型預(yù)測9、完整代碼 1、導(dǎo)入庫 引入必要的庫,包括PyTorch、Pandas等。 import numpy as np import pandas as pd f…

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

  • 1、導(dǎo)入庫
  • 2、數(shù)據(jù)準(zhǔn)備
  • 3、數(shù)據(jù)拆分
  • 4、數(shù)據(jù)標(biāo)準(zhǔn)化
  • 5、數(shù)據(jù)轉(zhuǎn)換
  • 6、模型搭建
  • 7、模型訓(xùn)練
  • 8、模型預(yù)測
  • 9、完整代碼

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_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、數(shù)據(jù)準(zhǔn)備

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

后續(xù)完整代碼中,數(shù)據(jù)也是采用先下載,單獨保存之后,再重新讀取的方式。

# 導(dǎo)入數(shù)據(jù)
housedata = fetch_california_housing()  # 首次運行會下載數(shù)據(jù)集
data_x, data_y = housedata.data, housedata.target  # 讀取數(shù)據(jù)和標(biāo)簽
data_df = pd.DataFrame(data=data_x, columns=housedata.feature_names)  # 將數(shù)據(jù)處理成dataframe格式
data_df['target'] = data_y  # 添加標(biāo)簽列
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ù)標(biāo)準(zhǔn)化

# 數(shù)據(jù)標(biāo)準(zhǔn)化處理
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 = 0train_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()  # 每次迭代梯度初始化0loss.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.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# 搭建全連接神經(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ù)標(biāo)準(zhǔn)化處理
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 = 0train_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()  # 每次迭代梯度初始化0loss.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()
http://www.risenshineclean.com/news/22617.html

相關(guān)文章:

  • 鄭州一站式網(wǎng)站搭建認(rèn)真負(fù)責(zé)百度大搜
  • 蘋果軟件 做ppt模板下載網(wǎng)站有哪些seo崗位
  • 建設(shè)工程管理專業(yè)學(xué)什么北京seo網(wǎng)站優(yōu)化公司
  • 浙江省公路建設(shè)發(fā)票網(wǎng)站谷歌商店paypal三件套
  • 網(wǎng)站建設(shè)價格標(biāo)準(zhǔn)報價百度快速收錄權(quán)限域名
  • 做網(wǎng)站的域名和空間是什么意思濟南做網(wǎng)站公司哪家好
  • 多網(wǎng)站綁定域名手機建網(wǎng)站軟件
  • 企業(yè)網(wǎng)站設(shè)置應(yīng)用商店搜索優(yōu)化
  • 云網(wǎng)站開發(fā)東莞快速排名
  • 曲周手機網(wǎng)站建設(shè)百度搜索量最大的關(guān)鍵詞
  • 供應(yīng)鏈管理專業(yè)就業(yè)前景東莞seo網(wǎng)絡(luò)推廣專
  • 那里可以找建網(wǎng)站的人seo排名怎么做
  • 吉首網(wǎng)站建設(shè)廣州 關(guān)于進一步優(yōu)化
  • 幫企業(yè)做網(wǎng)站線上推廣的方法
  • 網(wǎng)站優(yōu)化試題現(xiàn)在最好的營銷方式
  • 怎樣免費做彩票網(wǎng)站營銷的方法手段有哪些
  • 建網(wǎng)站流程 知乎最打動人心的廣告語
  • 網(wǎng)上競價投標(biāo)流程北京百度關(guān)鍵詞優(yōu)化
  • 網(wǎng)站軟文制作企業(yè)網(wǎng)站建設(shè)平臺
  • 利用百度網(wǎng)盤自動播放做視頻網(wǎng)站會計培訓(xùn)班的費用是多少
  • 開普網(wǎng)站建設(shè)公司免費寫文章的軟件
  • 做公司網(wǎng)站需要幾個域名網(wǎng)絡(luò)營銷的特點是什么
  • 甘肅疫情防控最新政策seo怎么優(yōu)化
  • 江油網(wǎng)站網(wǎng)站建設(shè)煙臺網(wǎng)站建設(shè)
  • 太原網(wǎng)站推廣教程百度搜索量最大的關(guān)鍵詞
  • 知名的教育行業(yè)網(wǎng)站開發(fā)推廣app用什么平臺比較好
  • 大邑縣建設(shè)局網(wǎng)站深圳開發(fā)公司網(wǎng)站建設(shè)
  • 政府職能網(wǎng)站建設(shè)seo門戶網(wǎng)價格是多少錢
  • 設(shè)計本官方網(wǎng)站下載如何設(shè)計網(wǎng)站
  • 開網(wǎng)站賺50萬做百度指數(shù)官方下載