Простое DNN для функции Quadrati c в Tensorflow 1 - PullRequest
0 голосов
/ 10 апреля 2020

Я хотел бы смоделировать простую квадратичную c функцию, используя Tensorflow 1.

import numpy as np
import tensorflow.compat.v1 as tf #I'm using tensorflow 1

def testFunc(n): #x^2 
    return n[0] * n[0]

#create train and test set
X_train_small = np.random.uniform(-1.0, 1.0, (25000,1))
y_train_small = np.apply_along_axis(testFunc,1,X_train_small)
X_test_small = np.random.uniform(-1.0, 1.0, (5000,1))
y_test_small = np.apply_along_axis(testFunc,1,X_test_small)


#create Network
tf.disable_v2_behavior()
tf.reset_default_graph()

#input layer
X = tf.placeholder(tf.float32, shape=(None,1), name="X")
y = tf.placeholder(tf.float32, shape=(None), name="y")

with tf.name_scope("dnn"):
    hidden1 = tf.layers.dense(X, 30, name="hidden1", activation=tf.nn.tanh)
    hidden2 = tf.layers.dense(hidden1, 15, name="hidden2", activation=tf.nn.tanh)
    logits = tf.layers.dense(hidden2, 1, name="outputs")

with tf.name_scope("loss"):
    error = logits-y
    loss = tf.reduce_mean(tf.square(error), name="loss") #mse as loss

with tf.name_scope("train"):
    optimizer = tf.train.AdamOptimizer(0.05)
    training_op = optimizer.minimize(loss)

init = tf.global_variables_initializer()
epochs = 50
batch_size = 100
m = X_train_small.shape[0]
n_batches = int(np.ceil(m/batch_size))

with tf.Session() as sess:
    init.run()
    #train the model
    for epoch in range(epochs):
        shuffel = np.random.permutation(m) #used for creating random batches
        for i in range(m//batch_size):
            d = {X : X_train_small[shuffel[i*batch_size:(i+1)*batch_size]], y : y_train_small[shuffel[i*batch_size:(i+1)*batch_size]]}
            sess.run(training_op, feed_dict=d)

    #eval
    print("eval")
    print(sess.run(loss, feed_dict={X : X_test_small, y : y_test_small}))

    #print first twenty predictions
    print("predict")
    print(sess.run(logits, feed_dict={X : X_test_small[:20], y : y_test_small[:20]}))
    #print firt ten answers
    print(y_test_small[:20])

Выход:

eval:
0.08857345
predict:
[[0.32180825] [0.31820688] [0.31976846] [0.32560274] [0.32335055]
 [0.32165223] [0.31789842] [0.3208077 ] [0.32917795] [0.31791273]
 [0.32507008] [0.32701296] [0.32496828] [0.32358733] [0.32018262]
 [0.31790856] [0.32912886] [0.32151538] [0.32566196] [0.3197044 ]]

[5.10843078e-02 6.11050853e-01 2.75838834e-01 9.43170079e-02
 1.19800995e-04 6.15442553e-02 7.00573233e-01 1.36474876e-01
 8.12286445e-01 6.96211080e-01 5.29943189e-02 2.71234274e-01
 4.65144845e-02 4.80682043e-04 2.13495465e-01 6.97483434e-01
 7.94839897e-01 7.15627025e-02 9.97065979e-02 2.86348669e-01]

Вы видите, что выход модели почти постоянна, но как я могу изменить модель, чтобы получить лучшие результаты? Я уже пытался использовать tanh как функцию активации. Я также попытался увеличить количество слоев и увеличить количество единиц на слой.

...