model.predict() == ValueError:检查输入时出错:期望 flatten_input 有 3 个维度,但得到形状为 (1, 2) 的数组

2023-12-01

该项目背后的想法是最终删除“测试”变量并利用来自传感器的真实数据。测试环境有效,但现在我希望能够使用真实数据。

使用两个数据点(从 1 到 100 的整数)作为输入:土壤湿度和下雨机会。

底线: 我只想输入两个数字并获得模型对要采取的操作的最佳预测(如果可能的话,还有置信百分比)。

不过,我在尝试做出预测时遇到了错误。

我尝试过的事情:

pred = dqn.model.predict(np.array([30, 30]))
ValueError: Error when checking input: expected flatten_input to have 3 dimensions, but got array with shape (2, 1)

pred = dqn.model.predict(np.expand_dims(np.array([30, 30]), axis=0))
ValueError: Error when checking input: expected flatten_input to have 3 dimensions, but got array with shape (1, 2)

我看到其他一些线程提到重塑,但我对这个项目有点厌倦,不确定这是否是解决方案。

为了更快地进行测试,我降低了一些变量,但是在这里。这是我当前的代码:

import os
import random
from abc import ABC
import numpy as np
from gym import Env
from gym.spaces import Discrete, Box
from rl.agents import DQNAgent
from rl.memory import SequentialMemory
from rl.policy import BoltzmannQPolicy
from tensorflow.keras.layers import Dense, Flatten
from tensorflow.keras.models import Sequential
from tensorflow.keras.optimizers import Adam

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'

# Step per episode
steps = 10000
# Number of episodes
episodes = 100
# Score requirement per episode
# Used for stats and to filter training data
score_requirement = 1000


# Creates a Model that emulates a Markov Decision Process
# Finite process -> steps
# Rewards for watering well and punishes for watering bad
# Action -> Observation -> Reward
class PlantEnv(Env, ABC):
    def __init__(self):
        # Actions = water: 0=(none), 1=(3 seconds), 2=(4 seconds), 3=(5 seconds), 4=(6 seconds)
        self.action_space = Discrete(5)

        # Starting Moisture
        moisture = 20 + random.randint(-10, 10)
        # Starting Chance of Rain
        chance_of_rain = 50 + random.randint(-50, 50)

        # Observations
        self.observation_space = Box(low=np.array([0, 0]), high=np.array([100, 100]), dtype=np.int)
        self.state = moisture, chance_of_rain

        # Number of water steps left
        self.water_length = steps

    def step(self, action):
        # Action section
        water = 0

        if action == 1:
            water = 2
        elif action == 2:
            water = 3
        elif action == 3:
            water = 4
        elif action == 4:
            water = 5

        # Retrieve previous state
        moisture, chance_of_rain = self.state

        # The lower/higher this is, greatly affects the scoring
        #  5 or 6 is the best with this setup
        moisture += (water * 5)
        self.water_length -= 1

        # Reward Section
        reward = 0
        if 40 <= moisture <= 60:
            reward = 2
        # If moisture is dry or wet
        elif 60 < moisture <= 80 or 20 <= moisture < 40:
            reward = 1
        # If moisture is really dry or really wet
        elif 80 < moisture <= 100 or 0 <= moisture < 20:
            reward = -1
        # If moisture is really dry or really wet
        elif 100 < moisture or moisture < 0:
            reward = -2

        # Check if shower is done
        if self.water_length <= 0:
            done = True
        else:
            done = False

        # Apply noise to test program
        # Simulate real-life conditions: evaporation, water loss, rain
        # Not used in final program
        moistureLoss = random.randint(15, 25)
        moisture -= moistureLoss
        # Simulate chance of rain
        chance_of_rain = 50 + random.randint(-50, 50)
        xfactor = chance_of_rain + random.randint(-50, 50)
        if xfactor > 100:
            moisture += (10 + random.randint(0, 15))

        # Set placeholder for info
        info = {}

        # Save current state
        self.state = moisture, chance_of_rain

        # Return step information
        return self.state, reward, done, info

    def reset(self):
        # Reset test environment
        # Set starting moisture
        moisture = 50 + random.randint(-10, 10)
        # Set starting chance of rain array
        chance_of_rain = 50 + random.randint(-50, 50)
        self.state = moisture, chance_of_rain
        # Reset Test time
        self.water_length = steps
        return self.state


# # Builds a model using previously defined states and actions
# def build_model():
#     inputs = Input(shape=(1, 2), name="input")
#     inputsF = Flatten()(inputs)
#     common = Dense(24, activation="relu", name="state")(inputsF)
#     action = Dense(5, activation="softmax", name="action")(common)
#     critic = Dense(1, name="output")(common)
#     model = keras.Model(inputs=inputs, outputs=[action, critic])
#     return model

# Build Model
def build_model():
    model = Sequential()
    model.add(Flatten(input_shape=(1, 2)))
    model.add(Dense(24, activation='relu'))
    model.add(Dense(48, activation='relu'))
    model.add(Dense(5, activation='linear'))
    return model


# Build Agent
def build_agent(model):
    policy = BoltzmannQPolicy()
    memory = SequentialMemory(limit=1000, window_length=1)
    dqn = DQNAgent(model=model, memory=memory, policy=policy, nb_actions=5,
                   nb_steps_warmup=50, target_model_update=1e-3)
    return dqn


# Build Deep-Q-Network
def build_dqn(dqn):
    dqn.compile(Adam(learning_rate=1e-3), metrics=['mae', 'accuracy'])
    dqn.fit(env, nb_steps=2000, visualize=False, verbose=1)
    return dqn


# Create environment
env = PlantEnv()

# Store data to show scoring stats and to use for training.
accepted_scores = []
training_data = []
scores = []
good_episodes = 0

# Create episodes and initiate simulation
for episode in range(1, episodes + 1):
    observation = env.reset()
    done = False
    score = 0
    history = []
    prev_observation = []

    # Print starting moisture to compare to ending moisture
    # print("Start Moisture: {}%".format(observation[0]))
    while not done:
        action = env.action_space.sample()
        # Force action override for plant protection
        if observation[0] > 100:
            action = 0
        elif observation[0] < 0:
            action = 4
        observation, reward, done, info = env.step(action)
        score += reward
        if len(prev_observation) > 0:
            history.append([prev_observation, action])
        prev_observation = observation

    # # Print ending moisture to compare to starting moisture
    # # Then print Episode number and score
    # print("End Moisture  : {}%".format(observation[0]))
    # print('Episode: {}  Score:{}\n'.format(episode, score))

    # Gather scores for episodes scoring above requirement
    if score >= score_requirement:
        good_episodes += 1
        accepted_scores.append(score)
        for data in history:
            if data[1] == 1:
                output = [1]
            else:
                output = [0]

            training_data.append([data[0], output])

    scores.append(score)

# Print number of episodes above score requirement
if len(accepted_scores) > 0:
    print("Average accepted score: ", np.mean(accepted_scores))
    print("Median accepted score : ", np.median(accepted_scores))
print("Episodes above accepted score of {}: {}/{}\n".format(score_requirement, good_episodes, episodes))

# Build Model and print summary
model = build_model()
model.summary()

# # Save Model
# model.save('./testModel1', overwrite=True)
# print("Model saved.")

dqn = build_agent(model)
dqn = build_dqn(dqn)


scores = dqn.test(env, nb_episodes=1, visualize=False)
print(np.mean(scores.history['episode_reward']))

pred = dqn.model.predict(np.expand_dims(np.array([30, 30]), axis=0))



确保模型的输入具有正确的形状。它需要一个 3D 张量,其中第一个维度是批量大小。尝试这个:

test_array = np.random.random((1, 1, 2))
print('Test array --> ', test_array)
print('Predictions --> ', dqn.model.predict(test_array))
Test array -->  [[[0.4636345  0.18498545]]]
Predictions -->  [[-0.01383634  0.006188    0.03987967  0.03497294  0.02642388]]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

model.predict() == ValueError:检查输入时出错:期望 flatten_input 有 3 个维度,但得到形状为 (1, 2) 的数组 的相关文章

  • caffe安装:opencv libpng16.so.16链接问题

    我正在尝试在 Ubuntu 14 04 机器上使用 python 接口编译 caffe 我已经安装了 Anaconda 和 opencvconda install opencv 我还安装了咖啡中规定的所有要求 并更改了注释块makefile
  • 如何在Python + Selenium中获取元素的值

    我在我的 Python 3 6 3 代码中得到了这个 HTML 元素 作为 Selenium网页元素当然 span class ocenaCzastkowa masterTooltip style color 000000 alt 5 sp
  • 在Python中将大文件(25k条目)加载到dict中很慢?

    我有一个大约有 25000 行的文件 它是 s19 格式的文件 每行就像 S214780010 00802000000010000000000A508CC78C 像这样的事情怎么样 我做了一个测试文件 只有一行S21478001000802
  • 我可以同时打开两个 Tkinter Windows 吗?

    可以同时打开2个窗口吗 import tkinter as Tk import random import math root Tk Tk canvas Tk Canvas root background image Tk PhotoIma
  • NumPy 数组与 SQLite

    我在 Python 中见过的最常见的 SQLite 接口是sqlite3 但是有什么东西可以很好地与 NumPy 数组或 rearray 配合使用吗 我的意思是 它可以识别数据类型 不需要逐行插入 并提取到 NumPy rec 数组中 有点
  • 获取字符串模板中所有标识符列表的函数(Python)

    对于标准库string template在Python中 有没有一个函数可以获取所有标识符的列表 例如 使用以下 xml 文件
  • 无法使用Python请求会话模块登录网站

    我刚刚开始进行网络抓取 对于我的第一个项目 我尝试使用 requests Session 登录 artofproblemsolving com 并访问另一个用户的帐户 这是我的代码 import requests LOGIN URL htt
  • 如何在Python中手动对数字列表进行排序?

    规格 Ubuntu 13 04 Python 3 3 1 背景 Python的初学者 遇到了这个 手动排序 问题 我被要求做的事情 让用户输入 3 个数值并将它们存储在 3 个不同的变量中 不使用列表或排序算法 手动将这 3 个数字从小到大
  • 使用 python 从 CSV 创建字典

    我有一个 CSV 格式的文件 其中 A B 和 C 是标题 我如何以Python方式将此CSV转换为以下形式的字典 A 1 B 4 C 7 A 2 B 5 C 8 A 3 B 6 C 9 到目前为止我正在尝试以下代码 import csv
  • Python FTP下载550错误

    我编写了一个 ftp 爬虫来下载特定文件 它会一直工作 直到找到要下载的特定文件 然后抛出此错误 ftplib error perm 550 该文件存在于我的下载文件夹中 但文件大小为 0 kb 我需要转换某些内容才能下载吗 我可以访问 f
  • 机器学习的周期性数据(例如度角 -> 179 与 -179 相差 2)

    我使用 Python 进行核密度估计 并使用高斯混合模型对多维数据样本的可能性进行排名 每一条数据都是一个角度 我不确定如何处理机器学习的角度数据的周期性 首先 我通过添加 360 来删除所有负角 因此所有负角都变成了正角 179 变成了
  • 增强迪基-富勒测试中的 BIC 在 Python 中到底是如何工作的?

    这个问题是关于 statsmodels tsa stattools python 库 adfuller 中的增强迪基 富勒测试实现 原则上 AIC 和 BIC 应该计算一组可用模型的信息标准 并选择最好的模型 信息损失最低的模型 但它们在增
  • 将 str.contains 映射到 pandas DataFrame

    python 初学者 我正在寻找创建字符串的字典映射以及关联的值 我有一个数据框 想要创建一个新列 如果字符串匹配 则会将该列标记为 x df pd DataFrame comp dell notebook dell notebook S3
  • 如何将 pandas DataFrame 转换为 TimeSeries?

    我正在寻找一种将 DataFrame 转换为 TimeSeries 而不拆分索引和值列的方法 有任何想法吗 谢谢 In 20 import pandas as pd In 21 import numpy as np In 22 dates
  • 解析整数集的字符串并列出间隔

    I have 2 5 7 9 12 string 我想从中获取 2 5 7 8 9 12 列表 python中有没有内置的函数 Thanks UPD 我想 直接的答案是No 不管怎样 谢谢你的 片段 使用一个 建议者斯文 马尔纳克 s 2
  • 在 4K 屏幕上使用 Matplotlib 和 TKAgg 或 Qt5Agg 后端

    我在 Ubuntu 16 04 上使用 Matplotlib 2 0 和 Python 3 6 来创建数据图 电脑显示器的分辨率为 4k 分辨率为 3840x2160 绘图数字看起来非常小 字体也很小 我已经尝试过TKAgg and Qt5
  • 为数据集生成随机 JSON 结构排列

    我想生成 JSON 结构的许多不同排列作为同一数据集的表示 最好不需要对实现进行硬编码 例如 给定以下 JSON name smith occupation agent enemy humanity nemesis neo 应该产生许多不同
  • JSONDecodeError:额外数据:Python [重复]

    这个问题在这里已经有答案了 我使用以下代码从文件加载 json file file name obj list with open file as f for json obj in f obj list append loads json
  • 如何在不同的目录中执行python脚本?

    Solved对于可能觉得这有帮助的人 请参阅下面我的答案 我有两个脚本 a py 和 b py 在我当前的目录 C Users MyName Desktop MAIN 中 我运行 gt python a py 第一个脚本 a py 在我当前
  • 如何使 Django 自定义管理命令参数不再需要?

    我正在尝试在 django 中编写自定义管理命令 如下所示 class Command BaseCommand def add arguments self parser parser add argument delay type int

随机推荐