我正在尝试使用tensorflow编写的深度神经网络的for循环。我已经尝试过手动将每一层相乘。工作正常。但是为了使其具有吸引力,我试图在OOP中使其成为Keras风格。但是出现形状错误。谁能解释这里出了什么问题?
对我来说,我是新来的。因此,如果我在代码中做了任何愚蠢的事情,请原谅我。
class Sequential_Model:
def __init__(self):
self.__current_layer = -1
self.__weights = list()
self.__biases = list()
self.__dropout = list()
self.__l1_regularizer = list()
self.__l2_regularizer = list()
self.__activation = list()
def Add_Dense_layer(self, input_shape, output_shape, activation_function = 'leaky_relu', dropout_rate = 0.0):
self.__current_layer = self.__current_layer + 1
self.__weights.append(tf.Variable(tf.random.truncated_normal([input_shape, output_shape], 0.1)))
self.__biases.append(tf.Variable(tf.ones([output_shape])))
self.__activation.append((self.__current_layer, activation_function))
self.__dropout.append((self.__current_layer , dropout_rate))
def Add_L1_Regularize():
pass
def Add_L2_Regularize():
pass
def __rmse(self, predictions , label):
return tf.losses.mean_squared_error(predictions, label)
def __train(self, train_data, train_label, validation_data, validation_label, epochs, batch_size):
print(train_data.shape)
print(train_label.shape)
x_train = tf.placeholder(tf.float32)
y_train = tf.placeholder(tf.float32)
x_valid = tf.placeholder(tf.float32)
y_valid = tf.placeholder(tf.float32)
output = tf.add(tf.matmul(x_train, self.__weights[0]) , self.__biases[0])
if self.__activation[0][1] == 'relu':
output = tf.nn.relu(output)
elif self.__activation[0][1] == 'leaky_relu':
output = tf.nn.relu(output)
if self.__dropout[0][1] != 0.0 :
output = tf.layers.dropout(output, self.__dropout[0][1])
for i in range(1, self.__current_layer + 1):
output = tf.add(tf.matmul(output, self.__weights[i]) , self.__biases[i])
if self.__activation[i][1] == 'relu':
output = tf.nn.relu(output)
elif self.__activation[i][1] == 'leaky_relu':
output = tf.nn.leaky_relu(output)
if self.__dropout[i][1] != 0.0 :
output = tf.layers.dropout(output, self.__dropout[i][1])
#if self.__loss == 'rmse':
#loss = self.__rmse(output , y_train)
loss = tf.losses.mean_squared_error(output, y_train)
#if self.__optimizer == 'adam':
optimizer = tf.train.AdamOptimizer(learning_rate=self.__learning_rate).minimize(loss)
init = tf.global_variables_initializer()
with tf.Session() as sess:
# create initialized variables
sess.run(init)
for epoch in range(epochs+1):
avg_cost = 0.0
total_num_batch = train_data.shape[0]//batch_size
for index, offset in enumerate(range(0, train_data.shape[0], batch_size)):
xs, ys = train_data[offset: offset + batch_size], train_label[offset: offset + batch_size]
#print(xs.shape)
_, cost = sess.run([optimizer, loss], feed_dict = {x_train: xs, y_train: np.reshape( ys, (-1, 1))})
avg_cost += (cost / total_num_batch)
if epoch % 20 == 0:
print("Epoch:", (epoch), "cost =", "{:.5f}".format(avg_cost))
def fit(self,train_data, train_label, epochs = 100, batch_size = 24, validation_data = (None, None), validation_size = 0.1):
if validation_data[0] == None or validation_data[1] == None:
train_data, validation_data, train_lable, validation_label = train_test_split(train_data, train_label,
test_size = validation_size)
self.__train(train_data, train_label, validation_data, validation_label, epochs, batch_size)
def compile(self, loss='rmse', optimizer='adam', learning_rate = 0.01):
self.__loss = loss
self.__optimizer = optimizer
self.__learning_rate = learning_rate
model = Sequential_Model()
model.Add_Dense_layer(input_shape=74 , output_shape=74, activation_function='leaky_relu', dropout_rate=0.2)
model.Add_Dense_layer(input_shape=74 , output_shape=37, activation_function='leaky_relu', dropout_rate=0.2)
model.Add_Dense_layer(input_shape=37, output_shape=15, activation_function='leaky_relu', dropout_rate=0.2)
model.Add_Dense_layer(input_shape=15, output_shape=7, activation_function='leaky_relu', dropout_rate=0.1)
model.Add_Dense_layer(input_shape=7, output_shape=1, activation_function='leaky_relu', dropout_rate=0.1)
model.compile(learning_rate=0.001)
model.fit(train_data=X_train, train_label=Y_train)
---------------------------------------------------------------------------
InvalidArgumentError Traceback (most recent call last)
D:\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in _do_call(self, fn, *args)
1333 try:
-> 1334 return fn(*args)
1335 except errors.OpError as e:
D:\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in _run_fn(feed_dict, fetch_list, target_list, options, run_metadata)
1318 return self._call_tf_sessionrun(
-> 1319 options, feed_dict, fetch_list, target_list, run_metadata)
1320
D:\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in _call_tf_sessionrun(self, options, feed_dict, fetch_list, target_list, run_metadata)
1406 self._session, options, feed_dict, fetch_list, target_list,
-> 1407 run_metadata)
1408
InvalidArgumentError: Incompatible shapes: [24,1] vs. [19,1]
[[{{node mean_squared_error_9/SquaredDifference}} = SquaredDifference[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:GPU:0"](_arg_Placeholder_43_0_1/_1, LeakyRelu_27)]]
[[{{node mean_squared_error_9/num_present/broadcast_weights/assert_broadcastable/AssertGuard/Assert/Switch_2/_15}} = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:CPU:0", send_device="/job:localhost/replica:0/task:0/device:GPU:0", send_device_incarnation=1, tensor_name="edge_121_m...t/Switch_2", tensor_type=DT_INT32, _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]
During handling of the above exception, another exception occurred:
InvalidArgumentError Traceback (most recent call last)
<ipython-input-63-3932e4f6c131> in <module>()
----> 1 model.fit(train_data=X_train, train_label=Y_train)
<ipython-input-60-b65b270e68fd> in fit(self, train_data, train_label, epochs, batch_size, validation_data, validation_size)
105
106
--> 107 self.__train(train_data, train_label, validation_data, validation_label, epochs, batch_size)
108
109
<ipython-input-60-b65b270e68fd> in __train(self, train_data, train_label, validation_data, validation_label, epochs, batch_size)
87 xs, ys = train_data[offset: offset + batch_size], train_label[offset: offset + batch_size]
88 #print(xs.shape)
---> 89 _, cost = sess.run([optimizer, loss], feed_dict = {x_train: xs, y_train: np.reshape( ys, (-1, 1))})
90
91 avg_cost += (cost / total_num_batch)
D:\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in run(self, fetches, feed_dict, options, run_metadata)
927 try:
928 result = self._run(None, fetches, feed_dict, options_ptr,
--> 929 run_metadata_ptr)
930 if run_metadata:
931 proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)
D:\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
1150 if final_fetches or final_targets or (handle and feed_dict_tensor):
1151 results = self._do_run(handle, final_targets, final_fetches,
-> 1152 feed_dict_tensor, options, run_metadata)
1153 else:
1154 results = []
D:\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in _do_run(self, handle, target_list, fetch_list, feed_dict, options, run_metadata)
1326 if handle is None:
1327 return self._do_call(_run_fn, feeds, fetches, targets, options,
-> 1328 run_metadata)
1329 else:
1330 return self._do_call(_prun_fn, handle, feeds, fetches)
D:\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in _do_call(self, fn, *args)
1346 pass
1347 message = error_interpolation.interpolate(message, self._graph)
-> 1348 raise type(e)(node_def, op, message)
1349
1350 def _extend_graph(self):
InvalidArgumentError: Incompatible shapes: [24,1] vs. [19,1]
[[node mean_squared_error_9/SquaredDifference (defined at <ipython-input-60-b65b270e68fd>:69) = SquaredDifference[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:GPU:0"](_arg_Placeholder_43_0_1/_1, LeakyRelu_27)]]
[[{{node mean_squared_error_9/num_present/broadcast_weights/assert_broadcastable/AssertGuard/Assert/Switch_2/_15}} = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:CPU:0", send_device="/job:localhost/replica:0/task:0/device:GPU:0", send_device_incarnation=1, tensor_name="edge_121_m...t/Switch_2", tensor_type=DT_INT32, _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]
Caused by op 'mean_squared_error_9/SquaredDifference', defined at:
File "D:\Anaconda3\lib\runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "D:\Anaconda3\lib\runpy.py", line 85, in _run_code
exec(code, run_globals)
File "D:\Anaconda3\lib\site-packages\ipykernel_launcher.py", line 16, in <module>
app.launch_new_instance()
File "D:\Anaconda3\lib\site-packages\traitlets\config\application.py", line 658, in launch_instance
app.start()
File "D:\Anaconda3\lib\site-packages\ipykernel\kernelapp.py", line 477, in start
ioloop.IOLoop.instance().start()
File "D:\Anaconda3\lib\site-packages\zmq\eventloop\ioloop.py", line 177, in start
super(ZMQIOLoop, self).start()
File "D:\Anaconda3\lib\site-packages\tornado\ioloop.py", line 888, in start
handler_func(fd_obj, events)
File "D:\Anaconda3\lib\site-packages\tornado\stack_context.py", line 277, in null_wrapper
return fn(*args, **kwargs)
File "D:\Anaconda3\lib\site-packages\zmq\eventloop\zmqstream.py", line 440, in _handle_events
self._handle_recv()
File "D:\Anaconda3\lib\site-packages\zmq\eventloop\zmqstream.py", line 472, in _handle_recv
self._run_callback(callback, msg)
File "D:\Anaconda3\lib\site-packages\zmq\eventloop\zmqstream.py", line 414, in _run_callback
callback(*args, **kwargs)
File "D:\Anaconda3\lib\site-packages\tornado\stack_context.py", line 277, in null_wrapper
return fn(*args, **kwargs)
File "D:\Anaconda3\lib\site-packages\ipykernel\kernelbase.py", line 283, in dispatcher
return self.dispatch_shell(stream, msg)
File "D:\Anaconda3\lib\site-packages\ipykernel\kernelbase.py", line 235, in dispatch_shell
handler(stream, idents, msg)
File "D:\Anaconda3\lib\site-packages\ipykernel\kernelbase.py", line 399, in execute_request
user_expressions, allow_stdin)
File "D:\Anaconda3\lib\site-packages\ipykernel\ipkernel.py", line 196, in do_execute
res = shell.run_cell(code, store_history=store_history, silent=silent)
File "D:\Anaconda3\lib\site-packages\ipykernel\zmqshell.py", line 533, in run_cell
return super(ZMQInteractiveShell, self).run_cell(*args, **kwargs)
File "D:\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2698, in run_cell
interactivity=interactivity, compiler=compiler, result=result)
File "D:\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2808, in run_ast_nodes
if self.run_code(code, result):
File "D:\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2862, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-63-3932e4f6c131>", line 1, in <module>
model.fit(train_data=X_train, train_label=Y_train)
File "<ipython-input-60-b65b270e68fd>", line 107, in fit
self.__train(train_data, train_label, validation_data, validation_label, epochs, batch_size)
File "<ipython-input-60-b65b270e68fd>", line 69, in __train
loss = tf.losses.mean_squared_error(output, y_train)
File "D:\Anaconda3\lib\site-packages\tensorflow\python\ops\losses\losses_impl.py", line 671, in mean_squared_error
losses = math_ops.squared_difference(predictions, labels)
File "D:\Anaconda3\lib\site-packages\tensorflow\python\ops\gen_math_ops.py", line 8258, in squared_difference
"SquaredDifference", x=x, y=y, name=name)
File "D:\Anaconda3\lib\site-packages\tensorflow\python\framework\op_def_library.py", line 787, in _apply_op_helper
op_def=op_def)
File "D:\Anaconda3\lib\site-packages\tensorflow\python\util\deprecation.py", line 488, in new_func
return func(*args, **kwargs)
File "D:\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 3274, in create_op
op_def=op_def)
File "D:\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py", line 1770, in __init__
self._traceback = tf_stack.extract_stack()
InvalidArgumentError (see above for traceback): Incompatible shapes: [24,1] vs. [19,1]
[[node mean_squared_error_9/SquaredDifference (defined at <ipython-input-60-b65b270e68fd>:69) = SquaredDifference[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/device:GPU:0"](_arg_Placeholder_43_0_1/_1, LeakyRelu_27)]]
[[{{node mean_squared_error_9/num_present/broadcast_weights/assert_broadcastable/AssertGuard/Assert/Switch_2/_15}} = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/device:CPU:0", send_device="/job:localhost/replica:0/task:0/device:GPU:0", send_device_incarnation=1, tensor_name="edge_121_m...t/Switch_2", tensor_type=DT_INT32, _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]