Home > Software engineering >  Problems with Python tensorflow
Problems with Python tensorflow

Time:04-15

I am a noob in programming who tried to study machine learning. I used tensorflow for Python. Here's the code, written (but not 100% copied) with official tensorflow guide (here's it https://www.tensorflow.org/guide/basics). I can't see the final graph with the results after training. I've tried two methods of training and both share the same problem. Could anyone help me?

import matplotlib as mp
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as pl

mp.rcParams["figure.figsize"] = [20, 10]
precision = 500
x = tf.linspace(-10.0, 10.0, precision)


def y(x): return 4 * np.sin(x - 1)   3

newY = y(x)   tf.random.normal(shape=[precision])

class Model(tf.keras.Model):
    def __init__(self, units):
        super().__init__()
        self.dense1 = tf.keras.layers.Dense(units = units, activation = tf.nn.relu, kernel_initializer=tf.random.normal, bias_initializer=tf.random.normal)
        self.dense2 = tf.keras.layers.Dense(1)
    
    def __call__(self, x, training = True):
        x = x[:, tf.newaxis]
        x = self.dense1(x)
        x = self.dense2(x)
        return tf.squeeze(x, axis=1)

model = Model(164)

pl.plot(x, y(x), label = "origin")
pl.plot(x, newY, ".", label = "corrupted")
pl.plot(x, model(x), label = "before training")

"""                                                     The first method
vars = model.variables
optimizer = tf.optimizers.SGD(learning_rate = 0.01)

for i in range(1000):
    with tf.GradientTape() as tape:
        prediction = model(x)
        error = (newY-prediction)**2
        mean_error = tf.reduce_mean(error)
    gradient = tape.gradient(mean_error, vars)
    optimizer.apply_gradients(zip(gradient, vars))
"""

model.compile(loss = tf.keras.losses.MSE, optimizer = tf.optimizers.SGD(learning_rate = 0.01))
model.fit(x, newY, epochs=100,batch_size=32,verbose=0)

pl.plot(x, model(x), label = "after training")
pl.legend()
pl.show()

CodePudding user response:

Assuming the code works, because you have used the code from the guide, I suspect you haven't installed a GUI backend for Matplotlib (you need this for the plots to display). Check if you receive this type of message: UserWarning: Matplotlib is currently using agg, which is a non-GUI backend, so cannot show the figure. If so, you can install one, e.g. sudo apt-get install python3-tk

CodePudding user response:

As I can see, your third graph and your fourth graph are the same. They are pl.plot(x, model(x), label = "before training") and pl.plot(x, model(x), label = "after training") You can figure out that the x-axis and y-axis data of two graphs are the same.

Hope my answer is helpful to you!

  • Related