我创建了一个简单的回归模型来训练csv数据。我已经成功地完成了训练和评估,但是当我试图通过单行来预测其输出时,我得到了一个输入形状错误。
我在google collab上试过了。
下面是代码。
# load libraries and csv
import tensorflow as tf
import pandas as pd
import matplotlib.pyplot as plt
insurance_data = pd.read_csv("https://raw.githubusercontent.com/stedy/Machine-Learning-with-R-datasets/master/insurance.csv")
insurance_data.head()
# import the Classes.
from sklearn.compose import make_column_transformer
from sklearn.preprocessing import MinMaxScaler, OneHotEncoder
from sklearn.model_selection import train_test_split
# set up Normalization and One Hot encoding for columns.
CT = make_column_transformer(
(MinMaxScaler(), ["age", "bmi", "children"]), #normalize all these columns only.
(OneHotEncoder(handle_unknown="ignore"), ["sex", "smoker", "region"])
)
# make X and Y.
X1 = insurance_data.drop("charges", axis=1)
Y1 = insurance_data["charges"]
# make Train and Test data.
X1_train, X1_test, Y1_train, Y1_test = train_test_split(X1, Y1, test_size=0.2, random_state=42)
# Fit column transformer to our Training data only.
CT.fit(X1_train)
# transform training and test data with Normalization
X1_train_normalized = CT.transform(X1_train)
X1_test_normalized = CT.transform(X1_test)
X1_train.shape, X1_train_normalized.shape
# make the model,
tf.random.set_seed(43)
insurance_v3 = tf.keras.Sequential([
tf.keras.layers.Input(shape=(11)),
tf.keras.layers.Dense(100, activation=None, name="hidden1"),
tf.keras.layers.Dense(10, activation=None, name="hidden2"),
tf.keras.layers.Dense(1, activation=None, name="out1")
], name="insurance_model_v3")
insurance_v3.compile(
loss=tf.keras.losses.mae,
optimizer=tf.keras.optimizers.Adam(learning_rate=0.001),
metrics=["mae"]
)
insurance_v3.fit(X1_train_normalized, Y1_train, epochs=100, verbose=0)
insurance_v3.evaluate(X1_test_normalized, Y1_test)
# test custom output.
t = X1_train_normalized[2]
t = tf.convert_to_tensor(t, tf.float64)
t = tf.expand_dims(t, 1)
t
insurance_v3.predict(t)
我从标准化的X训练中取了一行(我不应该这样做),只是为了看看它是否接受它并返回一个Y值。
你能告诉我如何正确地做到这一点,以便我可以从网站表单中获取值,将其转换为Tensor,然后将其传递给模型,然后模型返回一个值吗?因为我应该在django应用程序中使用这个模型。
我尝试将行转换为Tensor,但每次它都会给我一个或另一个错误。首先,我得到了所需维度为2的ndim错误,但有时我会得到unrankTensor的错误。
1条答案
按热度按时间jdgnovmf1#
你必须在将input(t)输入到网络之前对其进行整形,并且为了整形Tensor,你必须启用behavior。试试这个,它运行成功: