首页 > 解决方案 > How to train model using tensorflow.keras in Python 3?

问题描述

I want to train model using Sequential and Dense provided by tensorflow.keras library. I have tried this:

from tensorflow.keras import Sequential
from tensorflow.keras.layers import Dense

model = Sequential()
model.add(Dense(32, input_shape=(2,), activation='relu'))
model.add(Dense(16, activation='relu'))
model.add(Dense(1, activation='sigmoid'))

model.compile(loss="binary_crossentropy", optimizer="adam", metrics=["accuracy"])

print("Train X")
print(trainX)
print("Train Y")
print(trainY)

model.fit(trainX, trainY, epochs=150, batch_size=64)

To visualize my trainX and trainY, there it is the print results:

Train X
[[array([0.        , 1.        , 0.74858224, 0.7930363 , 0.7781208 ,
       0.7797821 , 0.80437887, 0.79465854, 0.8112153 , 0.79861283,
       0.7892152 , 0.8047467 , 0.79931486], dtype=float32) #array1d 13 length
  array([1., 1., 1., ..., 1., 1., 1.], dtype=float32)] #array1d 4096 length
 [array([0.        , 1.        , 0.78938663, 0.8871767 , 0.8864205 ,
       0.8544437 , 0.87749857, 0.86471486, 0.8644276 , 0.85352105,
       0.84812653, 0.86479014, 0.85331386], dtype=float32)
  array([1., 1., 1., ..., 1., 1., 1.], dtype=float32)]
 [array([0.        , 1.        , 0.7598003 , 0.836788  , 0.8227602 ,
       0.8243963 , 0.83666295, 0.79830813, 0.8127302 , 0.8106634 ,
       0.80431014, 0.8150548 , 0.8016478 ], dtype=float32)
  array([1., 1., 1., ..., 1., 1., 1.], dtype=float32)]
 ...
 [array([0.        , 1.        , 0.8446178 , 0.8453315 , 0.8611171 ,
       0.85805404, 0.8642554 , 0.86262083, 0.85664994, 0.8561216 ,
       0.859685  , 0.85963935, 0.85896343], dtype=float32)
  array([1., 1., 1., ..., 1., 1., 1.], dtype=float32)]
 [array([0.        , 1.        , 0.69153315, 0.83713776, 0.75600296,
       0.7540438 , 0.80176806, 0.74226856, 0.76164556, 0.7642133 ,
       0.7565041 , 0.7707479 , 0.75812143], dtype=float32)
  array([1., 1., 1., ..., 1., 1., 1.], dtype=float32)]
 [array([0.        , 1.        , 0.92892283, 0.9767726 , 0.9398309 ,
       0.9516973 , 0.96030724, 0.9374307 , 0.95159173, 0.9480775 ,
       0.9421067 , 0.9474583 , 0.9451861 ], dtype=float32)
  array([1., 1., 1., ..., 1., 1., 1.], dtype=float32)]]
Train Y
[[0.]  #array1d 1 length
 [0.]
 [0.]
 ...
 [0.]
 [0.]
 [0.]]

But i got this error:

------------------------------------------------------
ValueError           Traceback (most recent call last)
~\AppData\Local\Temp/ipykernel_2124/155013707.py in <module>
     14 print(trainY)
     15 
---> 16 model.fit(trainX, trainY, epochs=150, batch_size=64)

C:\Python39\lib\site-packages\tensorflow\python\keras\engine\training.py in fit(self, x, y, batch_size, epochs, verbose, callbacks, validation_split, validation_data, shuffle, class_weight, sample_weight, initial_epoch, steps_per_epoch, validation_steps, validation_batch_size, validation_freq, max_queue_size, workers, use_multiprocessing)
   1131          training_utils.RespectCompiledTrainableState(self):
   1132       # Creates a `tf.data.Dataset` and handles batch and epoch iteration.
-> 1133       data_handler = data_adapter.get_data_handler(
   1134           x=x,
   1135           y=y,

C:\Python39\lib\site-packages\tensorflow\python\keras\engine\data_adapter.py in get_data_handler(*args, **kwargs)
   1362   if getattr(kwargs["model"], "_cluster_coordinator", None):
   1363     return _ClusterCoordinatorDataHandler(*args, **kwargs)
-> 1364   return DataHandler(*args, **kwargs)
   1365 
   1366 

C:\Python39\lib\site-packages\tensorflow\python\keras\engine\data_adapter.py in __init__(self, x, y, sample_weight, batch_size, steps_per_epoch, initial_epoch, epochs, shuffle, class_weight, max_queue_size, workers, use_multiprocessing, model, steps_per_execution, distribute)
   1152     adapter_cls = select_data_adapter(x, y)
   1153     self._verify_data_adapter_compatibility(adapter_cls)
-> 1154     self._adapter = adapter_cls(
   1155         x,
   1156         y,

C:\Python39\lib\site-packages\tensorflow\python\keras\engine\data_adapter.py in __init__(self, x, y, sample_weights, sample_weight_modes, batch_size, epochs, steps, shuffle, **kwargs)
    245                **kwargs):
    246     super(TensorLikeDataAdapter, self).__init__(x, y, **kwargs)
--> 247     x, y, sample_weights = _process_tensorlike((x, y, sample_weights))
    248     sample_weight_modes = broadcast_sample_weight_modes(
    249         sample_weights, sample_weight_modes)

C:\Python39\lib\site-packages\tensorflow\python\keras\engine\data_adapter.py in _process_tensorlike(inputs)
   1044     return x
   1045 
-> 1046   inputs = nest.map_structure(_convert_numpy_and_scipy, inputs)
   1047   return nest.list_to_tuple(inputs)
   1048 

C:\Python39\lib\site-packages\tensorflow\python\util\nest.py in map_structure(func, *structure, **kwargs)
    865 
    866   return pack_sequence_as(
--> 867       structure[0], [func(*x) for x in entries],
    868       expand_composites=expand_composites)
    869 

C:\Python39\lib\site-packages\tensorflow\python\util\nest.py in <listcomp>(.0)
    865 
    866   return pack_sequence_as(
--> 867       structure[0], [func(*x) for x in entries],
    868       expand_composites=expand_composites)
    869 

C:\Python39\lib\site-packages\tensorflow\python\keras\engine\data_adapter.py in _convert_numpy_and_scipy(x)
   1039       if issubclass(x.dtype.type, np.floating):
   1040         dtype = backend.floatx()
-> 1041       return ops.convert_to_tensor_v2_with_dispatch(x, dtype=dtype)
   1042     elif _is_scipy_sparse(x):
   1043       return _scipy_sparse_to_sparse_tensor(x)

C:\Python39\lib\site-packages\tensorflow\python\util\dispatch.py in wrapper(*args, **kwargs)
    204     """Call target, and fall back on dispatchers if there is a TypeError."""
    205     try:
--> 206       return target(*args, **kwargs)
    207     except (TypeError, ValueError):
    208       # Note: convert_to_eager_tensor currently raises a ValueError, not a

C:\Python39\lib\site-packages\tensorflow\python\framework\ops.py in convert_to_tensor_v2_with_dispatch(value, dtype, dtype_hint, name)
   1428     ValueError: If the `value` is a tensor not of given `dtype` in graph mode.
   1429   """
-> 1430   return convert_to_tensor_v2(
   1431       value, dtype=dtype, dtype_hint=dtype_hint, name=name)
   1432 

C:\Python39\lib\site-packages\tensorflow\python\framework\ops.py in convert_to_tensor_v2(value, dtype, dtype_hint, name)
   1434 def convert_to_tensor_v2(value, dtype=None, dtype_hint=None, name=None):
   1435   """Converts the given `value` to a `Tensor`."""
-> 1436   return convert_to_tensor(
   1437       value=value,
   1438       dtype=dtype,

C:\Python39\lib\site-packages\tensorflow\python\profiler\trace.py in wrapped(*args, **kwargs)
    161         with Trace(trace_name, **trace_kwargs):
    162           return func(*args, **kwargs)
--> 163       return func(*args, **kwargs)
    164 
    165     return wrapped

C:\Python39\lib\site-packages\tensorflow\python\framework\ops.py in convert_to_tensor(value, dtype, name, as_ref, preferred_dtype, dtype_hint, ctx, accepted_result_types)
   1564 
   1565     if ret is None:
-> 1566       ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)
   1567 
   1568     if ret is NotImplemented:

C:\Python39\lib\site-packages\tensorflow\python\framework\tensor_conversion_registry.py in _default_conversion_function(***failed resolving arguments***)
     50 def _default_conversion_function(value, dtype, name, as_ref):
     51   del as_ref  # Unused.
---> 52   return constant_op.constant(value, dtype, name=name)
     53 
     54 

C:\Python39\lib\site-packages\tensorflow\python\framework\constant_op.py in constant(value, dtype, shape, name)
    262     ValueError: if called on a symbolic tensor.
    263   """
--> 264   return _constant_impl(value, dtype, shape, name, verify_shape=False,
    265                         allow_broadcast=True)
    266 

C:\Python39\lib\site-packages\tensorflow\python\framework\constant_op.py in _constant_impl(value, dtype, shape, name, verify_shape, allow_broadcast)
    274       with trace.Trace("tf.constant"):
    275         return _constant_eager_impl(ctx, value, dtype, shape, verify_shape)
--> 276     return _constant_eager_impl(ctx, value, dtype, shape, verify_shape)
    277 
    278   g = ops.get_default_graph()

C:\Python39\lib\site-packages\tensorflow\python\framework\constant_op.py in _constant_eager_impl(ctx, value, dtype, shape, verify_shape)
    299 def _constant_eager_impl(ctx, value, dtype, shape, verify_shape):
    300   """Implementation of eager constant."""
--> 301   t = convert_to_eager_tensor(value, ctx, dtype)
    302   if shape is None:
    303     return t

C:\Python39\lib\site-packages\tensorflow\python\framework\constant_op.py in convert_to_eager_tensor(value, ctx, dtype)
     96       dtype = dtypes.as_dtype(dtype).as_datatype_enum
     97   ctx.ensure_initialized()
---> 98   return ops.EagerTensor(value, ctx.device_name, dtype)
     99 
    100 

ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type numpy.ndarray).

I'm still a rookie in Machine Learning, i think there is something wrong with the feature input because i put it in array. Btw that is the model receiving 2 feature A (array) and B (array) as input and C as predictions (true or false). How to fix this so i can make a prediction model?

标签: pythontensorflowkeraspython-3.9

解决方案


如果您的数据有 2 个特征,那么您的 TrainX 的形状需要是(观察次数(例如 n),2)。因此尝试

TrainX = TrainX.flatten().reshape(n, 2)

如果您的火车 X 有很多列,那么您的网络需要如下所示:

model = Sequential()
model.add(Dense(32, input_shape=(trainX.shape[1],), activation='relu'))

最后,您可能需要对 fit 函数进行一些更改

model.fit(trainX, np.ravel(trainY), epochs=150, batch_size=64) # as y works here for a 1d array

推荐阅读