如何在Tensorflow中训练数据?

时间:2019-05-23 07:57:09

标签: python tensorflow

我是Tensorflow的新成员:

我想训练我的数据以检测图像:

这是我的完整代码,我用来训练模型: 我演示了4张图片,其中2张图片是汽车,2张图片不是汽车。

import tensorflow as tf
from tensorflow import keras
filenames = tf.constant(['C:\DemoTensorflow\Bai1\Images\image1.jpg', 'C:\DemoTensorflow\Bai1\Images\image2.jpg', 'C:\DemoTensorflow\Bai1\Images\image3.jpg', 'C:\DemoTensorflow\Bai1\Images\image4.jpg'])
labels =[0,0,1,1]  # 0 for not_car, 1 for car

# step 2: create a dataset returning slices of `filenames`
dataset = tf.data.Dataset.from_tensor_slices((filenames, labels))

# step 3: parse every image in the dataset using `map`
def _parse_function(filename, label):
    image_string = tf.read_file(filename)
    image_decoded = tf.image.decode_jpeg(image_string, channels=3)
    image = tf.cast(image_decoded, tf.float32)
    return image, label

dataset = dataset.map(_parse_function)
dataset = dataset.batch(2)

# step 4: create iterator and final input tensor
iterator = dataset.make_one_shot_iterator()
images, labels = iterator.get_next()

# Returns a short sequential model
def create_model():
  model = tf.keras.models.Sequential([
    keras.layers.Flatten(input_shape=(28, 28)),
    keras.layers.Dense(128, activation=tf.nn.relu),
    keras.layers.Dense(10, activation=tf.nn.softmax)
  ])

  model.compile(optimizer=tf.keras.optimizers.Adam(),
                loss=tf.keras.losses.sparse_categorical_crossentropy,
                metrics=['accuracy'])

  return model

model = create_model()
model.fit(images, labels, epochs=10, steps_per_epoch=30)
model.save('C:\DemoTensorflow\Bai1\my_model.h5')

火车时发生错误:

WARNING:tensorflow:From C:\python3.6\lib\site-packages\tensorflow\python\ops\res
ource_variable_ops.py:435: colocate_with (from tensorflow.python.framework.ops)
is deprecated and will be removed in a future version.
Instructions for updating:
Colocations handled automatically by placer.
Traceback (most recent call last):
  File "C:\DemoTensorflow\Bai1\tranimagelaotohayko.py", line 38, in <module>
    model.fit(images, labels, epochs=10, steps_per_epoch=30)
  File "C:\python3.6\lib\site-packages\tensorflow\python\keras\engine\training.p
y", line 776, in fit
    shuffle=shuffle)
  File "C:\python3.6\lib\site-packages\tensorflow\python\keras\engine\training.p
y", line 2382, in _standardize_user_data
    exception_prefix='input')
  File "C:\python3.6\lib\site-packages\tensorflow\python\keras\engine\training_u
tils.py", line 353, in standardize_input_data
    'with shape ' + str(data_shape))
ValueError: Error when checking input: expected flatten_input to have 3 dimensio
ns, but got array with shape (None, None, None, 3)

为什么不能训练我的数据?

如何在Tensorflow中训练数据?

0 个答案:

没有答案