Idiom of using in F#

本文通过一个HTTP请求的示例,展示了F#语言如何简化代码并确保资源安全释放。使用了[b]using[/b]函数使得代码更加简洁安全。
In Don Syme's [url=http://blogs.msdn.com/dsyme/archive/2006/12/18/DraftChaptersUpdateDec2006.aspx]excellent book drafts[/url] of his upcoming book [i]Expert F#[/i], the following code is used to demonstrate the quickness and easiness of F# interactive development.

[code]
> let req = WebRequest.Create("http://www.microsoft.com");;
val req : WebRequest
> let resp = req.GetResponse();;
val resp : WebResponse
> let stream = resp.GetResponseStream();;
val stream : Stream
> let reader = new StreamReader(stream) ;;
val reader : StreamReader
> let html = reader.ReadToEnd();;
val html : string = "<html>...</html>"
[/code]

However, writing codes in such way would be too imperative. By using the idiomatic [b]using[/b] function, we can write it in a more concise and safer form:

[code]#light
let http (url: string) =
let req = WebRequest.Create(url)
using (req.GetResponse())
(fun res -> using (res.GetResponseStream())
(fun stream -> let reader = new StreamReader(stream)
reader.ReadToEnd())) [/code]

The arguments of [b]using[/b] are:
[code]val it : 'a -> ('a -> 'b) -> 'b when 'a :> IDisposable = <fun:clo@0>[/code]
Clearly, the first argument requires a resource that implements the IDisposable interface ( [b]:>[/b] is a special operator in F# for up-casting); then [b]using[/b] will feed the resource to a function to process further and finally will guarantee to release the resource when everything is done.
# 代码参考 # PyTorch深度学习入门 作者:曾芃壹 # # -- Code Examples # # 参考代码来自 https://www.ituring.com.cn/book/2703 # 时间:2024年4月7日 Date: April 7, 2024 # 文件名称 Filename: BasicML8.py # 编码实现 Coding by: Wei Zhou, 邮箱 Mailbox:2686818585@qq.com # 所属单位:中国 成都,西南民族大学(Southwest University of Nationality,or Southwest Minzu University), 计算机科学与工程学院. # Affiliation: School of Computer Science and Engineering,SWUN (before 2020) or SMU (2020 - now), Chengdu, PR. China # coding=utf-8 # 用Pytorch的神经网络类实现逻辑回归 # coding=utf-8 import os import torch from torch import nn, optim import torch.nn.functional as F # from torch.autograd import Variable from torchvision import datasets, transforms ''' Torchvision 是一个和 PyTorch 配合使用的 Python 包。它不只提供了一些常用数据集,还提供了几个已经搭建好的经典网络模型,以及集成了一些图像数据 处理方面的工具,主要供数据预处理阶段使用。简单地说,Torchvision 库就是常用数据集 + 常见网络模型 + 常用图像处理方法。 Torchvision 中默认使用的图像加载器是 PIL,为了确保 Torchvision 正常运行,还需要安装一个 Python 的第三方图像处理库——Pillow 库。 ''' from torchvision import datasets, transforms # 1 解释下面transforms.Compose函数的作用,和各个参数的含义。 transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,)) ]) # 2 解释下面datasets.MNIST(函数的作用,和各个参数的含义。 trainset = datasets.MNIST('data', train=True, download=True, transform=transform) testset = datasets.MNIST('data', train=False, download=True, transform=transform) class LeNet(nn.Module): # 定义Net的初始化函数,本函数定义了神经网络的基本结构 def __init__(self): # 继承父类的初始化方法,即先运行nn.Module的初始化函数 super(LeNet, self).__init__() # C1卷积层:输入1张灰度图片,输出6张特征图,卷积核5x5 self.c1 = nn.Conv2d(1, 6, (5, 5)) # C3卷积层:输入6张特征图,输出16张特征图,卷积核5x5 self.c3 = nn.Conv2d(6, 16, 5) # 3. 解释为什么这里设置为16 * 4 * 4,能否设置成其它值?请具体解释理由。 # 全连接层S4->C5:从S4到C5是全连接,S4层中16*4*4个节点全连接到C5层的120个节点上 self.fc1 = nn.Linear(16 * 4 * 4, 120) # 全连接层C5->F6:C5层的120个节点全连接到F6的84个节点上 self.fc2 = nn.Linear(120, 84) # 全连接层F6->OUTPUT:F6层的84个节点全连接到OUTPUT层的10个节点上,10个节点的输出代表着0到9的不同分值。 self.fc3 = nn.Linear(84, 10) # 定义向前传播函数 def forward(self, x): # 输入的灰度图片x经过c1的卷积之后得到6张特征图,然后使用relu函数,增强网络的非线性拟合能力,接着使用2x2窗口的最大池化,然后更新到x x = F.max_pool2d(F.relu(self.c1(x)), 2) # 输入x经过c3的卷积之后由原来的6张特征图变成16张特征图,经过relu函数,并使用最大池化后将结果更新到x x = F.max_pool2d(F.relu(self.c3(x)), 2) # 使用view函数将张量x(S4)变形成一维向量形式,总特征数不变,为全连接层做准备 x = x.view(-1, self.num_flat_features(x)) # 输入S4经过全连接层fc1,再经过relu,更新到x x = F.relu(self.fc1(x)) # 输入C5经过全连接层fc2,再经过relu,更新到x x = F.relu(self.fc2(x)) # 输入F6经过全连接层fc3,更新到x x = self.fc3(x) return x # 计算张量x的总特征量 def num_flat_features(self, x): # 4 为什么要对第零维度剔除,后面维度又表示什么? # 由于默认批量输入,第零维度的batch剔除 size = x.size()[1:] num_features = 1 for s in size: num_features *= s return num_features CUDA = torch.cuda.is_available() if CUDA: lenet = LeNet().cuda() else: lenet = LeNet() criterion = nn.CrossEntropyLoss() optimizer = optim.SGD(lenet.parameters(), lr=0.001, momentum=0.9) # 5 解释torch.utils.data.DataLoader函数,包括每个参数的意义。 trainloader = torch.utils.data.DataLoader(trainset, batch_size=4, shuffle=True, num_workers=2) testloader = torch.utils.data.DataLoader(testset, batch_size=4, shuffle=False, num_workers=2) def train(model, criterion, optimizer, epochs=1): for epoch in range(epochs): running_loss = 0.0 # 6 解释 enumerate(trainloader, 0)函数是什么? for i, data in enumerate(trainloader, 0) 的作用是什么? for i, data in enumerate(trainloader, 0): inputs, labels = data if CUDA: inputs, labels = inputs.cuda(), labels.cuda() optimizer.zero_grad() outputs = model(inputs) loss = criterion(outputs, labels) loss.backward() optimizer.step() running_loss += loss.item() if i % 1000 == 999: print('[Epoch:%d, Batch:%5d] Loss: %.3f' % (epoch + 1, i + 1, running_loss / 1000)) running_loss = 0.0 print('Finished Training') def test(testloader, model): correct = 0 total = 0 for data in testloader: images, labels = data if CUDA: images = images.cuda() labels = labels.cuda() outputs = model(images) _, predicted = torch.max(outputs.data, 1) total += labels.size(0) correct += (predicted == labels).sum() print('Accuracy on the test set: %d %%' % (100 * correct / total)) def load_param(model, path): if os.path.exists(path): model.load_state_dict(torch.load(path)) def save_param(model, path): torch.save(model.state_dict(), path) # torch.save(lenet, ‘model.pkl’) 和 torch.save(lenet.state_dict(), ‘model.pkl’)的使用区别是什么? load_param(lenet, 'model.pkl') train(lenet, criterion, optimizer, epochs=2) save_param(lenet, 'model.pkl') test(testloader, lenet) 运行为什么出错了RuntimeError: An attempt has been made to start a new process before the current process has finished its bootstrapping phase. This probably means that you are not using fork to start your child processes and you have forgotten to use the proper idiom in the main module: if __name__ == '__main__': freeze_support() ... The "freeze_support()" line can be omitted if the program is not going to be frozen to produce an executable. To fix this issue, refer to the "Safe importing of main module" section in https://docs.python.org/3/library/multiprocessing.html raise RuntimeError('''
10-28
基于粒子群优化算法的p-Hub选址优化(Matlab代码实现)内容概要:本文介绍了基于粒子群优化算法(PSO)的p-Hub选址优化问题的研究与实现,重点利用Matlab进行算法编程和仿真。p-Hub选址是物流与交通网络中的关键问题,旨在通过确定最优的枢纽节点位置和非枢纽节点的分配方式,最小化网络总成本。文章详细阐述了粒子群算法的基本原理及其在解决组合优化问题中的适应性改进,结合p-Hub中转网络的特点构建数学模型,并通过Matlab代码实现算法流程,包括初始化、适应度计算、粒子更新与收敛判断等环节。同时可能涉及对算法参数设置、收敛性能及不同规模案例的仿真结果分析,以验证方法的有效性和鲁棒性。; 适合人群:具备一定Matlab编程基础和优化算法理论知识的高校研究生、科研人员及从事物流网络规划、交通系统设计等相关领域的工程技术人员。; 使用场景及目标:①解决物流、航空、通信等网络中的枢纽选址与路径优化问题;②学习并掌握粒子群算法在复杂组合优化问题中的建模与实现方法;③为相关科研项目或实际工程应用提供算法支持与代码参考。; 阅读建议:建议读者结合Matlab代码逐段理解算法实现逻辑,重点关注目标函数建模、粒子编码方式及约束处理策略,并尝试调整参数或拓展模型以加深对算法性能的理解。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值