python - 如何使用多个 3D 数组训练回归模型?
问题描述
我想用 3D 数组训练我的回归模型?我怎样才能在 Python 中做到这一点?你能指导我吗?实际上我想通过输入多个 3D 数组来预测回归值。是否可以从多个 3d 数组中仅预测单个浮点数?谢谢
train.model((x1,x2,x3..xN), y 值)。
其中 x1,x2,..xN 是 3D 数组。Y 仅输出单个浮点数。
解决方案
关键是将您的 3D 样本重塑为平面 1D 样本。以下示例代码用于tf.reshape
在馈送到常规密集网络之前重塑输入以回归到tf.identity
(无激活)输出的单个值。
%tensorflow_version 2.x
%reset -f
import tensorflow as tf
from tensorflow.keras import *
from tensorflow.keras.models import *
from tensorflow.keras.layers import *
from tensorflow.keras.callbacks import *
class regression_model(Model):
def __init__(self):
super(regression_model,self).__init__()
self.dense1 = Dense(units=300, activation=tf.keras.activations.relu)
self.dense2 = Dense(units=200, activation=tf.keras.activations.relu)
self.dense3 = Dense(units=1, activation=tf.identity)
@tf.function
def call(self,x):
h1 = self.dense1(x)
h2 = self.dense2(h1)
u = self.dense3(h2) # Output
return u
if __name__=="__main__":
inp = [[[1],[2],[3],[4]], [[3],[3],[3],[3]]] # 2 samples of whatever shape
exp = [[10], [12]] # Regress to sums for example'
inp = tf.constant(inp,dtype=tf.float32)
exp = tf.constant(exp,dtype=tf.float32)
NUM_SAMPLES = 2
NUM_VALUES_IN_1SAMPLE = 4
inp = tf.reshape(inp,(NUM_SAMPLES,NUM_VALUES_IN_1SAMPLE))
model = regression_model()
model.compile(loss=tf.losses.MeanSquaredError(),
optimizer=tf.optimizers.Adam(1e-3))
model.fit(x=inp,y=exp, batch_size=len(inp), epochs=100)
print(f"\nPrediction from {inp}, will be:")
print(model.predict(x=inp, batch_size=len(inp), steps=1))
# EOF
推荐阅读
- r - R循环/lapply,按分组累积总计
- java - 为什么调用此 readFile 方法时出现错误?
- c++ - C++ 嵌套类相互引用
- java-8 - AEM 6.2 SP1 不支持 Java 8 Lambda 表达式。Java 8 的其余功能(例如 Stream)正在运行
- c# - Xamarin 将网格绑定到 ViewModel
- css - 如何使用 flex 展开元素以在父容器中占据相同的宽度
- c# - curlopt_httpheader 相当于 c#
- python - 抓取亚马逊交易页面不返回 html 代码 - python
- reactjs - keppler.gl 上的矢量切片支持
- office-js - OfficeJs`Cannot read property 'Version' of null` Zone.js 错误