Neural network examples in Python
Python has always been widely used and loved for its simple, flexible syntax and powerful ecosystem and libraries, including in fields such as scientific computing and machine learning. Neural networks play a vital role in the field of machine learning and can be used in many fields such as computer vision, natural language processing, and recommendation systems. This article will introduce neural networks in Python and give some examples.
What is a neural network
Neural network is a deep learning model that has the characteristics of simulating the nervous system of animals. A neural network is composed of multiple neurons. Each neuron is equivalent to a function. Its input is the output from other neurons, which is processed by an activation function to generate an output. Neural networks utilize the backpropagation algorithm to continuously adjust weights and biases, allowing the model to better fit the data and make predictions or classifications.
TensorFlow
TensorFlow is a popular deep learning framework launched by Google for building neural networks and other machine learning algorithms. Originally developed for internal Google researchers, TensorFlow quickly became one of the most popular deep learning frameworks after being open sourced.
In TensorFlow, we can use the following steps to create a neural network:
- Prepare the data set: The data set must be divided into two parts: a training set and a test set. The training set is used to train the model, while the test set is used to test the accuracy of the model.
- Create a neural network: You can use Python to write and implement a neural network. Neural network models can be built using the TensorFlow API.
- Train the model: Train the neural network model to predict the output of new data. This can be done by using the stochastic gradient descent algorithm and performing backpropagation, continuously updating the weights and biases of the model.
- Test the model: Test the model using the test set to determine its accuracy. Different metrics can be used to evaluate the performance of the model, such as precision, recall, and F1 score.
Now, we will introduce two examples of neural networks implemented using TensorFlow.
Neural Network Example 1: Handwritten Digit Recognition
Handwritten digit recognition is an important issue in the field of computer vision, and neural networks have achieved good results on this issue. In TensorFlow, you can train a neural network using the MNIST dataset, which contains 60,000 28x28 grayscale images and corresponding labels.
First, we need to install the TensorFlow and NumPy libraries. The following is a complete code for handwritten digit recognition:
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) #创建模型 x = tf.placeholder(tf.float32, [None, 784]) W = tf.Variable(tf.zeros([784, 10])) b = tf.Variable(tf.zeros([10])) y = tf.nn.softmax(tf.matmul(x, W) + b) #定义损失函数和优化器 y_actual = tf.placeholder(tf.float32, [None, 10]) loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_actual, logits=y)) train_step = tf.train.GradientDescentOptimizer(0.01).minimize(loss) #初始化变量 init = tf.global_variables_initializer() #训练模型 sess = tf.Session() sess.run(init) for i in range(1000): batch_xs, batch_ys = mnist.train.next_batch(100) sess.run(train_step, feed_dict={x: batch_xs, y_actual: batch_ys}) #评估模型 correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_actual,1)) accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) print(sess.run(accuracy, feed_dict={x: mnist.test.images, y_actual: mnist.test.labels}))
In this example, we first prepared the dataset MNIST, and then created a simple neural network model containing 784 inputs and 10 outputs. Next, we defined the loss function and optimizer and fed the training data into the model for training. Finally, we performed test evaluation on the test data and obtained an accuracy of 92.3%.
Neural Network Example 2: Spam Filter
Almost everyone uses the mail system now, but everyone faces the spam problem. A spam filter is a program that checks whether an email is spam. Let’s see how to use neural networks to build a spam filter.
First, we need to prepare a spam data set, including emails that have been marked as spam and non-spam. Please note that when building a spam filter, there will be two categories of messages: non-spam and spam.
The following is the complete code of the spam filter:
import numpy as np import pandas as pd import tensorflow as tf from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score #读取数据集 data = pd.read_csv('spam.csv') data = data.drop(['Unnamed: 2', 'Unnamed: 3', 'Unnamed: 4'], axis=1) #转换标签 data['v1'] = data['v1'].map({'ham': 0, 'spam': 1}) #划分数据集 X_train, X_test, y_train, y_test = train_test_split(data['v2'], data['v1'], test_size=0.33, random_state=42) #创建神经网络模型 max_words = 1000 tokenize = tf.keras.preprocessing.text.Tokenizer(num_words=max_words, char_level=False) tokenize.fit_on_texts(X_train) x_train = tokenize.texts_to_matrix(X_train) x_test = tokenize.texts_to_matrix(X_test) model = tf.keras.models.Sequential() model.add(tf.keras.layers.Dense(512, input_shape=(max_words,), activation='relu')) model.add(tf.keras.layers.Dropout(0.5)) model.add(tf.keras.layers.Dense(256, activation='sigmoid')) model.add(tf.keras.layers.Dropout(0.5)) model.add(tf.keras.layers.Dense(1, activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) #训练模型 model.fit(x_train, y_train, batch_size=32, epochs=5, validation_data=(x_test, y_test)) #评估模型 y_predict = model.predict(x_test) print("Accuracy:", accuracy_score(y_test, y_predict.round()))
In this example, we use sklearn's train_test_split() method to divide the data set, and then use the Keras library Text preprocessing tools convert datasets into matrices (one-hot encoding). Next, we use Sequential to declare the neuron and set its parameters. Finally, we used the trained model to predict the test data and evaluated it to obtain an accuracy of 98.02%.
Conclusion
Neural networks in Python are a powerful technique that can be used in a variety of applications such as image recognition, spam filters, etc. Using TensorFlow, we can easily create, train, and test neural network models and obtain satisfactory results. As people's demand for machine learning grows, neural network technology will become a more important tool and be more widely used in future application scenarios.
The above is the detailed content of Neural network examples in Python. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".
