我需要神经网络和gekko的完整代码来优化神经网络的输出

问题描述 投票:0回答:1

我从未使用过python,我是新人,需要你的帮助,以便我可以学习如何使用。我有 12 个变量的热泵数据(功耗是变量之一),我想在神经网络中训练我的模型,以功耗作为输出。我想最小化 gekko 的功耗,所以我需要神经网络和 gekko 的完整代码来优化神经网络的输出。

这是一个具有一个输入和一个输出的示例问题,用于演示目的。

import numpy as np
import matplotlib.pyplot as plt

#Source function to generate data
def f(x):
    return np.cos(2*np.pi*x)

#represent noise from a data sample
N = 350
xl = np.linspace(0,1.2,N)
noise = np.random.normal(0,.3,N)
y_measured = f(xl) + noise

plt.figure(figsize=(6,3.5))
plt.plot(xl,f(xl),label='source function')
plt.plot(xl,y_measured,'.',label='measured points')
plt.legend()
plt.show()

神经网络模型可以拟合数据然后用于优化问题吗?

optimization neural-network gekko
1个回答
0
投票

如果原函数已知,Gekko 可以找到最优解,例如:

from gekko import GEKKO
m = GEKKO()
x = m.Var(0,lb=0,ub=1)
y = m.Intermediate(m.cos(x*2*np.pi)) #function is used here
m.Obj(y)
m.solve(disp=False)
print('solution:',y.value[0])
print('x:',x.value[0])

这给出了原始函数在

x=0.5
处的最小值。如果一个函数未知,但需要从数据中回归,则有许多不同的模型形式。神经网络是其中之一,但还有其他类型可能是有价值的。 工程师机器学习课程中的流程图显示了构建机器学习模型的一般流程图。

第一步是整合、可视化和评估特征(输入),以确定哪些特征与输出高度相关。有关整个过程的更多详细信息请参阅风力发电案例研究。清理和缩放数据后,使用

scikit-learn
tensorflow
进行训练,然后导入 Gekko。

使用 scikit-learn 进行训练

import pandas as pd
from gekko.ML import Gekko_NN_SKlearn, CustomMinMaxGekkoScaler
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPRegressor

#Training the Data and split it
data = pd.DataFrame(np.array([xl,y_measured]).T,columns=['x','y'])
features = ['x']
label = ['y']

train,test = train_test_split(data,test_size=0.2,shuffle=True)

s = CustomMinMaxGekkoScaler(data,features,label)
ds = s.scaledData()
mma = s.minMaxValues()

trains,tests = train_test_split(ds,test_size=0.2,shuffle=True)
hl= [25,15]
mlp = MLPRegressor(hidden_layer_sizes= hl, activation='relu',
                   solver='adam', batch_size = 32,
                   learning_rate = 'adaptive',learning_rate_init = .0005,
                   tol=1e-6 ,n_iter_no_change = 200,
                   max_iter=12000)
mlp.fit(trains[features],np.ravel(trains[label]))
r2 = mlp.score(tests[features],np.ravel(tests[label]))
print('nnSK r2:',r2)

使用 Gekko 优化神经网络模型

现在将

scikit-learn
NN 模型导入 gekko 并优化:

from gekko import GEKKO
m = GEKKO()
x = m.Var(0,lb=0,ub=1)
y = Gekko_NN_SKlearn(mlp,mma,m).predict([x])
m.Obj(y)
m.solve(disp=False)
print('solution:',y.value[0])
print('x:',x.value[0])
print('Gekko Solvetime:',m.options.SOLVETIME,'s')

这给出了一个接近于

0.5
的原始解的解。

x: 0.49272077892
Gekko Solvetime: 0.11490000002 s

这个问题可以通过 12 个输入来适应您的问题。有关将

tensorflow
gpflow
scikit-learn
模型与 gekko 一起使用的更多信息,请参阅 Gekko 文档

© www.soinside.com 2019 - 2024. All rights reserved.