我是机器学习的新手,我想做一个可以预测时间序列图的模型,我一直得到错误。我是不是漏掉了什么?我发现我从获取参考代码中学习,然后修改它,并随着时间的推移学习每个组件的功能。
""" Original Repository (Reference)
https://github.com/nicknochnack/Tensorflow-in-10-Minutes/blob/main/Tensorflow%20in%2010.ipynb
"""
import pandas as pd
import numpy
from sklearn.model_selection import train_test_split
from tensorflow.keras.models import Sequential, load_model
from tensorflow.keras.layers import Dense
from sklearn.metrics import accuracy_score
import matplotlib.pyplot as plt
df = pd.read_csv('Marble & Slope Internal Data.csv')
x = pd.get_dummies(df['Distance Travelled(CM)'])
y = df['Height Off Ground(CM)']
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=.2)
x_train.head()
y_train.head()
model = Sequential()
model.add(Dense(units=32, activation='relu',input_dim=25))
model.add(Dense(units=64, activation='relu'))
model.add(Dense(units=1, activation='sigmoid'))
model.compile(loss='binary_crossentropy', optimizer='sgd', metrics='accuracy')
model.fit(x_train, y_train, epochs=20, batch_size=32)
myline = numpy.linspace(0, 100, 100)
plt.plot(myline, model.predict(myline),color='#ff8003',linewidth=3)
plt.show()
SHELL输出
Epoch 1/20
1/1 [==============================] - ETA: 0s - loss: 0.9882 - accuracy: 0.0000e+00
...
...
1/1 [==============================] - ETA: 0s - loss: nan - accuracy: 0.0000e+00
1/1 [==============================] - 0s 16ms/step - loss: nan - accuracy: 0.0000e+00
Epoch 20/20
WARNING:tensorflow:Model was constructed with shape (None, 25) for input KerasTensor(type_spec=TensorSpec(shape=(None, 25), dtype=tf.float32, name='dense_input'), name='dense_input', description="created by layer 'dense_input'"), but it was called on an input with incompatible shape (None,).
Traceback (most recent call last):
File "C:Users___OneDriveDocumentsPythonALGA.py", line 30, in <module>
plt.plot(myline, model.predict(myline),color='#ff8003',linewidth=3)
File "C:Users___AppDataLocalProgramsPythonPython310libsite-packageskerasutilstraceback_utils.py", line 67, in error_handler
raise e.with_traceback(filtered_tb) from None
File "C:Users___AppDataLocalTemp__autograph_generated_file5t873kv5.py", line 15, in tf__predict_function
retval_ = ag__.converted_call(ag__.ld(step_function), (ag__.ld(self), ag__.ld(iterator)), None, fscope)
ValueError: in user code:
File "C:Users___AppDataLocalProgramsPythonPython310libsite-packageskerasenginetraining.py", line 1845, in predict_function *
return step_function(self, iterator)
File "C:Users___AppDataLocalProgramsPythonPython310libsite-packageskerasenginetraining.py", line 1834, in step_function **
outputs = model.distribute_strategy.run(run_step, args=(data,))
File "C:Users___AppDataLocalProgramsPythonPython310libsite-packageskerasenginetraining.py", line 1823, in run_step **
outputs = model.predict_step(data)
File "C:Users___AppDataLocalProgramsPythonPython310libsite-packageskerasenginetraining.py", line 1791, in predict_step
return self(x, training=False)
File "C:Users___AppDataLocalProgramsPythonPython310libsite-packageskerasutilstraceback_utils.py", line 67, in error_handler
raise e.with_traceback(filtered_tb) from None
File "C:Users___AppDataLocalProgramsPythonPython310libsite-packageskerasengineinput_spec.py", line 228, in assert_input_compatibility
raise ValueError(f'Input {input_index} of layer "{layer_name}" '
ValueError: Exception encountered when calling layer "sequential" (type Sequential).
Input 0 of layer "dense" is incompatible with the layer: expected min_ndim=2, found ndim=1. Full shape received: (None,)
Call arguments received by layer "sequential" (type Sequential):
• inputs=tf.Tensor(shape=(None,), dtype=float32)
• training=False
• mask=None
使用Kaggle慢性肾脏疾病数据集,我能够重复这个错误。形状不匹配是原因。
为了解决这个问题,我对myline进行了如下所示的重塑。
model.predict(tf.reshape(myline,(1,25)))
完整的代码请参考此要点。谢谢你!