search
HomeTechnology peripheralsAIHow to create a simple neural network using PyTorch

How to create a simple neural network using PyTorch

PyTorch is a Python-based deep learning framework for building various neural networks. This article will show how to use PyTorch to build a simple neural network and provide code examples.

First, we need to install PyTorch. It can be installed from the command line with the following command:

pip install torch

Next, we will use PyTorch to build a simple fully connected neural network for binary classification tasks. This neural network will have two hidden layers with 10 neurons each. We will use the sigmoid activation function and the cross-entropy loss function.

The following is the complete code:

import torch
import torch.nn as nn
import torch.optim as optim

# 定义神经网络模型
class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.fc1 = nn.Linear(2, 10)  # 第一个隐藏层
        self.fc2 = nn.Linear(10, 10)  # 第二个隐藏层
        self.fc3 = nn.Linear(10, 1)  # 输出层

    def forward(self, x):
        x = torch.sigmoid(self.fc1(x))
        x = torch.sigmoid(self.fc2(x))
        x = torch.sigmoid(self.fc3(x))
        return x

# 创建数据集
X = torch.tensor([[0, 0], [0, 1], [1, 0], [1, 1]], dtype=torch.float32)
y = torch.tensor([[0], [1], [1], [0]], dtype=torch.float32)

# 创建神经网络实例
net = Net()

# 定义损失函数和优化器
criterion = nn.BCELoss()
optimizer = optim.SGD(net.parameters(), lr=0.1)

# 训练神经网络
for epoch in range(10000):
    optimizer.zero_grad()
    output = net(X)
    loss = criterion(output, y)
    loss.backward()
    optimizer.step()

    # 打印训练损失
    if epoch % 1000 == 0:
    print('Epoch {}: loss = {}'.format(epoch, loss.item()))

# 使用训练好的神经网络进行预测
with torch.no_grad():
    output = net(X)
    predicted = (output > 0.5).float()
    print('Predicted: {}\n'.format(predicted))

First, we define a class named Net, which inherits from nn.Module. This class contains all layers of the neural network. In this example, we define three fully connected layers, the first two of which are hidden layers and the last one is the output layer.

In the Net class, in addition to defining a forward method to describe the forward propagation process of the neural network, we also use the sigmoid activation function to pass the output of each hidden layer to Next level.

Next, we created a dataset containing four samples, each with two features. We also defined a neural network instance named net and selected BCELoss as the loss function and SGD as the optimizer.

Then, we start training the neural network. In each iteration, we first zero out the gradient of the optimizer and then pass the dataset X into the neural network to get the output. We calculate the loss and perform backpropagation, and finally update the network parameters using an optimizer. We also printed the training loss for every 1000 iterations.

After training is completed, we use the no_grad context manager to make predictions on the dataset. We will output the four predictions and print them.

This is a simple example demonstrating how to build a basic neural network using PyTorch. PyTorch provides many tools and functions to help us build and train neural networks more easily.

The above is the detailed content of How to create a simple neural network using PyTorch. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:网易伏羲. If there is any infringement, please contact admin@php.cn delete
Excel TRANSPOSE FunctionExcel TRANSPOSE FunctionApr 22, 2025 am 09:52 AM

Powerful tools in Excel data analysis and processing: Detailed explanation of TRANSPOSE function Excel remains a powerful tool in the field of data analysis and processing. Among its many features, the TRANSPOSE function stands out for its ability to reorganize data quickly and efficiently. This feature is especially useful for data scientists and AI professionals who often need to reconstruct data to suit specific analytics needs. In this article, we will explore the TRANSPOSE function of Excel in depth, exploring its uses, usage and its practical application in data science and artificial intelligence. Learn more: Microsoft Excel Data Analytics Table of contents In Excel

How to Install Power BI DesktopHow to Install Power BI DesktopApr 22, 2025 am 09:49 AM

Get Started with Microsoft Power BI Desktop: A Comprehensive Guide Microsoft Power BI is a powerful, free business analytics tool enabling data visualization and seamless insight sharing. Whether you're a data scientist, analyst, or business user, P

Graph RAG: Enhancing RAG with Graph Structures - Analytics VidhyaGraph RAG: Enhancing RAG with Graph Structures - Analytics VidhyaApr 22, 2025 am 09:48 AM

Introduction Ever wondered how some AI systems seem to effortlessly access and integrate relevant information into their responses, mimicking a conversation with an expert? This is the power of Retrieval-Augmented Generation (RAG). RAG significantly

SQL GRANT CommandSQL GRANT CommandApr 22, 2025 am 09:45 AM

Introduction Database security hinges on managing user permissions. SQL's GRANT command is crucial for this, enabling administrators to assign specific access rights to different users or roles. This article explains the GRANT command, its syntax, c

What is Python IDLE?What is Python IDLE?Apr 22, 2025 am 09:43 AM

Introduction Python IDLE is a powerful tool that can easily develop, debug and run Python code. Its interactive shell, syntax highlighting, autocomplete and integrated debugger make it ideal for programmers of all levels of experience. This article will outline its functions, settings, and practical applications. Overview Learn about Python IDLE and its development benefits. Browse and use the main components of the IDLE interface. Write, save, and run Python scripts in IDLE. Use syntax highlighting, autocomplete and intelligent indentation. Use the IDLE integrated debugger to effectively debug Python code. Table of contents

Python & # 039: S maximum Integer ValuePython & # 039: S maximum Integer ValueApr 22, 2025 am 09:40 AM

Python: Mastering Large Integers – A Comprehensive Guide Python's exceptional capabilities extend to handling integers of any size. While this offers significant advantages, it's crucial to understand potential limitations. This guide provides a deta

9 Free Stanford AI Courses9 Free Stanford AI CoursesApr 22, 2025 am 09:35 AM

Introduction Artificial intelligence (AI) is revolutionizing industries and unlocking unprecedented possibilities across diverse fields. Stanford University, a leading institution in AI research, provides a wealth of free online courses to help you

What is Meta's Segment Anything Model(SAM)?What is Meta's Segment Anything Model(SAM)?Apr 22, 2025 am 09:25 AM

Meta's Segment Anything Model (SAM): A Revolutionary Leap in Image Segmentation Meta AI has unveiled SAM (Segment Anything Model), a groundbreaking AI model poised to revolutionize computer vision and image segmentation. This article delves into SAM

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools