简体   繁体   中英

Squared X Tensorflow Model

I'm learning Tensorflow 2 and cannot accomplish a very basic task, I want to train my model so it would calculate the squared value of a given number (y=x*x)

Here is my code:


    # random vector of inputs
    x = tf.random.uniform((1000,), minval=-100, maxval=100, dtype='int32')
    # labels (squared input)
    y = tf.convert_to_tensor(list(n * n for n in x))

    model = keras.Sequential([
        keras.layers.Dense(1),
    ])

    model.compile(loss=keras.losses.binary_crossentropy, optimizer='adam')
    model.fit(x, y, epochs=5, batch_size=50)

    print(model.predict([2]))

Why it doesn't work?

So my error was in that I expected my model would return the squared value instead of the slope (y = x * slop + bias), here is the fixed version (that works):

    # random vector of inputs
    x = tf.random.uniform((1000,), minval=-100, maxval=100, dtype='int32')
    # labels (slops)
    y = tf.convert_to_tensor(list(n for n in x))

    model = keras.Sequential([
        keras.layers.Dense(1)
    ])

    model.compile(optimizer='adam', loss='mean_absolute_error')

    model.fit(x, y, epochs=10, batch_size=50)

    print(2 * int(model.predict([2])))

>4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM