python-kerasHow do I use Python and Keras to create a classification example?
The following example uses Python and Keras to create a classification example:
# import necessary libraries
import numpy as np
from keras.models import Sequential
from keras.layers import Dense
# define the data
x_data = np.array([[1,2], [2,3], [3,1], [4,3], [5,3], [6,2]])
y_data = np.array([0,0,0,1,1,1])
# define the model
model = Sequential()
model.add(Dense(1, activation='sigmoid', input_dim=2))
model.compile(optimizer='sgd', loss='binary_crossentropy', metrics=['accuracy'])
# train the model
model.fit(x_data, y_data, epochs=200)
# evaluate the model
results = model.evaluate(x_data, y_data)
# print the results
print("Accuracy:", results[1])
Output example
Accuracy: 1.0
The code above creates a classification example using Python and Keras. It first imports the necessary libraries, such as NumPy and the Keras Sequential and Dense layers. Then it defines the data, which consists of a set of input values (x_data) and the corresponding output labels (y_data). Next, the model is defined as a Sequential model with a single Dense layer that uses a sigmoid activation function. The model is then compiled using a stochastic gradient descent (SGD) optimizer and a binary cross entropy loss function. Finally, the model is trained using the x_data and y_data values for 200 epochs and then evaluated using the same data. The output of the evaluation is the accuracy of the model, which in this case is 1.0.
Helpful links
More of Python Keras
- How do I check which version of Keras I am using in Python?
- How do I use Python Keras to zip a file?
- How do I save weights in a Python Keras model?
- How do I install Keras on Windows using Python?
- How can I use Python with Keras to build a deep learning model?
- How do I install the Python Keras .whl file?
- How can I improve the validation accuracy of my Keras model using Python?
- How do I use validation_data when creating a Keras model in Python?
- How do I use zero padding in Python Keras?
- How can I use XGBoost, Python and Keras together to build a machine learning model?
See more codes...