>从互联网帮助我试图从头开始设计密集层.但我得到了一个错误,如下所示,请帮助我解决它.我在这里发布了全部代码.请帮帮我.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import tensorflow
import os
import keras
import tensorflow as tf
import numpy as np
import pickle,time
from tensorflow.keras.utils import to_categorical
from keras.datasets import cifar10
(x_train, y_train), (x_test,y_test) = cifar10.load_data()
x_train = x_train/255.0
x_test = x_test/255.0
y_train= to_categorical(y_train,37)
y_test= to_categorical(y_test,37)
batch_size = 16
epochs = 20
learning_rate=0.001
nfilters = [45]
sfilters = [2]
def H( inputs, num_filters , dropout_rate ):
x = tf.keras.layers.BatchNormalization( epsilon=eps )( inputs )
x = tf.keras.layers.Activation('relu')(x)
x = tf.keras.layers.ZeroPadding2D((1, 1))(x)
x = tf.keras.layers.Conv2D(num_filters, kernel_size=(3, 3), use_bias=False , kernel_initializer='he_normal' )(x)
x = tf.keras.layers.Dropout(rate=dropout_rate )(x)
return x
def transition(inputs, num_filters , compression_factor , dropout_rate ):
# compression_factor is the 'θ'
x = tf.keras.layers.BatchNormalization( epsilon=eps )(inputs)
x = tf.keras.layers.Activation('relu')(x)
num_feature_maps = inputs.shape[1] # The value of 'm'
x = tf.keras.layers.Conv2D( np.floor( compression_factor * num_feature_maps ).astype( np.int ) ,
kernel_size=(1, 1), use_bias=False, padding='same' , kernel_initializer='he_normal' , kernel_regularizer=tf.keras.regularizers.l2( 1e-4 ) )(x)
x = tf.keras.layers.Dropout(rate=dropout_rate)(x)
x = tf.keras.layers.AveragePooling2D(pool_size=(3, 3))(x)
return x
def dense_block( inputs, num_layers, num_filters, growth_rate , dropout_rate ):
for i in range(num_layers): # num_layers is the value of 'l'
conv_outputs = H(inputs, num_filters , dropout_rate )
inputs = tf.keras.layers.Concatenate()([conv_outputs, inputs])
num_filters += growth_rate # To increase the number of filters for each layer.
return inputs, num_filters
class CNN(tf.keras.Model):
def __init__(self,nfilters,sfilters):
super(CNN,self).__init__()
#tf.random.set_seed(0)
self.conv1 = tf.keras.layers.Conv2D(nfilters[0] , kernel_size=(sfilters[0],sfilters[0]) , use_bias=False, kernel_initializer='he_normal', kernel_regularizer=tf.keras.regularizers.l2( 1e-4 ) )
#self.dense_block = dense_block(self, sfilters[0] , num_filters, growth_rate , dropout_rate )
#self.transition = transition(self,num_filters , compress_factor , dropout_rate )
self.globalaverage = tf.keras.layers.GlobalAveragePooling2D()
self.dense = tf.keras.layers.Dense(37) # Num Classes for CIFAR-10
self.activation = tf.keras.layers.Activation( 'softmax' )
def call(self, input_tensor, training=False):
global num_filters
x = self.conv1(input_tensor)
for i in range( num_blocks ):
x, num_filters = dense_block( x, num_layers_per_block , num_filters, growth_rate , dropout_rate )
x = transition(x, num_filters , compress_factor , dropout_rate )
x = self.globalaverage( x )
x = self.dense( x ) # Num Classes for CIFAR-10
return self.activation( x )
input_shape = x_train.shape[1:]
num_blocks = 1
num_layers_per_block = 3
growth_rate = 8
dropout_rate = 0.6
compress_factor = 0.5
eps = 1.1e-5
num_filters = 8
model = CNN(nfilters,sfilters)
model.compile(loss=tf.keras.losses.categorical_crossentropy ,optimizer=tf.keras.optimizers.Adam( lr=0.001 ) ,metrics=[ 'acc' ])
model.build(x_train.shape)
model.summary()
H = model.fit(x_train,y_train,batch_size=batch_size,epochs=epochs)
I am getting this errors
> ValueError回溯(最近一次调用gt last)> gt<iphon-input-26-fac936e4654b> in<module>()> 90模型.构建(x_列车形状)> 91模型.summary()>---> 92 H=模型.fit(x_u-train,y_u-train,batch_u-size=batch_u-size,epochs=epochs)>> 1帧>>/usr/local/lib/python3.7/dist-packages/tensorflow/python/framework/func_u图.自动签名处理程序中的py>(*args,kwargs)1145,但作为e的异常除外:#pylint:disable=broad,除非1146,如果> hasattr(e,"ag_error_u元数据"):>-> 1147提升e.ag_error_u元数据.to_exception(e)1148 else:1149 raise>>值错误:在用户代码中:>>文件/usr/local/lib/python3.7/dist-packages/keras/engine/training.py",>行1021,在train_u函数中> return step_u函数(self,iterator)>文件/usr/local/lib/python3.7/dist-packages/keras/engine/training.py",>行1010,在step_u函数中>输出=模型.分布式策略.run(run_step,args=(data,)> File"/usr/local/lib/python3.7/dist-packages/keras/engine/training.py",>第1000行,在run_u步骤> outputs=model.train_step(data)> File"/usr/local/lib/python3.7/dist-packages/keras/engine/training.py",>第859行,在train_step中> y_pred=self(x,training=True)> File"/usr/local/lib/python3.7/dist-packages/keras/utils/traceback_utils.py",>第67行,在error_handler> raise e.with_traceback(filtered_tb)from None>> ValueError:调用层"cnn_3"(键入cnn)时遇到异常&燃气轮机 >在用户代码中:> > File"<iphon-input-26-fac936e4654b>",第71行,in call> x,num_filters=dense_block(x,num_layers_per_block,num_filters,growth_rate,dropout_rate)> File"<iphon-input-26-fac936e4654b>",第49行,in dense_block> conv_outputs=H(inputs,num filters,dropout_rate)> File"<iphon-input-26-fac936e4654544b>",第29行,in H.> x=tf.克拉斯.层.BatchNormalization(epsilon=eps)(inputs)> File/usr/local/lib/python3.7/dist packages/keras/utils/traceback_utils.py",>第67行,在error_handler中>从None提升e.with_traceback(filtered_tb)> >值错误:tf.函数仅支持单例tf.第一次调用时创建的变量.确保tf.变量仅创建一次>,或在tf外部创建.作用请参阅(>)https://www.tensorflow.org/guide/function#creating_tfvariables了解更多信息&燃气轮机 &燃气轮机 &收到的gt调用参数:>•输入张量=tf.张量(形状=(16,32,32,3),dtype=float32)>•训练=True