Copyright: Jingmin Wei, Pattern Recognition and Intelligent System, School of Artificial and Intelligence, Huazhong University of Science and Technology
文章目录
使用sklearn库的fetch_california_housing()函数。数据集共包含20640个样本,有8个自变量。
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
# 导入数据
housedata = fetch_california_housing()
# 切分训练集和测试集
X_train, X_test, y_train, y_test = train_test_split(housedata.data, housedata.target,
test_size = 0.3, random_state = 42)
70% 训练集,30%测试集。
X_train, X_test, y_train, y_test
(array([[ 4.1312 , 35. , 5.88235294, ..., 2.98529412,
33.93 , -118.02 ],
[ 2.8631 , 20. , 4.40120968, ..., 2.0141129 ,
32.79 , -117.09 ],
[ 4.2026 , 24. , 5.61754386, ..., 2.56491228,
34.59 , -120.14 ],
...,
[ 2.9344 , 36. , 3.98671727, ..., 3.33206831,
34.03 , -118.38 ],
[ 5.7192 , 15. , 6.39534884, ..., 3.17889088,
37.58 , -121.96 ],
[ 2.5755 , 52. , 3.40257649, ..., 2.10869565,
37.77 , -122.42 ]]),
array([[ 1.6812 , 25. , 4.19220056, ..., 3.87743733,
36.06 , -119.01 ],
[ 2.5313 , 30. , 5.03938356, ..., 2.67979452,
35.14 , -119.46 ],
[ 3.4801 , 52. , 3.97715472, ..., 1.36033229,
37.8 , -122.44 ],
...,
[ 3.512 , 16. , 3.76228733, ..., 2.36956522,
33.67 , -117.91 ],
[ 3.65 , 10. , 5.50209205, ..., 3.54751943,
37.82 , -121.28 ],
[ 3.052 , 17. , 3.35578145, ..., 2.61499365,
34.15 , -118.24 ]]),
array([1.938, 1.697, 2.598, ..., 2.221, 2.835, 3.25 ]),
array([0.477 , 0.458 , 5.00001, ..., 2.184 , 1.194 , 2.098 ]))
# 数据标准化处理
scale = StandardScaler()
X_train_s = scale.fit_transform(X_train)
X_test_s = scale.transform(X_test)
# 将训练数据转为数据表
housedatadf = pd.DataFrame(data=X_train_s, columns = housedata.feature_names)
housedatadf['target'] = y_train
housedatadf
| MedInc | HouseAge | AveRooms | AveBedrms | Population | AveOccup | Latitude | Longitude | target | |
|---|---|---|---|---|---|---|---|---|---|
| 0 | 0.133506 | 0.509357 | 0.181060 | -0.273850 | -0.184117 | -0.010825 | -0.805682 | 0.780934 | 1.93800 |
| 1 | -0.532218 | -0.679873 | -0.422630 | -0.047868 | -0.376191 | -0.089316 | -1.339473 | 1.245270 | 1.69700 |
| 2 | 0.170990 | -0.362745 | 0.073128 | -0.242600 | -0.611240 | -0.044800 | -0.496645 | -0.277552 | 2.59800 |
| 3 | -0.402916 | -1.155565 | 0.175848 | -0.008560 | -0.987495 | -0.075230 | 1.690024 | -0.706938 | 1.36100 |
| 4 | -0.299285 | 1.857152 | -0.259598 | -0.070993 | 0.086015 | -0.066357 | 0.992350 | -1.430902 | 5.00001 |
| ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
| 14443 | 1.308827 | 0.509357 | 0.281603 | -0.383849 | -0.675265 | -0.007030 | -0.875918 | 0.810891 | 2.29200 |
| 14444 | -0.434100 | 0.350793 | 0.583037 | 0.383154 | 0.285105 | 0.063443 | -0.763541 | 1.075513 | 0.97800 |
| 14445 | -0.494787 | 0.588640 | -0.591570 | -0.040978 | 0.287736 | 0.017201 | -0.758858 | 0.601191 | 2.22100 |
| 14446 | 0.967171 | -1.076283 | 0.390149 | -0.067164 | 0.306154 | 0.004821 | 0.903385 | -1.186252 | 2.83500 |
| 14447 | -0.683202 | 1.857152 | -0.829656 | -0.087729 | 1.044630 | -0.081672 | 0.992350 | -1.415923 | 3.25000 |
14448 rows × 9 columns
使用相关系数热力图分析数据集中9个变量的相关性
datacor = np.corrcoef(housedatadf.values, rowvar=0)
datacor = pd.DataFrame(data = datacor, columns = housedatadf.columns,
index = housedatadf.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()

从图像可以看出,和目标函数相关性最大的是MedInc(收入中位数)变量。而且AveRooms和AveBedrms两个变量的正相关性较强。
# 将数据集转为张量
X_train_t = torch.from_numpy(X_train_s.astype(np.float32))
y_train_t = torch.from_numpy(y_train.astype(np.float32))
X_test_t = torch.from_numpy(X_test_s.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)
# 搭建全连接神经网络回归
class MLPregression(nn.Module):
def __init__(self):
super(MLPregression, 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]
# 输出网络结构
from torchsummary import summary
testnet = MLPregression()
summary(testnet, input_size=(1, 8)) # 表示1个样本,每个样本有8个特征
----------------------------------------------------------------
Layer (type) Output Shape Param #
================================================================
Linear-1 [-1, 1, 100] 900
Linear-2 [-1, 1, 100] 10,100
Linear-3 [-1, 1, 50] 5,050
Linear-4 [-1, 1, 1] 51
================================================================
Total params: 16,101
Trainable params: 16,101
Non-trainable params: 0
----------------------------------------------------------------
Input size (MB): 0.00
Forward/backward pass size (MB): 0.00
Params size (MB): 0.06
Estimated Total Size (MB): 0.06
----------------------------------------------------------------
# 输出网络结构
from torchviz import make_dot
testnet = MLPregression()
x = torch.randn(1, 8).requires_grad_(True)
y = testnet(x)
myMLP_vis = make_dot(y, params=dict(list(testnet.named_parameters()) + [('x', x)]))
myMLP_vis

然后使用训练集对网络进行训练
# 定义优化器
optimizer = torch.optim.SGD(testnet.parameters(), lr = 0.01)
loss_func = nn.MSELoss() # 均方根误差损失函数
train_loss_all = []
# 对模型迭代训练,总共epoch轮
for epoch in range(30):
train_loss = 0
train_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() # 每次迭代梯度初始化0
loss.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)
在测试集上的绝对值误差为: 0.39334159455403034
真实集和预测值可视化,查看之间的差异
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()

在测试集上,MLP回归正确地预测处理原始数据的变化趋势,但部分样本的预测差异较大。
我想在Ruby中创建一个用于开发目的的极其简单的Web服务器(不,不想使用现成的解决方案)。代码如下:#!/usr/bin/rubyrequire'socket'server=TCPServer.new('127.0.0.1',8080)whileconnection=server.acceptheaders=[]length=0whileline=connection.getsheaders想法是从命令行运行这个脚本,提供另一个脚本,它将在其标准输入上获取请求,并在其标准输出上返回完整的响应。到目前为止一切顺利,但事实证明这真的很脆弱,因为它在第二个请求上中断并出现错误:/usr/b
网络编程套接字网络编程基础知识理解源`IP`地址和目的`IP`地址理解源MAC地址和目的MAC地址认识端口号理解端口号和进程ID理解源端口号和目的端口号认识`TCP`协议认识`UDP`协议网络字节序socket编程接口`sockaddr``UDP`网络程序服务器端代码逻辑:需要用到的接口服务器端代码`udp`客户端代码逻辑`udp`客户端代码`TCP`网络程序服务器代码逻辑多个版本服务器单进程版本多进程版本多线程版本线程池版本服务器端代码客户端代码逻辑客户端代码TCP协议通讯流程TCP协议的客户端/服务器程序流程三次握手(建立连接)数据传输四次挥手(断开连接)TCP和UDP对比网络编程基础知识
是否可以在不实际下载文件的情况下检查文件是否存在?我有这么大的(~40mb)文件,例如:http://mirrors.sohu.com/mysql/MySQL-6.0/MySQL-6.0.11-0.glibc23.src.rpm这与ruby不严格相关,但如果发件人可以设置内容长度就好了。RestClient.get"http://mirrors.sohu.com/mysql/MySQL-6.0/MySQL-6.0.11-0.glibc23.src.rpm",headers:{"Content-Length"=>100} 最佳答案
我在这方面尝试了很多URL,在我遇到这个特定的之前,它们似乎都很好:require'rubygems'require'nokogiri'require'open-uri'doc=Nokogiri::HTML(open("http://www.moxyst.com/fashion/men-clothing/underwear.html"))putsdoc这是结果:/Users/macbookair/.rvm/rubies/ruby-2.0.0-p481/lib/ruby/2.0.0/open-uri.rb:353:in`open_http':404NotFound(OpenURI::HT
深度学习12.CNN经典网络VGG16一、简介1.VGG来源2.VGG分类3.不同模型的参数数量4.3x3卷积核的好处5.关于学习率调度6.批归一化二、VGG16层分析1.层划分2.参数展开过程图解3.参数传递示例4.VGG16各层参数数量三、代码分析1.VGG16模型定义2.训练3.测试一、简介1.VGG来源VGG(VisualGeometryGroup)是一个视觉几何组在2014年提出的深度卷积神经网络架构。VGG在2014年ImageNet图像分类竞赛亚军,定位竞赛冠军;VGG网络采用连续的小卷积核(3x3)和池化层构建深度神经网络,网络深度可以达到16层或19层,其中VGG16和VGG
(本文是网络的宏观的概念铺垫)目录计算机网络背景网络发展认识"协议"网络协议初识协议分层OSI七层模型TCP/IP五层(或四层)模型报头以太网碰撞路由器IP地址和MAC地址IP地址与MAC地址总结IP地址MAC地址计算机网络背景网络发展 是最开始先有的计算机,计算机后来因为多项技术的水平升高,逐渐的计算机变的小型化、高效化。后来因为计算机其本身的计算能力比较的快速:独立模式:计算机之间相互独立。 如:有三个人,每个人做的不同的事物,但是是需要协作的完成。 而这三个人所做的事是需要进行协作的,然而刚开始因为每一台计算机之间都是互相独立的。所以前面的人处理完了就需要将数据
安全产品安全网关类防火墙Firewall防火墙防火墙主要用于边界安全防护的权限控制和安全域的划分。防火墙•信息安全的防护系统,依照特定的规则,允许或是限制传输的数据通过。防火墙是一个由软件和硬件设备组合而成,在内外网之间、专网与公网之间的界面上构成的保护屏障。下一代防火墙•下一代防火墙,NextGenerationFirewall,简称NGFirewall,是一款可以全面应对应用层威胁的高性能防火墙,提供网络层应用层一体化安全防护。生产厂家•联想网御、CheckPoint、深信服、网康、天融信、华为、H3C等防火墙部署部署于内、外网编辑额,用于权限访问控制和安全域划分。UTM统一威胁管理(Un
Linux操作系统——网络配置与SSH远程安装完VMware与系统后,需要进行网络配置。第一个目标为进行SSH连接,可以从本机到VMware进行文件传送,首先需要进行网络配置。1.下载远程软件首先需要先下载安装一款远程软件:FinalShell或者xhell7FinalShellxhell7FinalShell下载:Windows下载http://www.hostbuf.com/downloads/finalshell_install.exemacOS下载http://www.hostbuf.com/downloads/finalshell_install.pkg2.配置CentOS网络安装好
在神经网络方面,我完全是个初学者。我整天都在与ruby-fann和ai4r搏斗,不幸的是我没有任何东西可以展示,所以我想我会来到StackOverflow并询问这里的知识渊博的人。我有一组样本——每天都有一个数据点,但它们不符合我能够找出的任何明确模式(我尝试了几次回归)。不过,我认为看看是否有任何方法可以仅从日期预测future的数据会很好,而且我认为神经网络将是生成希望表达这种关系的函数的好方法.日期是DateTime对象,数据点是十进制数,例如7.68。我一直在将DateTime对象转换为float,然后除以10,000,000,000得到一个介于0和1之间的数字,我一直在将
我有一个nokigiri网络抓取工具,它发布到我试图发布到heroku的数据库。我有一个sinatra应用程序前端,我想从数据库中获取它。我是Heroku和Web开发的新手,不知道处理此类问题的最佳方法。我是否必须将上传到数据库的网络爬虫脚本放在sinatra路由下(如mywebsite.com/scraper),并让它变得如此模糊以至于没有人访问它?最后,我想让sinatra部分成为一个从数据库中提取的restapi。感谢大家的参与 最佳答案 您可以采用两种方法。第一个是通过控制台使用herokurunYOURCMD运行scrap