繁体   English   中英

如何将多个数组提供给 keras 机器学习算法?

[英]How can i feed multiple arrays to a keras machine learning algorithm?

我打算制作一个保费预测器,它根据多种因素(包括性别、性别、BMI 等)来预测您的保险费(总共 6 个)我有数据,但我不知道如何养活多个数组到它。 这是代码-

import tensorflow as tf
import numpy as np
from tensorflow import keras
import pandas as pd
a=0
file=pd.read_csv(r"""C:\Users\lavni\OneDrive\Desktop\proj.csv""",sep=',')
Age=pd.DataFrame(file,columns=['age']).to_numpy()
Sex=pd.DataFrame(file,columns=['sex']).to_numpy()
BMI=pd.DataFrame(file,columns=['bmi']).to_numpy()
Children=pd.DataFrame(file,columns=['children']).to_numpy()
Smoker=pd.DataFrame(file,columns=['smoker']).to_numpy()
Region=pd.DataFrame(file,columns=['region']).to_numpy()
Charges=pd.DataFrame(file,columns=['charges']).to_numpy()

Data=[Age,Sex,BMI,Children,Smoker,Region]

model=keras.Sequential([keras.layers.Dense(units=6,input_shape=[6])])
model.compile(optimizer='sgd',loss='mean_squared_error')

model.fit(Data,Charges)

运行它后,它给了我以下错误:

    ValueError: Layer sequential expects 1 inputs, but it received 6 input tensors. Inputs received: [<tf.Tensor 'IteratorGetNext:0' shape=(None, 1) dtype=int64>, <tf.Tensor 'IteratorGetNext:1' shape=(None, 1) dtype=string>, <tf.Tensor 'IteratorGetNext:2' shape=(None, 1) dtype=float32>, <tf.Tensor 'IteratorGetNext:3' shape=(None, 1) dtype=int64>, <tf.Tensor 'IteratorGetNext:4' shape=(None, 1) dtype=string>, <tf.Tensor 'IteratorGetNext:5' shape=(None, 1) dtype=string>]

我理解这个错误,对它进行了一些研究,我发现它需要是一个元组,但尽管改变了它,它仍然给出了同样的错误。

提前致谢。

这里有几个问题,首先,不要使用pd.DataFrame从文件中加载单列数据(1d 数据)。 如果您只需要读取pd.read_csv ,请使用pd.read_csv ,可选择使用squeeze参数。

接下来,您不能使用 python 列表来对多个输入进行分组,您必须使用元组,如下所示:

Data = (a,b,c,d) # Not [a,b,c,d]

否则,keras 模型将尝试提供您的数据集a然后b等等,而不是[a[0], b[0], ...] 这似乎是你的目标。

接下来,在您的特定情况下,您似乎不需要多输入 keras 模型。 您所需要的只是第一层上的有效input_shape 这就是模型抱怨的原因。 它需要一个输入,而您正试图插入其中的 6 个。 将输入转换为单个数组,如

data = dataframe.to_numpy() #dataframe must have 6 columns!
targets = targets.to_numpy() #single column
...
model.fit(data,targets)

使用此信息更新您的代码,并在出现其他问题时询问我。
干杯!

用这种方式写:

model = keras.Sequential()
model.add(keras.layers.Dense(units=6, input_shape=(6,)))
model.add(keras.layers.Dense(units=?))

最后一层是输出层(因为我不知道你的输出是什么样的,我无法定义单位。)

还有一个给您的快速提示,您可以通过编写如下代码来减少代码大小:

import tensorflow as tf
import numpy as np
from tensorflow import keras
import pandas as pd
a=0
file = pd.read_csv(r"""C:\Users\lavni\OneDrive\Desktop\proj.csv""",sep=',')
Charges = file['charges'].to_numpy()

features = ['age', 'sex', 'bmi', 'children', 'smoker', 'region']
Data = file[features].to_numpy()
# it will convert all of your features into a numpy array

model = keras.Sequential()
model.add(keras.layers.Dense(units=6, input_shape=(6,)))
model.compile(optimizer='sgd',loss='mean_squared_error')

model.fit(Data,Charges)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM