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 use zero padding in 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 do I check which version of Keras I am using in Python?
- How can I install the python module tensorflow.keras in R?
- How can I use YOLO with Python and Keras?
- How can I use XGBoost, Python and Keras together to build a machine learning model?
- 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 choose between Python Keras and Scikit Learn for machine learning?
See more codes...