在著名的 iris 資料集中,我嘗試過不同的 ML 模型,例如線性回歸、SVM、決策樹和隨機森林。我想使用卷積網路。我在一個quora帖子中看到了這個,發現它很有趣。這只是出于好奇,但我該如何實作呢?
帖子鏈接:https ://www.quora.com/How-can-I-train-an-Iris-data-set-in-a-CNN-algorithm
uj5u.com熱心網友回復:
您可以在下面使用此代碼:
# Create your features and Y
X = np.array(df.drop("Species", axis=1))
y = np.array(df.Species).reshape(-1, 1)
# Encoding Target Y to One-Hot format
encoder = OneHotEncoder(sparse=False)
y = encoder.fit_transform(y)
# You can then use train test split
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, stratify=y)
# Important to reshape your data here to feed it to the CNN.
X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))
X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))
# Build the model and train
model = tf.keras.Sequential()
model.add(tf.keras.layers.Convolution1D(filters=2, kernel_size=1,input_shape=(4,1), name='Conv1'))
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(10, activation='relu', name='Dense1'))
model.add(tf.keras.layers.Dense(10, activation='relu', name='Dense2'))
model.add(tf.keras.layers.Dense(3, activation='softmax', name='output'))
optimizer = tf.keras.optimizers.Adam(lr=0.001)
model.compile(optimizer, loss='categorical_crossentropy', metrics=['accuracy'])
model.summary()
model.fit(X_train, y_train, validation_data=(X_test, y_test) ,epochs=1000,)
# Test preditions
y_pred = model.predict(X_test)
# Get argmax of both y_test and y_pred to get classes
y_pred = np.argmax(y_pred, axis=1)
y_test = np.argmax(y_test, axis=1)
# Accuracy and Classification Report
print(f"Accuracy:{accuracy_score(y_test, y_pred)*100}%")
print(classification_report(y_test, y_pred))
就是這個!
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/510088.html
