32、航班实时机器学习预测:从批处理到流式处理

航班实时机器学习预测:从批处理到流式处理

1. 与航班机器学习服务交互

1.1 发送 POST 请求并解析响应

在能够创建和解析 JSON 字节后,我们可以与航班机器学习服务进行交互。该服务的部署 URL 如下:

String endpoint = "https://ml.googleapis.com/v1/projects/"
       + String.format("%s/models/%s/versions/%s:predict",
                        PROJECT, MODEL, VERSION);
GenericUrl url = new GenericUrl(endpoint);

以下是向 Google Cloud Platform 进行身份验证、发送请求并获取响应的代码:

GoogleCredential credential = GoogleCredential.getApplicationDefault();
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
HttpRequestFactory requestFactory = httpTransport.createRequestFactory(credential);
HttpContent content = new ByteArrayContent("application/json", json.getBytes());
HttpRequest request = requestFactory.buildRequest("POST", url, content);
request.setUnsuccessfulResponseHandler(
    new HttpBackOffUnsuccessfulResponseHandler(new ExponentialBackOff()));
request.setReadTimeout(5 * 60 * 1000);
String response = request.execute().parseAsString();

这里添加了两个容错机制:如果出现网络中断或临时故障(非 2xx 的 HTTP 错误),会使用 ExponentialBackoff 类增加重试间隔来重试请求。由于流量突然激增可能导致额外服务器上线时出现 100 - 150 秒的延迟,因此设置了较长的超时时间。

1.2 预测服务客户端

上述代码封装在 FlightsMLService 辅助类中,用于获取航班准点的概率:

public static double predictOntimeProbability(Flight f, double defaultValue) 
throws IOException, GeneralSecurityException {
    if (f.isNotCancelled() && f.isNotDiverted()) {
        Request request = new Request();
        Instance instance = new Instance(f);
        request.instances.add(instance);
        Response resp = sendRequest(request);
        double[] result = resp.getOntimeProbability(defaultValue);
        if (result.length > 0) {
            return result[0];
        } else {
            return defaultValue;
        }
    }
    return defaultValue;
}

需要检查航班是否取消或改道,因为神经网络仅在有实际到达信息的航班上进行训练。

2. 向航班信息添加预测

2.1 批处理输入和输出

在进行实时处理之前,先编写批处理管道实现相同功能。定义一个 Java 接口 InputOutput 来封装输入和输出:

interface InputOutput extends Serializable {
    public PCollection<Flight> readFlights(Pipeline p, MyOptions options);
    public void writeFlights(PCollection<Flight> outFlights, MyOptions options);
}

批处理数据从 BigQuery 表读取,并将结果写入 Google Cloud Storage 的文本文件。关键步骤如下表所示:
| 步骤 | 功能 | 代码 |
| — | — | — |
| 1 | 创建查询 | String query = "SELECT EVENT_DATA FROM flights.simevents WHERE STRING(FL_DATE) = '2015-01-04' AND (EVENT = 'wheelsoff' OR EVENT = 'arrived') "; |
| 2 | 读取行 | BigQueryIO.Read.fromQuery(query) |
| 3 | 解析为 Flight 对象 | TableRow row = c.element(); String line = (String) row.getOrDefault("EVENT_DATA", ""); Flight f = Flight.fromCsv(line); if (f != null) { c.outputWithTimestamp(f, f.getEventTimestamp()); } |

创建 FlightPred 对象来表示需要写入的数据:

@DefaultCoder(AvroCoder.class)
public class FlightPred {
    Flight flight;
    double ontime;
    // constructor, etc.
}

ontime 字段根据不同情况存储不同值:
- 如果收到的事件是 wheelsoff ,则存储预测的准点概率。
- 如果收到的事件是 arrived ,则存储实际的准点性能(0 或 1)。
- 如果航班取消或改道,则存储 null 。

写入代码如下:

PCollection<FlightPred> prds = addPrediction(outFlights);
PCollection<String> lines = predToCsv(prds);
lines.apply("Write", TextIO.Write.to(options.getOutput() + "flightPreds").withSuffix(".csv"));

addPrediction() 方法的 processElement() 方法如下:

Flight f = c.element();
double ontime = -5;
if (f.isNotCancelled() && f.isNotDiverted()) {
    if (f.getField(INPUTCOLS.EVENT).equals("arrived")) {
        ontime = f.getFieldAsFloat(INPUTCOLS.ARR_DELAY, 0) < 15 ? 1 : 0;
    } else {
        ontime = FlightsMLService.predictOntimeProbability(f, -5.0);
    }
}
c.output(new FlightPred(f, ontime));

将 FlightPred 转换为 CSV 文件时,会将无效的负值替换为 null :

FlightPred pred = c.element();
String csv = String.join(",", pred.flight.getFields());
if (pred.ontime >= 0) {
    csv = csv + "," + new DecimalFormat("0.00").format(pred.ontime);
} else {
    csv = csv + ",";
}
c.output(csv);

2.2 数据处理管道

实现管道的中间部分,除了处理出发延迟外,与 CreateTrainingDataset 中的代码相同:

Pipeline p = Pipeline.create(options);
InputOutput io = new BatchInputOutput();
PCollection<Flight> allFlights = io.readFlights(p, options);
PCollectionView<Map<String, Double>> avgDepDelay = readAverageDepartureDelay(p, options.getDelayPath());
PCollection<Flight> hourlyFlights = CreateTrainingDataset.applyTimeWindow(allFlights);
PCollection<KV<String, Double>> avgArrDelay = CreateTrainingDataset.computeAverageArrivalDelay(hourlyFlights);
hourlyFlights = CreateTrainingDataset.addDelayInformation(hourlyFlights, avgDepDelay, avgArrDelay, averagingFrequency);
io.writeFlights(hourlyFlights, options);
PipelineResult result = p.run();
result.waitUntilFinish();

出发延迟直接从训练期间写出的全局平均值(训练数据集上)中读取:

private static PCollectionView<Map<String, Double>> readAverageDepartureDelay(Pipeline p, String path) {
    return p.apply("Read delays.csv", TextIO.Read.from(path))
           .apply("Parse delays.csv",
                ParDo.of(new DoFn<String, KV<String, Double>>() {
                    @ProcessElement
                    public void processElement(ProcessContext c) throws Exception {
                        String line = c.element();
                        String[] fields = line.split(",");
                        c.output(KV.of(fields[0], Double.parseDouble(fields[1])));
                    }
                }))
           .apply("toView", View.asMap());
}

2.3 识别低效问题

在 Google Cloud Platform 的 Cloud Dataflow 上执行批处理管道时,发现推理一直失败。通过 Google Cloud Platform 网络控制台的 API 仪表板监控 API 使用情况,发现前几个请求以 HTTP 响应代码 200 成功,但其余请求以响应代码 429(“请求过多”)失败。可以请求增加配额,但在此之前,应优化管道以减少对服务的请求。

2.4 批量请求

不需要逐个向服务发送航班信息,可以批量请求。有两种批量请求的方式:基于计数(累积航班直到达到阈值,如 100 个航班,然后使用这些航班调用服务)或基于时间(在固定时间跨度内累积航班,如两分钟,然后使用该时间段内累积的所有航班信息调用服务)。

在 Cloud Dataflow 管道中基于计数批量请求的代码如下:

.apply(Window.into(new GlobalWindows()).triggering(
    Repeatedly.forever(AfterFirst.of(
        AfterPane.elementCountAtLeast(100),
        AfterProcessingTime.pastFirstElementInPane().plusDelayOf(Duration.standardMinutes(1))))

但由于管道使用了滑动窗口来计算平均到达延迟,应用 GlobalWindow 会导致对象重新窗口化,产生不必要的副作用。因此,需要在滑动窗口的上下文中进行批量处理。

解决方案是为每个航班发出一个键值对,键反映航班的批次号:

Flight f = c.element();
String key = "batch=" + System.identityHashCode(f) % NUM_BATCHES;
c.output(KV.of(key, f));

然后使用 GroupByKey 进行分组:

PCollection<FlightPred> lines = outFlights
   .apply("Batch->Flight", ParDo.of(...))
   .apply("CreateBatches", GroupByKey.<String, Flight> create())

GroupByKey 输出的 Iterable<Flight> 可以用于批量预测:

double[] batchPredict(Iterable<Flight> flights, float defaultValue) throws IOException, GeneralSecurityException {
    Request request = new Request();
    for (Flight f : flights) {
        request.instances.add(new Instance(f));
    }
    Response resp = sendRequest(request);
    double[] result = resp.getOntimeProbability(defaultValue);
    return result;
}

通过这种更改,请求数量大幅下降,并且在配额范围内。

以下是批量请求优化的流程图:

graph TD;
    A[开始] --> B[获取航班数据];
    B --> C[发出键值对];
    C --> D[GroupByKey分组];
    D --> E[批量预测];
    E --> F[结束];

3. 流式处理管道

3.1 合并 PCollections

当处理流式数据时,数据从 Cloud Pub/Sub 读取并流入 BigQuery。之前从文本文件读取数据时, arrived 和 wheelsoff 事件来自同一个文件,但模拟代码将这些事件流式传输到 Cloud Pub/Sub 的两个不同主题。为了重用数据处理代码,需要合并这两个 PCollection 。可以使用 Flatten 转换来实现:

// 空集合开始
PCollectionList<Flight> pcs = PCollectionList.empty(p);
// 从两个主题读取航班
for (String eventType : new String[]{"wheelsoff", "arrived"}){
    String topic = "projects/" + options.getProject() + "/topics/" + eventType;
    PCollection<Flight> flights = p.apply(eventType + ":read",
        PubsubIO.<String> read().topic(topic)
               .withCoder(StringUtf8Coder.of())
               .timestampLabel("EventTimeStamp"))
          .apply(eventType + ":parse",
               ParDo.of(new DoFn<String, Flight>() {
                    @ProcessElement
                    public void processElement(ProcessContext c) throws Exception {
                        String line = c.element();
                        Flight f = Flight.fromCsv(line);
                        if (f != null) {
                            c.output(f);
                        }
                    }
                }));
    pcs = pcs.and(flights);
}
// 合并集合
return pcs.apply(Flatten.<Flight>pCollections());

这里需要注意 PubsubIO 读取时的 timestampLabel 。如果不指定,消息将被分配插入到 Pub/Sub 时的时间戳。为了使用航班的实际时间作为时间戳,需要在发布消息时指定 EventTimeStamp 属性:

def publish(topics, allevents, notify_time):
    timestamp = notify_time.strftime(RFC3339_TIME_FORMAT)
    for key in topics:  # 'departed', 'arrived', etc.
        topic = topics[key]
        events = allevents[key]
        with topic.batch() as batch:
            for event_data in events:
                batch.publish(event_data, EventTimeStamp=timestamp)

3.2 流式输出到 BigQuery

将 FlightPred 信息流式传输到 BigQuery 需要创建 TableRow 并写入 BigQuery 表:

String outputTable = options.getProject() + ':' + BQ_TABLE_NAME;
TableSchema schema = new TableSchema().setFields(getTableFields());
PCollection<FlightPred> preds = addPredictionInBatches(outFlights);
PCollection<TableRow> rows = toTableRows(preds);
rows.apply("flights:write_toBQ", BigQueryIO.Write.to(outputTable)
    .withSchema(schema));

3.3 执行流式处理管道

编写好管道代码后,可以启动第 4 章的模拟程序将记录流式传输到 Cloud Pub/Sub:

cd ../04_streaming/simulate
python simulate.py --startTime "2015-04-01 00:00:00 UTC" --endTime "2015-04-03 00:00:00 UTC" --speedFactor 60

然后启动 Cloud Dataflow 管道来消费这些记录,调用航班机器学习服务,并将结果记录写入 BigQuery:

mvn compile exec:java \
-Dexec.mainClass=com.google.cloud.training.flights.AddRealtimePrediction \
-Dexec.args="--realtime --speedupFactor=60 --maxNumWorkers=10 --autoscalingAlgorithm=THROUGHPUT_BASED"

通过 realtime 选项可以在批处理和实时处理的 InputOutput 实现之间切换。

3.4 处理延迟和乱序记录

在实际应用中,航班记录可能会延迟或乱序到达。可以通过在模拟程序使用的 BigQuery SQL 语句中添加随机延迟来模拟这种情况:

SELECT
    EVENT,
    NOTIFY_TIME AS ORIGINAL_NOTIFY_TIME,
    TIMESTAMP_ADD(NOTIFY_TIME, INTERVAL CAST (0.5 + RAND()*120 AS INT64) SECOND) AS NOTIFY_TIME,
    EVENT_DATA
FROM
    `flights.simevents`

这里使用 RAND() 函数生成 0 到 1 之间的随机数,乘以 120 得到 0 到 2 分钟的延迟。

还可以模拟其他延迟分布:
- 均匀分布延迟 :如果要模拟 90 到 120 秒的延迟,可以使用 CAST(90.5 + RAND()*30 AS INT64) 。
- 指数分布延迟 :使用 CAST(-LN(RAND()*0.99 + 0.01)*30 + 90.5 AS INT64) 来模拟指数分布延迟。
- 正态分布延迟 :在 BigQuery 中使用用户定义函数(UDF)来生成正态分布的随机变量:

js = """
    var u = 1 - Math.random();
    var v = 1 - Math.random();
    var f = Math.sqrt(-2 * Math.log(u)) * Math.cos(2*Math.PI*v);
    f = f * sigma + mu;
    if (f < 0)
        return 0;
    else
        return f;
""".replace('\n', ' ')

然后在 SQL 中创建临时 UDF 并使用:

sql = """
CREATE TEMPORARY FUNCTION
trunc_rand_normal(x FLOAT64, mu FLOAT64, sigma FLOAT64)
RETURNS FLOAT64
LANGUAGE js AS "{}";
SELECT
    trunc_rand_normal(ARR_DELAY, 90, 15) AS JITTER
FROM
    ...
""".format(js).replace('\n', ' ')

为了实验不同类型的延迟,可以修改模拟代码:

jitter = 'CAST (-LN(RAND()*0.99 + 0.01)*30 + 90.5 AS INT64)'
# 运行查询以提取模拟事件
querystr = """\
SELECT
    EVENT,
    TIMESTAMP_ADD(NOTIFY_TIME, INTERVAL {} SECOND) AS NOTIFY_TIME,
    EVENT_DATA
FROM
    `cloud-training-demos.flights.simevents`
WHERE
    NOTIFY_TIME >= TIMESTAMP('{}')
    AND NOTIFY_TIME < TIMESTAMP('{}')
ORDER BY
    NOTIFY_TIME
""".format(jitter, start_time, end_time)

以下是流式处理管道的流程图:

graph TD;
    A[开始] --> B[从 Cloud Pub/Sub 读取数据];
    B --> C[合并 PCollections];
    C --> D[添加预测信息];
    D --> E[转换为 TableRow];
    E --> F[写入 BigQuery];
    F --> G[结束];

综上所述,通过上述步骤,我们可以从批处理过渡到流式处理,实现航班实时机器学习预测,并处理可能出现的延迟和乱序记录。在实际应用中,可以根据具体需求调整代码和参数,以达到最佳性能和准确性。

相关推荐

Zabbix华为交换机光衰告警

zabbix使用自动发现监控huawei网络设备光衰

qq_31651649的博客 4529

从Chiplet到UCIE:D2D互联技术如何重塑半导体设计生态

本文探讨了D2D互联技术在半导体设计中的革命性作用,从Chiplet到UCIE标准的演进如何重塑行业生态。详细分析了D2D互联的技术本质、架构选择及UCIE标准带来的变革,并展望了未来光学D2D和3D集成等趋势。高速互联接口技术的突破为AI加速器和计算芯片提供了更高带宽和能效。

weixin_29292535的博客 931

Android开发者必看:5分钟搞定DeepSeek API接入(附完整代码示例)

本文为Android开发者提供快速接入DeepSeek API的完整指南,包含环境配置、网络层设计、请求体构建等关键步骤,并附有详细代码示例。通过工程化实践,帮助开发者高效集成AI对话、代码生成等高级功能,提升移动应用竞争力。

bush的博客 535

Adversarial Texture for Fooling Person Detectors in the Physical World

本文提出了对抗纹理的想法(AdvTexture),与基本补丁攻击不同对抗纹理可以生成任意大小,可以覆盖任意大小的不了,并且纹理的任何局部都有对抗性的效果。当衣服被对抗纹理覆盖是,摄像头捕捉到的每一个局部区域都可以攻击探测器,这成功解决了片段缺失的问题。提出了一种两阶段生成方法:基于环形收割的可扩展生成攻击(TC-EGA)来制作广告纹理。第一阶段,训练一个全卷积网络FCN作为生成器,通过采样随机潜变量作为输入来产生纹理(不同于GAN中传统的生成器架构,每一层都使用卷积运算)......

weixin_49171105的博客 1067

EMS案例:BMS传导发射超标整改案例

BMS作为新能源汽车的关键部件,其EMC性能直接影响整车的安全性和可靠性。本文通过一个实际的传导发射整改案例,详细展示了从问题定位、分析到解决方案实施的全过程。希望这些经验能够为从事类似产品设计的工程师提供有价值的参考,在未来的产品开发中避免类似问题,设计出更加可靠、稳定的BMS产品。EMC设计是一门结合理论与实践的艺术,只有通过不断积累经验、深入理解电磁场理论,并紧密结合实际应用场景,才能在复杂的电磁环境中设计出鲁棒性强的电子产品。

m0_56451176的博客 272

Spatial-ORMLLM: Improve Spatial Relation Understanding in the Operating Room with Multimodal Larg...

手术室(OR)中的精准空间建模是众多临床任务的基础,可为术中感知、风险规避及手术决策提供支持。现有方法虽利用大规模多模态数据集进行 latent 空间对齐,以隐式学习空间关系,但却忽视了多模态大型语言模型(MLLM)的3D能力。然而,这种方法存在两个问题:1)手术室通常缺乏多台视频和音频传感器,多模态3D数据难以获取;2)仅依赖易获取的2D数据训练,无法捕捉复杂场景中的细粒度细节。为解决这一问题,我们提出——首个针对手术室3D空间推理的大型视觉语言模型。

UnknownBody_2的博客 592

实战!用Python爬取海关总署进出口贸易数据 —— 从反爬突破到数据可视化全流程指南

{"period": "2026-05", "country": "美国", "import_val": 123.4, "export_val": 567.8, ...}研究员可构建领先指标模型;fig = px.bar(top, x="country", y="total_usd", title="贸易总额TOP10")html.H1("海关进出口数据看板", style={"textAlign": "center"}),"""发起带签名的POST请求(实际为GET + query param)"""

2201_76125261的博客 588

【AI 智能体】Windows 环境 Hermes Agent(爱马仕)安装详细过程

Windows 环境 Hermes Agent(爱马仕)安装详细过程

congge_study的博客 1829

深度学习工具包 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');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

上一篇: 1、可观测性:现代分布式系统的必备要素
下一篇: 2、现代系统可观测性与OpenTelemetry的变革力量
cuda7parallel
博客等级 码龄1天 0粉丝 1273原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值