当batchsize> 8时,InvalidArgumentError如何在generator中正确使用batchsize?

如何解决当batchsize> 8时,InvalidArgumentError如何在generator中正确使用batchsize?

当我以批处理大小大于1运行这些生成器(对于LSTM)时,出现以下错误:

InvalidArgumentError:  Incompatible shapes: [8,30,10] vs. [8,10]
     [[node sub (defined at ....py:72) ]] [Op:__inference_train_function_6469] 

Function call stack:
train_function


# EDIT:
# solverd
# But now I get:

InvalidArgumentError:  Incompatible shapes: [8] vs. [0]
     [[node gradient_tape/mean_squared_error/weighted_loss/BroadcastGradientArgs (defined at ....py:76) ]] [Op:__inference_train_function_400935]

Function call stack:
train_function

#for this setup:
#Input shape is:  (3,33)
model.add(LSTM( 32,input_shape= (3,33),return_sequences= True ))
model.add(Dropout( 0.3 ));
model.add(BatchNormalization())
model.add(LSTM( 16 )) 
model.add(Dropout( 0.2 ));
model.add(BatchNormalization())
model.add(Dense( 6,activation= tanh )) 
 

Model: "sequential_23"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
lstm_46 (LSTM)               (None,3,32)             8448      
_________________________________________________________________
dropout_34 (Dropout)         (None,32)             0         
_________________________________________________________________
batch_normalization_43 (Batc (None,32)             128       
_________________________________________________________________
lstm_47 (LSTM)               (None,16)                3136      
_________________________________________________________________
dropout_35 (Dropout)         (None,16)                0         
_________________________________________________________________
batch_normalization_44 (Batc (None,16)                64        
_________________________________________________________________
dense_23 (Dense)             (None,6)                 102       
=================================================================
Total params: 11,878
Trainable params: 11,782
Non-trainable params: 96

“ MyGenerator_with_SampleWeights”使用(一维数组)作为每个样本的权重,而另一个则不使用。

如果您发现一些有助于提高这两个生成器效率的方法,我也感到非常高兴。

class MyGenerator_with_SampleWeights(tf.keras.utils.Sequence) :
    def __init__(self,list_x,labels,batch_size,sample_weights=None) : 
        self.labels         = labels
        self.batch_size     = batch_size
        self.list_x         = list_x
        self.sample_weights = sample_weights
        
    def __len__(self) :
        return (np.ceil(len(self.list_x) / float(self.batch_size))).astype(np.int)
    def __getitem__(self,idx) :
        batch_x      = self.list_x[idx * self.batch_size : (idx+1) * self.batch_size]
        batch_y      = self.labels[idx * self.batch_size : (idx+1) * self.batch_size]
        batch_weight = self.sample_weights[idx * self.batch_size : (idx+1) * self.batch_size]
        return np.array(batch_x),np.array(batch_y),np.array(batch_weight)

class MyGenerator(tf.keras.utils.Sequence) :
    def __init__(self,batch_size) : 
        self.labels         = labels
        self.batch_size     = batch_size
        self.list_x         = list_x 
        
    def __len__(self) :
        return (np.ceil(len(self.list_x) / float(self.batch_size))).astype(np.int)
    def __getitem__(self,idx) :
        batch_x      = self.list_x[idx * self.batch_size : (idx+1) * self.batch_size]
        batch_y      = self.labels[idx * self.batch_size : (idx+1) * self.batch_size] 
        return np.array(batch_x),np.array(batch_y)

这是一个最小的可重现样品: (还要从上方复制生成器)

import tensorflow as tf,numpy as np; 
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense,Dropout,LSTM,BatchNormalization
from tensorflow.keras.callbacks import TensorBoard,ModelCheckpoint 
path= r"C:\Users\User\documents\somefolder"  # <--- your path 

model = Sequential()
model.add(LSTM(500,input_shape=X_shapes,return_sequences=True))
model.add(Dropout(0.1)); model.add(BatchNormalization())   
model.add(LSTM(100))
model.add(Dropout(0.1)); model.add(BatchNormalization()) 
model.add(Dense(Y_cols,activation='tanh')); model.add(Dropout(0.2))

optimizer = tf.keras.optimizers.Adam(lr=0.005,decay=1e-7)
model.compile(loss='mean_squared_error',optimizer=optimizer,metrics=['mae'])

BATCH_SIZE  = 8
X_shapes = (30,5)
EPOCHS      = 3
Y_cols,len_X,len_Y = 10,1000,200
train_X,train_Y = np.asarray([np.random.random(X_shapes) for x in range(len_X)]),np.random.random((len_X,Y_cols))
validation_X,validation_Y = np.asarray([np.random.random(X_shapes) for x in range(len_Y)]),np.random.random((len_Y,Y_cols))
weight_arr = np.random.random((len_X,1))

tb = TensorBoard(path)
cp = ModelCheckpoint(path,monitor='val_loss',verbose=1,save_best_only=True,mode='min') 
    
if weight_arr is None:
    train_gen = MyGenerator(train_X,train_Y,BATCH_SIZE)
else:
    train_gen   = MyGenerator_with_SampleWeights(train_X,BATCH_SIZE,sample_weights=weight_arr) 
validation_gen  = MyGenerator(validation_X,validation_Y,BATCH_SIZE)
 
model.fit_generator(train_gen,steps_per_epoch=None,epochs=EPOCHS,validation_data = validation_gen,callbacks=[tb,cp]) 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-