我只是通过观看YouTube视频创建葡萄酒数据的神经网络,但是在model.fit中出现错误
我是机器学习的新手,所以我不知道任何解决方案,所以我还没有尝试过任何东西。
from sklearn.model_selection import train_test_split
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout
import pandas as pd
import numpy as np
from google.colab import files
np.random.seed(3)
# Number of Wine Classes
classifications = 3
#load dataset
uploaded = files.upload()
for fn in uploaded.keys():
print('User uploaded file "{name}" with length {length} bytes'.format(
name=fn, length=len(uploaded[fn])))
import io
dataset = pd.read_csv(io.StringIO(uploaded['wine.csv'].decode('utf-8')))
X = dataset[['Wine','Alcohol','Malic.acid','Ash','Acl','Mg','Phenols','Flavanoids','Nonflavanoid.phenols','Proanth','Color.int','Hue','OD','Proline']]
y = dataset[['Wine']]
# convert output values to one-hot
x_train = keras.utils.to_categorical(y_train-1, classifications)
x_test = keras.utils.to_categorical(y_test-1, classifications)
# creating model
model = Sequential()
model.add(Dense(10, input_dim=13, activation='relu'))
model.add(Dense(8, activation='relu'))
model.add(Dense(6, activation='relu'))
model.add(Dense(6, activation='relu'))
model.add(Dense(4, activation='relu'))
model.add(Dense(2, activation='relu'))
model.add(Dense(classifications, activation='softmax'))
# compile
model.compile(loss="categorical_crossentropy", optimizer="adam", metrics=['accuracy'])
# fit model
model.fit(x_train, y_train, batch_size=15, epochs=2500, validation_data=(x_test, y_test))
错误
ValueError:检查输入时出错:预期density_1_input具有形状(13,)但具有形状(3,)的数组
答案 0 :(得分:0)
在这里,您是one_hot对输入值而不是输出进行编码
# convert output values to one-hot
x_train = keras.utils.to_categorical(y_train-1, classifications)
x_test = keras.utils.to_categorical(y_test-1, classifications)
应该是:
# convert output values to one-hot
y_train = keras.utils.to_categorical(y_train-1, classifications)
y_test = keras.utils.to_categorical(y_test-1, classifications)
然后您只需要在X中保存特征而不是目标,因此新的X是:
X = dataset[['Alcohol','Malic.acid','Ash','Acl','Mg','Phenols','Flavanoids','Nonflavanoid.phenols','Proanth','Color.int','Hue','OD','Proline']]
最后不要忘记在fit方法中更改变量:
model.fit(X_train, y_train, batch_size=25, epochs=5000, validation_data=(X_test, y_test))