数据强化

# -*- coding: utf-8 -*- """

import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
#1. 随机调整图片的色彩,定义两种顺序。
def distort_color(image, color_ordering=0):
    if color_ordering == 0:
        image = tf.image.random_brightness(image, max_delta=32./255.)
        image = tf.image.random_saturation(image, lower=0.5, upper=1.5)
        image = tf.image.random_hue(image, max_delta=0.2)
        image = tf.image.random_contrast(image, lower=0.5, upper=1.5)
    else:
        image = tf.image.random_saturation(image, lower=0.5, upper=1.5)
        image = tf.image.random_brightness(image, max_delta=32./255.)
        image = tf.image.random_contrast(image, lower=0.5, upper=1.5)
        image = tf.image.random_hue(image, max_delta=0.2)
        # 防止 矩阵的值,超出[0, 1)
    return tf.clip_by_value(image, 0.0, 1.0)
    #2. 对图片进行预处理,将图片转化成神经网络的输入层数据。
def preprocess_for_train(image, height, width, bbox):
    if bbox is None:
        bbox = tf.constant([0.0, 0.0, 1.0, 1.0], dtype=tf.float32, shape=[1, 1, 4])
    if image.dtype != tf.float32:
        image = tf.image.convert_image_dtype(image, dtype=tf.float32)
        bbox_begin, bbox_size, _ = tf.image.sample_distorted_bounding_box( tf.shape(image),
                                                                           bounding_boxes=bbox, min_object_covered=0.4)
        bbox_begin, bbox_size, _ = tf.image.sample_distorted_bounding_box( tf.shape(image), bounding_boxes=bbox, min_object_covered=0.4)
        distorted_image = tf.slice(image, bbox_begin, bbox_size) # 将随机截取的图片调整为神经网络输入层的大小。
        distorted_image = tf.image.resize_images(distorted_image, [height, width], method=np.random.randint(4)) # 左右翻转图像
        distorted_image = tf.image.random_flip_left_right(distorted_image) # 使用一种随机的顺序调整图像的色彩
        distorted_image = distort_color(distorted_image, np.random.randint(2))
        return distorted_image #3. 读取图片
image_raw_data = tf.gfile.FastGFile("7.jpg", "rb").read() # 调用函数,进行函数的处理
with tf.Session() as sess:
    img_data = tf.image.decode_jpeg(image_raw_data) # 标准图像的方框大小
    boxes = tf.constant([[[0.05, 0.05, 0.9, 0.7], [0.35, 0.47, 0.5, 0.56]]]) # 运行6次,得到6种不同的图像
    for i in range(5):
        print("第"+str(i+1)+"次运行:")
        result = preprocess_for_train(img_data, 68, 68, boxes)
        plt.imsave('image'+str(i+1)+'.jpeg',result.eval())
        plt.imshow(result.eval())
        plt.show()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
获取股票数据的方法有很多种,比如从 Yahoo Finance 或者 Google Finance 等网站上爬取数据,或者使用开源的 Python 库如 pandas-datareader 等来获取数据。以下是一个使用 pandas-datareader 获取股票数据的示例代码: ``` python import pandas_datareader as pdr # 获取股票数据 df = pdr.get_data_yahoo('AAPL', start='2010-01-01', end='2020-12-31') # 保存为 CSV 文件 df.to_csv('AAPL.csv') ``` 该代码使用 pandas-datareader 库中的 get_data_yahoo() 方法获取了苹果公司(AAPL)从 2010 年 1 月 1 日到 2020 年 12 月 31 日的股票数据,并将其保存为 CSV 文件。 对于强化学习代码,可以使用 Python 中的开源强化学习库如 TensorFlow、Keras、PyTorch 等来实现。以下是一个使用 TensorFlow 实现强化学习的示例代码: ``` python import tensorflow as tf import numpy as np import pandas as pd # 读取股票数据 df = pd.read_csv('AAPL.csv') # 获取收盘价作为观测值 obs = np.array(df['Close']) # 定义强化学习模型 model = tf.keras.Sequential([ tf.keras.layers.Dense(10, activation='relu', input_shape=(1,)), tf.keras.layers.Dense(1) ]) # 定义损失函数和优化器 loss_fn = tf.keras.losses.MeanSquaredError() optimizer = tf.keras.optimizers.Adam(learning_rate=0.001) # 定义强化学习训练函数 @tf.function def train_step(obs, action, reward, next_obs): with tf.GradientTape() as tape: # 计算当前状态的 Q 值 q_values = model(obs) # 选择当前状态下的动作 chosen_action_q = tf.reduce_sum(tf.multiply(q_values, action), axis=1) # 计算目标 Q 值 target_q = reward + 0.99 * tf.reduce_max(model(next_obs), axis=1) # 计算损失函数 loss = loss_fn(chosen_action_q, target_q) # 计算梯度并更新模型参数 grads = tape.gradient(loss, model.trainable_variables) optimizer.apply_gradients(zip(grads, model.trainable_variables)) return loss # 强化学习训练 for i in range(1000): obs = np.reshape(obs, (-1, 1)) action = np.random.rand(len(obs), 2) reward = np.random.rand(len(obs)) next_obs = np.roll(obs, -1) next_obs[-1] = obs[-1] loss = train_step(obs, action, reward, next_obs) obs = next_obs if i % 100 == 0: print('Step: {}, Loss: {}'.format(i, loss)) ``` 该代码使用 TensorFlow 实现了一个简单的 Q 学习强化学习模型,其中观测值为收盘价,动作为随机选择的两个值,奖励为随机生成的值。在每一步中,模型根据当前观测值和动作计算出当前状态的 Q 值,并选择当前状态下的动作,然后使用目标 Q 值更新模型参数。训练过程中,模型会进行多次迭代,每次迭代随机选择动作和生成奖励,并计算损失函数进行模型参数更新。最终,模型可以学习到在不同状态下应该采取哪些动作来获得最大的奖励。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值