python - 每个纪元都覆盖剧情

标签 python python-3.x tensorflow matplotlib keras

我编写了一个具有神经网络近似多项式的小脚本,并绘制每个时期的结果,但问题是我希望每次迭代新的图都会覆盖以前的图,所以我可以看到它在训练过程中如何变化。

我在网上搜索了一下,发现我需要使用 ion() 或 isinteractive() 或clear(),但我都尝试了,但仍然不起作用。

编辑: 为了澄清起见,我使用的是 Jupyter 笔记本,所以我希望它能在这个平台上工作。

这是我的代码:

import numpy as np
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error
from keras.models import Sequential
from keras.layers import Dense
from numpy import asarray
from matplotlib import pyplot
from tensorflow.keras.layers import Conv1D
import tensorflow

class myCallback(tensorflow.keras.callbacks.Callback):
    def on_train_begin(self, logs={}):    
        pyplot.ion()

        
        
    def on_epoch_end(self, epoch, logs=None):
        yhat = model.predict(x)
        # inverse transforms
        x_plot = scale_x.inverse_transform(x)
        y_plot = scale_y.inverse_transform(y)
        yhat_plot = scale_y.inverse_transform(yhat)
        # report model error
        print('MSE: %.3f' % mean_squared_error(y_plot, yhat_plot))
        # plot x vs y
        plt = pyplot.scatter(x_plot,y_plot, label='Actual')
        # plot x vs yhat
        pyplot.scatter(x_plot,yhat_plot, label='Predicted')
        pyplot.title('Input (x) versus Output (y)')
        pyplot.xlabel('Input Variable (x)')
        pyplot.ylabel('Output Variable (y)')
        pyplot.legend()
        pyplot.show()
        
 


# define the dataset
x = asarray([i for i in range(-50,51)])
y = asarray([i**3 for i in x])
print(x.min(), x.max(), y.min(), y.max())
# reshape arrays into into rows and cols
x = x.reshape((len(x), 1))
y = y.reshape((len(y), 1))
# separately scale the input and output variables
scale_x = MinMaxScaler()
x = scale_x.fit_transform(x)
scale_y = MinMaxScaler()
y = scale_y.fit_transform(y)
print(x.min(), x.max(), y.min(), y.max())
# design the neural network model
model = Sequential()
model.add(Dense(10, input_dim=1, activation='relu', kernel_initializer='he_uniform'))
#Conv1D(32, 5, activation='relu')
model.add(Dense(10, activation='relu', kernel_initializer='he_uniform'))
model.add(Dense(1))
opt = tensorflow.keras.optimizers.Adam(learning_rate=0.01)
# define the loss function and optimization algorithm
model.compile(loss='mse', optimizer=opt)
# ft the model on the training dataset
model.fit(x, y, epochs=10, batch_size=10, verbose=0, callbacks=[myCallback()])
# make predictions for the input data

我们将非常感谢您的帮助!

最佳答案

每个纪元后您都会得到一个新的图,但这些变化并不真正可见,因为您的模型太弱了。这是一个具有显着差异的示例:

import numpy as np
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error
from keras.models import Sequential
from keras.layers import Dense
from numpy import asarray
from matplotlib import pyplot
import tensorflow

from IPython.display import clear_output

class myCallback(tensorflow.keras.callbacks.Callback):

    def on_epoch_end(self, epoch, logs=None):
        clear_output(wait=True)
        yhat = model.predict(x)
        # inverse transforms
        x_plot = scale_x.inverse_transform(x)
        y_plot = scale_y.inverse_transform(y)
        yhat_plot = scale_y.inverse_transform(yhat)
        # report model error
        print('MSE: %.3f' % mean_squared_error(y_plot, yhat_plot))
        # plot x vs y
        plt = pyplot.scatter(x_plot,y_plot, label='Actual')
        # plot x vs yhat
        pyplot.scatter(x_plot,yhat_plot, label='Predicted')
        pyplot.title('Input (x) versus Output (y)')
        pyplot.xlabel('Input Variable (x)')
        pyplot.ylabel('Output Variable (y)')
        pyplot.legend()
        pyplot.show()
        
# define the dataset
x = asarray([i for i in range(-50,51)])
y = asarray([i**3 for i in x])
print(x.shape)
print(x.min(), x.max(), y.min(), y.max())
# reshape arrays into into rows and cols
x = x.reshape((len(x), 1))
y = y.reshape((len(y), 1))
# separately scale the input and output variables
scale_x = MinMaxScaler()
x = scale_x.fit_transform(x)
scale_y = MinMaxScaler()
y = scale_y.fit_transform(y)
print(x.min(), x.max(), y.min(), y.max())
# design the neural network model
model = Sequential()
model.add(Dense(64, input_dim=1, activation='relu'))
model.add(Dense(32, activation='relu'))
model.add(Dense(16, activation='relu'))
model.add(Dense(1))
opt = tensorflow.keras.optimizers.Adam(learning_rate=0.01)
# define the loss function and optimization algorithm
model.compile(loss='mse', optimizer=opt)
# ft the model on the training dataset
model.fit(x, y, epochs=50, batch_size=10, verbose=0, callbacks=[myCallback()])
# make predictions for the input data

这是最后一个纪元的情节:

enter image description here

关于python - 每个纪元都覆盖剧情,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71277832/

相关文章:

python - 为什么我的脚本目录不在 Python sys.path 中?

python - 如何使用 argparse 获得不带连字符 (--) 的可能参数列表

python - 如何将字符串数据保存到 TFRecord?

python - 结果不正确的异常数学?

python - 通过浏览网页中的不同选项卡并将数据获取到 Dataframe 来进行网页抓取

定义函数闭包的 Pythonic 方式

python - 使用 TensorFlow 的训练和预测出了什么问题?

python - 检查时间序列数据的缺失值

python - TypeError : int() argument must be a string, 类似字节的对象或数字,而不是 'Calendar'

python - 如何在张量 session 中在一行中同时运行多个操作?