- 🍨 本文为🔗365天深度学习训练营中的学习记录博客
- 🍖 原作者:K同学啊
-
一、GPU设置
-
import torch
import torch.nn as nn
import torchvision.transforms as transforms
import torchvision
from torchvision import transforms, datasets
import os,PIL,pathlib,warningswarnings.filterwarnings("ignore") #忽略警告信息
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
device -
二、数据导入与拆分数据集
-
import os,PIL,random,pathlib
data_dir = './PotatoPlants/'#根据文件名修改
data_dir = pathlib.Path(data_dir)data_paths = list(data_dir.glob('*'))
classeNames = [str(path).split("\\")[1] for path in data_paths]
classeNames -
train_transforms = transforms.Compose([
transforms.Resize([224, 224]), # 将输入图片resize成统一尺寸
# transforms.RandomHorizontalFlip(), # 随机水平翻转
transforms.ToTensor(), # 将PIL Image或numpy.ndarray转换为tensor,并归一化到[0,1]之间
transforms.Normalize( # 标准化处理-->转换为标准正太分布(高斯分布),使模型更容易收敛
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225]) # 其中 mean=[0.485,0.456,0.406]与std=[0.229,0.224,0.225] 从数据集中随机抽样计算得到的。
])test_transform = transforms.Compose([
transforms.Resize([224, 224]), # 将输入图片resize成统一尺寸
transforms.ToTensor(), # 将PIL Image或numpy.ndarray转换为tensor,并归一化到[0,1]之间
transforms.Normalize( # 标准化处理-->转换为标准正太分布(高斯分布),使模型更容易收敛
mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225]) # 其中 mean=[0.485,0.456,0.406]与std=[0.229,0.224,0.225] 从数据集中随机抽样计算得到的。
])total_data = datasets.ImageFolder("./PotatoPlants/",transform=train_transforms)
total_data -
train_size = int(0.8 * len(total_data))
test_size = len(total_data) - train_size
train_dataset, test_dataset = torch.utils.data.random_split(total_data, [train_size, test_size])
train_dataset, test_dataset -
batch_size = 32
train_dl = torch.utils.data.DataLoader(train_dataset,
batch_size=batch_size,
shuffle=True,
num_workers=1)
test_dl = torch.utils.data.DataLoader(test_dataset,
batch_size=batch_size,
shuffle=True,
num_workers=1) -
for X, y in test_dl:
print("Shape of X [N, C, H, W]: ", X.shape)
print("Shape of y: ", y.shape, y.dtype)
break -
import torch.nn.functional as F
-
三、搭建Vgg16,也可以直接调用
class vgg16(nn.Module):
def __init__(self):
super(vgg16, self).__init__()
# 卷积块1
self.block1 = nn.Sequential(
nn.Conv2d(3, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)),
nn.ReLU(),
nn.Conv2d(64, 64, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)),
nn.ReLU(),
nn.MaxPool2d(kernel_size=(2, 2), stride=(2, 2))
)
# 卷积块2
self.block2 = nn.Sequential(
nn.Conv2d(64, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)),
nn.ReLU(),
nn.Conv2d(128, 128, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)),
nn.ReLU(),
nn.MaxPool2d(kernel_size=(2, 2), stride=(2, 2))
)
# 卷积块3
self.block3 = nn.Sequential(
nn.Conv2d(128, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)),
nn.ReLU(),
nn.Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)),
nn.ReLU(),
nn.Conv2d(256, 256, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)),
nn.ReLU(),
nn.MaxPool2d(kernel_size=(2, 2), stride=(2, 2))
)
# 卷积块4
self.block4 = nn.Sequential(
nn.Conv2d(256, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)),
nn.ReLU(),
nn.Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)),
nn.ReLU(),
nn.Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)),
nn.ReLU(),
nn.MaxPool2d(kernel_size=(2, 2), stride=(2, 2))
)
# 卷积块5
self.block5 = nn.Sequential(
nn.Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)),
nn.ReLU(),
nn.Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)),
nn.ReLU(),
nn.Conv2d(512, 512, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1)),
nn.ReLU(),
nn.MaxPool2d(kernel_size=(2, 2), stride=(2, 2))
)
# 全连接网络层,用于分类
self.classifier = nn.Sequential(
nn.Linear(in_features=512*7*7, out_features=4096),
nn.ReLU(),
nn.Linear(in_features=4096, out_features=4096),
nn.ReLU(),
nn.Linear(in_features=4096, out_features=3)
)def forward(self, x):
x = self.block1(x)
x = self.block2(x)
x = self.block3(x)
x = self.block4(x)
x = self.block5(x)
x = torch.flatten(x, start_dim=1)
x = self.classifier(x)return x
device = "cuda" if torch.cuda.is_available() else "cpu"
print("Using {} device".format(device))
model = vgg16().to(device)
model -
四、查看模型
-
# 统计模型参数量以及其他指标
import torchsummary as summary
summary.summary(model, (3, 224, 224)) -
五、训练和测试
-
# 训练循环
def train(dataloader, model, loss_fn, optimizer):
size = len(dataloader.dataset) # 训练集的大小
num_batches = len(dataloader) # 批次数目, (size/batch_size,向上取整)train_loss, train_acc = 0, 0 # 初始化训练损失和正确率
for X, y in dataloader: # 获取图片及其标签
X, y = X.to(device), y.to(device)
# 计算预测误差
pred = model(X) # 网络输出
loss = loss_fn(pred, y) # 计算网络输出和真实值之间的差距,targets为真实值,计算二者差值即为损失
# 反向传播
optimizer.zero_grad() # grad属性归零
loss.backward() # 反向传播
optimizer.step() # 每一步自动更新
# 记录acc与loss
train_acc += (pred.argmax(1) == y).type(torch.float).sum().item()
train_loss += loss.item()
train_acc /= size
train_loss /= num_batchesreturn train_acc, train_loss
-
def test (dataloader, model, loss_fn):
size = len(dataloader.dataset) # 测试集的大小
num_batches = len(dataloader) # 批次数目, (size/batch_size,向上取整)
test_loss, test_acc = 0, 0
# 当不进行训练时,停止梯度更新,节省计算内存消耗
with torch.no_grad():
for imgs, target in dataloader:
imgs, target = imgs.to(device), target.to(device)
# 计算loss
target_pred = model(imgs)
loss = loss_fn(target_pred, target)
test_loss += loss.item()
test_acc += (target_pred.argmax(1) == target).type(torch.float).sum().item()test_acc /= size
test_loss /= num_batchesreturn test_acc, test_loss
-
六、正式训练
-
import copy
optimizer = torch.optim.Adam(model.parameters(), lr= 1e-4)
loss_fn = nn.CrossEntropyLoss() # 创建损失函数epochs = 40
train_loss = []
train_acc = []
test_loss = []
test_acc = []best_acc = 0 # 设置一个最佳准确率,作为最佳模型的判别指标
for epoch in range(epochs):
model.train()
epoch_train_acc, epoch_train_loss = train(train_dl, model, loss_fn, optimizer)
model.eval()
epoch_test_acc, epoch_test_loss = test(test_dl, model, loss_fn)
# 保存最佳模型到 best_model
if epoch_test_acc > best_acc:
best_acc = epoch_test_acc
best_model = copy.deepcopy(model)
train_acc.append(epoch_train_acc)
train_loss.append(epoch_train_loss)
test_acc.append(epoch_test_acc)
test_loss.append(epoch_test_loss)
# 获取当前的学习率
lr = optimizer.state_dict()['param_groups'][0]['lr']
template = ('Epoch:{:2d}, Train_acc:{:.1f}%, Train_loss:{:.3f}, Test_acc:{:.1f}%, Test_loss:{:.3f}, Lr:{:.2E}')
print(template.format(epoch+1, epoch_train_acc*100, epoch_train_loss,
epoch_test_acc*100, epoch_test_loss, lr))
# 保存最佳模型到文件中
PATH = './best_model.pth' # 保存的参数文件名
torch.save(model.state_dict(), PATH)print('Done')
-
import matplotlib.pyplot as plt
#隐藏警告
import warnings
warnings.filterwarnings("ignore") #忽略警告信息
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号
plt.rcParams['figure.dpi'] = 100 #分辨率epochs_range = range(epochs)
plt.figure(figsize=(12, 3))
plt.subplot(1, 2, 1)plt.plot(epochs_range, train_acc, label='Training Accuracy')
plt.plot(epochs_range, test_acc, label='Test Accuracy')
plt.legend(loc='lower right')
plt.title('Training and Validation Accuracy')plt.subplot(1, 2, 2)
plt.plot(epochs_range, train_loss, label='Training Loss')
plt.plot(epochs_range, test_loss, label='Test Loss')
plt.legend(loc='upper right')
plt.title('Training and Validation Loss')
plt.show() -
七、指定图片预测
-
from PIL import Image
classes = list(total_data.class_to_idx)
def predict_one_image(image_path, model, transform, classes):
test_img = Image.open(image_path).convert('RGB')
plt.imshow(test_img) # 展示预测的图片test_img = transform(test_img)
img = test_img.to(device).unsqueeze(0)
model.eval()
output = model(img)_,pred = torch.max(output,1)
pred_class = classes[pred]
print(f'预测结果是:{pred_class}')# 预测训练集中的某张照片
predict_one_image(image_path='./PotatoPlants/Early_blight/1.JPG',
model=model,
transform=train_transforms,
classes=classes)

-
八、学习感想
-
对于Vgg16网络有了更深的理解,关于将改代码优化器换成随机梯度算法下周想尝试一下,然后识别准确率还需进一步提高
相关推荐
【YOLOv5进阶】——替换主干网络(backbone)-MobileNet为例
替换网络主体,即配置文件中的backbone,这里以轻量级网络MobileNet的替换为例,替换后网络参数数量降低了近一半,速度快了1倍左右,但训练效果指标相比之前不佳。
Yolov5 添加backbone方法
yolov5 添加 backbone 注意力机制模块
YOLOV5 改进:替换backbone为MobileVIT
yolov5替换主干网络的步骤如下,依旧和之前的一样。
Yolov5网络修改教程(将backbone修改为EfficientNet、MobileNet3、RegNet等)
在我的本科毕业论文中,我使用了Yolov5,并尝试对其更改。可以对Yolov5进行一定程度的定制化修改,例如更轻量级的Yolov5-MobileNetv3 或者比Yolov5s更好的(存疑,没有跑过大数据集,可自己实验)Yolov5-EfficientNet。......
YOLOv5改进实战 | 更换主干网络Backbone(一)之轻量化网络Ghostnet
工厂自动化布线实战:从功率计算到线槽布局的完整避坑指南
本文详细介绍了工厂自动化布线的实战经验,从功率计算到线槽布局的完整避坑指南。通过三步计算法确定线径需求,强调电压降控制的重要性,并分享线槽布局的50%法则和强弱电分离技巧。特别针对移动设备和多芯信号线提供专业解决方案,帮助工程师避免常见错误,提升布线效率和质量。
Delphi无标题窗体增强功能实现:让无标题窗体更具交互性
Delphi无标题窗体增强功能实现:让无标题窗体更具交互性 去发现同类优质开源项目:https://gitcode.com/ 项目介绍 在软件开发领域,Delphi 语言因其高效的执行速度和清晰的语法结构,一直受到开发者的喜爱。然而,在使用无标题窗体(borderstyle=bsnone)时,开发者常常面临一个问题:用户无法通过常规方式来移动或调整窗体大小。本项目正是为了解决这一难题而诞生,它提供...
深度学习简介(框架)
深度学习是一种基于人工神经网络的机器学习方法,它通过模拟人脑的工作原理来解决复杂的数据模式识别问题。这种方法在图像识别、语音识别、自然语言处理等领域取得了显著的进展。深度学习是机器学习的一个子领域,它基于人工神经网络的学习算法,特别是那些具有多层(深层)结构的网络。这些深度神经网络能够学习数据的高级特征和模式。深度学习作为人工智能的关键驱动技术,已经在多个领域展现出其强大的能力。随着研究的深入和技术的发展,深度学习将继续推动人工智能的边界向前发展。
无标题栏窗口拖动的实现
普通的Windows应用程序窗口都具有统一的窗口风格,它们一般都包括:用户区和非用户区两部分。非用户区包括标题条、窗口边框、最大化按钮、最小化按钮、关闭按钮和系统默认的快捷键及鼠标支持等。利用鼠标的左键通过拖动窗口的标题条可以在屏幕上任意移动整个窗口,当光标停止在窗口边框上时可以改变窗口的大小。在一些比较经典的软件中,有一类特殊的无标题条的窗口。这种窗口不需要改变窗口的大小,但必须具有窗口客户区域
cs188Inference in Bayes Nets(贝叶斯网络的推理)
cs188Inference in Bayes Nets贝叶斯网络的推理Question1(3 points):Bayes Net StructureQuestion2(1 points):Bayes Net ProbabilitiesQuestion 3(5 points):Join FactorsQuestion4(4 points):EliminateQuestion5(4 points):NormalizeQuestion 6(4 points):Variable EliminationQuesti
ImageNet分类实战:用PyTorch复现AlexNet的5个关键技巧(附代码)
本文详细介绍了使用PyTorch复现经典AlexNet模型进行ImageNet图像分类的五个关键工程技巧。内容涵盖模型架构的现代重构、训练策略优化、核心组件实现与替代方案,以及实用的训练调试方法,并提供了完整的代码示例,帮助开发者深入理解深度卷积神经网络的实现细节与优化思路。
无标题窗口的拖动
普通的Windows应用程序窗口都具有统一的窗口风格,它们一般都包括:用户区和非用户区两部分。非用户区包括标题条、窗口边框、最大化按钮、最小化按钮、关闭按钮和系统默认的快捷键及鼠标支持等。利用鼠标的左键通过拖动窗口的标题条可以在屏幕上任意移动整个窗口,当光标停止在窗口边框上时可以改变窗口的大小。在一些比较经典的软件中,有一类特殊的无标题条的窗口。这种窗口不需要改变窗口的大小,但必须具有窗口客户区域
Allegro层叠中的Etch Factor-铜皮的腐蚀因子如何计算
在用Allegro进行PCB设计的时候,Cross-section中需要填入对应的信息,一般填入每层的厚度即可,如下图。当PCB需要进行仿真分析的时候,Etch-Factor这个值是必须要填写的,如下图。实际铜皮进行蚀刻的时候,Etch-Factor的值并不是标准的90度,如下图。线路层实际形状是个梯形,Etch-Factor代表的就是梯形的角度,如下图。首先输入数值,比如1,再点击Inv,最后点击tan-1,可以得到角度的值。如果tanσ=2,σ=63.4,如下图计算结果。即tanσ=1,得到σ=45。
C#拖动无标题栏窗体
很长时间没有写博客了,今天又解决并测试通过了一个Delphi很简单的问题——无标题栏窗体的拖动 。其实是个很简单的问题,但是还是想写下来,一方面加深自己的记忆,一方面与朋友们分享!DeviceAnywhere在Ioicn发布了,反响似乎一般,我想是因为.net FrameWork环境的问题吧,希望Microsoft再出sp的时候把.net FrameWorkx.x集成到操作系统里吧,这样大家都方便
RTDETR最强结构图 | 包含模型整体结构图 | 全模块展开图 | AiFi模块展开图
RT-DETR 最全结构图
keras tensorflow 的lstm的新冠疫情感染人数预测 附完整代码数据 可直接运行
keras tensorflow 的lstm的新冠疫情感染人数预测 附完整代码数据 可直接运行
android设置activity全屏 | 无标题
1.设置activity无标题 方法一: 在Manifest.xml中为activity增加属性: android:theme="@android:style/Theme.NoTitleBar" 方法二: 在activity的onCreate()中加入:requestWindowFeature(Window.FEATURE_NO_TITLE); 2.设置activity全屏
在 SAP S/4HANA Private Cloud 中把标准 CDS View 发布为 OData:可操作的四条路径与完整示例
在 ADT 中创建。
C#中的无标题栏窗体
所以谓的无标题栏窗体,与标题无关,看边框设置将窗体的FormBorderStyle属性设置为None就可以了,其它的一些属性只是一些显示样式.关于无标题栏窗体的拖动就用傻办法,至少我看到的都是这样的.关于这一方面的介绍不少,我就不在这里缀述了,如果有想要示例的,可以留下邮箱.
Probability and Statistics - 4th edition
Probability and Statistics - 4th edition
深度学习工具包 DeepLearningToolbox
深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[](https://bitdeli.com/free "Bitdeli Badge")
Android应用设置无标题栏的实现方式
去掉标题栏 第一,在代码中实现; requestWindowFeature(Window.FEATURE_NO_TITLE); 代码要写在setContentView()前。 第二,在xml文件中进行配置; 调用系统自带的样式; 实现全屏效果: android:theme="@android:style/Theme.NoTitleBar.Fullscree
IMSL CNL 7.0.0 (x86-64)Crack
IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件
【QT学习】如何移动无标题栏窗口?(图文详解)
本篇,作者将分享如何移动无标题栏的窗口。
WINCC7.3破解文件
WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!
Labview无标题栏鼠标拖动窗口程序:打造极致简洁交互体验
Labview无标题栏鼠标拖动窗口程序:打造极致简洁交互体验 去发现同类优质开源项目:https://gitcode.com/ 项目介绍 在当今快速发展的软件交互设计中,用户界面(UI)的简洁性和易用性越来越受到重视。Labview 无标题栏鼠标拖动窗口程序正是为了满足这种需求而诞生的一个开源项目。它通过巧妙地调用Windows API函数GetMessagePos,实现了在无标题栏状态下,用户可...
delphi技巧——移动无标题窗口
delphi技巧——移动无标题窗口关键词:移动,消息,无标题 作者:朱能文 我们都知道windows是通过标题栏来移动窗体的,当我们在标题栏上按下鼠标左键时,windows将发送wM_NCHitTest消息,来告诉系统要移动窗体。但我们在实际编程时,有时为了界面的需要或特殊的要求,窗体没有标题栏,我们必须通过程序来移动窗体。下面我将介
Delphi 无标题窗体增强功能实现
Delphi 无标题窗体增强功能实现 去发现同类优质开源项目:https://gitcode.com/ 资源简介 本资源提供了一种在 Delphi 开发环境中对无标题窗体(borderstyle=bsnone)进行增强的方法。默认情况下,无标题窗体不显示边框,用户无法通过常规方式移动或调整窗体大小。本资源通过特定的技术手段,为无标题窗体添加了边框,同时实现了窗体的拖拽调整大小和移动位置的功能。 功...
使用OnNcHitTest消息实现无标题窗口的移动
<br />使用OnNcHitTest消息<br />实现无标题窗口的移动<br />////////////////////////////////////////////////////////////<br />UINT myWnd::OnNcHitTest(CPoint point)<br />{<br /> // TODO: 在此添加消息处理程序代码和/或调用默认值<br /> // rect 指定,鼠标点在什么地方时,可以移动窗口<br /> // 其实就是把这部分区域当成是 标题栏<br />
android手机设置无标题后,程序挂掉 解决 (如何用最简短语句设置 手机 全屏无标题)
手机设置无标题后,总是挂掉,最初以为是布局的问题,换了还是不中,然后新建一个工程,发现还是不中!怎么回事?我以前是搞过着的啊,原来设置全屏无标题,这些语句一定要设在setContentView前面!谨记啊! 还是对这些知识不熟悉,所以我写到这,复习下! 设置无标题+全屏: requestWindowFeature(Window.FEATURE_NO_TITLE); int flag = Wi
2817



被折叠的 条评论
为什么被折叠?



