简体   繁体   English

平方 X Tensorflow 模型

[英]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)我正在学习 Tensorflow 2,但无法完成一项非常基本的任务,我想训练我的模型,以便计算给定数字的平方值 (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):所以我的错误在于我希望我的模型会返回平方值而不是斜率(y = x * slop + bias),这是固定版本(有效):

    # 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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