python多线程处理同一批数据

# -*- coding: utf-8 -*-
import math
import random
import time
from concurrent.futures import ThreadPoolExecutor


def split_list():
    # 线程列表
    new_list = []
    count_list = []
    # 需要处理的数据
    _l = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    # 每个线程处理的数据大小
    split_count = 2
    # 需要的线程个数
    times = math.ceil(len(_l) / split_count)
    count = 0
    for item in range(times):
        _list = _l[count: count + split_count]
        new_list.append(_list)
        count_list.append(count)
        count += split_count
    return new_list, count_list


def work(df, _list):
    """ 线程执行的任务,让程序随机sleep几秒
    :param df:
    :param _list:
    :return:
    """
    sleep_time = random.randint(1, 5)
    print(f'count is {df},sleep {sleep_time},list is {_list}')
    time.sleep(sleep_time)
    return sleep_time, df, _list


def use():
    new_list, count_list = split_list()
    with ThreadPoolExecutor(max_workers=len(count_list)) as t:
        results = t.map(work, new_list, count_list)

    # 或执行如下两行代码
    # pool = ThreadPoolExecutor(max_workers=5)
    # 使用map的优点是 每次调用回调函数的结果不用手动的放入结果list中
    # results = pool.map(work, new_list, count_list)

    # map返回一个迭代器,其中的回调函数的参数 最好是可以迭代的数据类型,如list;如果有 多个参数 则 多个参数的 数据长度相同;
    # 如: pool.map(work,[[1,2],[3,4]],[0,1]]) 中 [1,2]对应0 ;[3,4]对应1 ;其实内部执行的函数为 work([1,2],0) ; work([3,4],1)
    # map返回的结果 是 有序结果;是根据迭代函数执行顺序返回的结果
    print(type(results))
    # 如下2行 会等待线程任务执行结束后 再执行其他代码
    for ret in results:
        print(ret)
    print('thread execute end!')


if __name__ == '__main__':
    use()
 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
以下是一个使用TensorFlow的LSTM模型来预测全球温度的示例代码,同时使用了多线程处理数据: ```python import tensorflow as tf import numpy as np from threading import Thread # 定义模型参数 num_epochs = 50 batch_size = 128 num_steps = 12 hidden_size = 128 learning_rate = 0.001 # 加载数据 data = np.load("global_temperature.npy") # 划分数据集 train_data = data[:int(len(data)*0.8)] test_data = data[int(len(data)*0.8):] # 定义多线程处理数据函数 def generate_batches(data, batch_size, num_steps): num_batches = int((len(data) - 1) / (batch_size * num_steps)) data = data[:num_batches * batch_size * num_steps] data = data.reshape((batch_size, -1)) for i in range(num_batches): x = data[:, i*num_steps:(i+1)*num_steps] y = data[:, i*num_steps+1:(i+1)*num_steps+1] yield x, y # 定义模型 graph = tf.Graph() with graph.as_default(): inputs = tf.placeholder(tf.float32, [batch_size, num_steps]) targets = tf.placeholder(tf.float32, [batch_size, num_steps]) lstm_cell = tf.contrib.rnn.BasicLSTMCell(hidden_size) initial_state = lstm_cell.zero_state(batch_size, tf.float32) with tf.variable_scope("lstm"): outputs, state = tf.nn.dynamic_rnn(lstm_cell, tf.expand_dims(inputs, -1), initial_state=initial_state) output = tf.reshape(outputs, [-1, hidden_size]) with tf.variable_scope("softmax"): softmax_w = tf.Variable(tf.random_normal([hidden_size, 1])) softmax_b = tf.Variable(tf.random_normal([1])) logits = tf.matmul(output, softmax_w) + softmax_b loss = tf.reduce_mean(tf.square(logits - tf.reshape(targets, [-1, 1]))) optimizer = tf.train.AdamOptimizer(learning_rate).minimize(loss) # 训练模型 with tf.Session(graph=graph) as sess: sess.run(tf.global_variables_initializer()) for epoch in range(num_epochs): train_loss = 0 num_batches = 0 for x, y in generate_batches(train_data, batch_size, num_steps): feed_dict = {inputs: x, targets: y} _, l = sess.run([optimizer, loss], feed_dict=feed_dict) train_loss += l num_batches += 1 print("Epoch {} Train Loss {:.3f}".format(epoch+1, train_loss/num_batches)) # 预测未来12个月的温度 test_inputs = test_data[:-1] test_targets = test_data[1:] test_predictions = [] state = sess.run(lstm_cell.zero_state(1, tf.float32)) for i in range(len(test_inputs)): feed_dict = {inputs: test_inputs[i:i+1], initial_state: state} state, prediction = sess.run([state, logits], feed_dict=feed_dict) test_predictions.append(prediction[0][0]) # 打印预测结果 print("Test Predictions:") print(test_predictions) ``` 这个示例代码中,我们使用了TensorFlow的LSTM模型来预测未来12个月的全球温度,同时使用了多线程处理数据。在训练模型时,我们使用了`generate_batches()`函数来生成批量的训练数据,以加快训练速度。在预测时,我们使用了训练好的模型来预测未来12个月的温度,并打印出了预测结果。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

TNT报社

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值