# ニューラルネットによる普遍性定理( x vs 0.5x^3-5x^2-20x) from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import mean_squared_error,r2_score from keras.models import Sequential from keras.layers import Dense from numpy import asarray from matplotlib import pyplot # データセットを定義する x = asarray([i for i in range(-10,11)]) y = asarray([0.5*i**3.0-5*i**2-20*i for i in x]) print(x.min(), x.max(), y.min(), y.max()) # 配列の形状を行と列に変換 x = x.reshape((len(x), 1)) y = y.reshape((len(y), 1)) # 入力と出力を別々に正規化 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()) # ニューラルネットモデルの設計 model = Sequential() #活性化関数はReLu 層の追加add() model.add(Dense(10, input_dim=1, activation='tanh', name = 'layer_1', kernel_initializer='he_uniform')) model.add(Dense(10, activation='tanh', name = 'layer_2', kernel_initializer='he_uniform')) model.add(Dense(1, name = 'layer_3')) print (model.summary()) # 損失関数(目的関数)mseと最適化アルゴリズムadamの定義 構築されたネットワークのコンパイルcompile() model.compile(loss='mse', optimizer='adam') # 学習データを使ってモデルの調整 学習・検証fit() model.fit(x, y, epochs=20000, batch_size=10, verbose=0) # 入力についての予測 yhat = model.predict(x) print("Weights and biases of the layers after training the model: \n") for layer in model.layers: print(layer.name) print("Weights") print("Shape: ",layer.get_weights()[0].shape,'\n',layer.get_weights()[0]) print("Bias") print("Shape: ",layer.get_weights()[1].shape,'\n',layer.get_weights()[1],'\n') # 逆変換 x_plot = scale_x.inverse_transform(x) y_plot = scale_y.inverse_transform(y) yhat_plot = scale_y.inverse_transform(yhat) # モデルの予測誤差 平均二乗誤差 print('MSE: %.3f' % mean_squared_error(y_plot, yhat_plot)) print("R2値=", r2_score(y_plot, yhat_plot)) # プロット x vs y pyplot.scatter(x_plot,y_plot, s=50, label='Actual') # プロット x vs yhat pyplot.plot(x_plot,yhat_plot, label='Predicted', color="black") pyplot.title('Input (x) versus Output (y)') pyplot.xlabel('Input Variable (x)') pyplot.ylabel('Output Variable (y)') pyplot.legend() pyplot.show()