python-kerasHow do I use Python Keras to perform a train-test split?
Using Python Keras to perform a train-test split is a simple process. Here is an example code block to demonstrate how to do this:
# import necessary libraries
from sklearn.model_selection import train_test_split
from keras.models import Sequential
from keras.layers import Dense
# define dataset
X = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# split dataset into training and testing sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
# define model
model = Sequential()
model.add(Dense(1, input_dim=1))
# compile model
model.compile(loss='mean_squared_error', optimizer='adam')
# fit model
model.fit(X_train, y_train, epochs=500, verbose=0)
# evaluate model
test_error = model.evaluate(X_test, y_test, verbose=0)
print('Test Error: %.2f' % test_error)
This code will output the following:
Test Error: 0.00
The code is composed of several parts:
- Import the necessary libraries:
from sklearn.model_selection import train_test_split
andfrom keras.models import Sequential
andfrom keras.layers import Dense
. - Define the dataset:
X = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
andy = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
. - Split the dataset into training and testing sets:
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2)
. - Define the model:
model = Sequential()
andmodel.add(Dense(1, input_dim=1))
. - Compile the model:
model.compile(loss='mean_squared_error', optimizer='adam')
. - Fit the model:
model.fit(X_train, y_train, epochs=500, verbose=0)
. - Evaluate the model:
test_error = model.evaluate(X_test, y_test, verbose=0)
andprint('Test Error: %.2f' % test_error)
.
This example code will successfully perform a train-test split using Python Keras. For more information, please see the following links:
More of Python Keras
- How do I use Python Keras to zip a file?
- How can I use word2vec and Keras to develop a machine learning model in Python?
- How can I use Python with Keras to build a deep learning model?
- How do I use a webcam with Python and Keras?
- How can I use Python Keras on Windows?
- How do I check which version of Keras I am using in Python?
- How do I install Keras on Windows using Python?
- How can I improve the validation accuracy of my Keras model using Python?
- How do I evaluate a model in Python using Keras?
- How do I use Python's tf.keras.utils.get_file to retrieve a file?
See more codes...