国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Home Operation and Maintenance CentOS How to conduct deep learning in PyTorch under CentOS

How to conduct deep learning in PyTorch under CentOS

Apr 14, 2025 pm 07:03 PM
python centos ai Mirror source pip installation red

Using PyTorch for deep learning on CentOS system requires step-by-step operation:

1. PyTorch installation

You can choose Anaconda or pip to install PyTorch.

A. Anaconda installation

  1. Download Anaconda: Download the Anaconda3 installation package for CentOS system from the official Anaconda website . Follow the installation wizard to complete the installation.

  2. Create a virtual environment: Open the terminal, create a virtual environment named pytorch and activate:

     conda create -n pytorch python=3.8
    conda activated pytorch
  3. Install PyTorch: In the activated pytorch environment, use conda to install PyTorch. If you need GPU acceleration, make sure you have CUDA and cuDNN installed and select the corresponding PyTorch version. The following command installs PyTorch containing CUDA 11.8 support:

     conda install pytorch torchvision torchaudio cudatoolkit=11.8 -c pytorch
  4. Verify installation: Start the Python interactive environment, run the following code to verify that PyTorch is installed successfully, and check GPU availability:

     import torch
    print(torch.__version__)
    print(torch.cuda.is_available())

B. pip installation

  1. Install pip: If your system does not have pip installed, please install it first:

     sudo yum install python3-pip
  2. Install PyTorch: Use pip to install PyTorch and use Tsinghua University mirror source to speed up downloading:

     pip install torch torchvision torchaudio -f https://pypi.tuna.tsinghua.edu.cn/simple
  3. Verify installation: Same as Anaconda method, run the following code to verify installation:

     import torch
    print(torch.__version__)
    print(torch.cuda.is_available())

2. Deep learning practice

Here is a simple MNIST handwritten numeric recognition example that demonstrates how to use PyTorch for deep learning:

  1. Import library:

     import torch
    import torch.nn as nn
    import torch.optim as optim
    import torchvision
    import torchvision.transforms as transforms
  2. Defining the model: This is a simple convolutional neural network (CNN):

     class SimpleCNN(nn.Module):
        def __init__(self):
            super(SimpleCNN, self).__init__()
            self.conv1 = nn.Conv2d(1, 32, kernel_size=3, padding=1)
            self.pool = nn.MaxPool2d(2, 2)
            self.fc1 = nn.Linear(32 * 14 * 14, 10) #Adjust the input dimension of the fully connected layer def forward(self, x):
            x = self.pool(torch.relu(self.conv1(x)))
            x = torch.flatten(x, 1) # Flatten x = self.fc1(x)
            Return x
  3. Prepare the data: Download the MNIST dataset and preprocess it:

     transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,))])
    train_dataset = torchvision.datasets.MNIST(root='./data', train=True, download=True, transform=transform)
    test_dataset = torchvision.datasets.MNIST(root='./data', train=False, download=True, transform=transform)
    train_loader = torch.utils.data.DataLoader(train_dataset, batch_size=64, shuffle=True)
    test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=1000, shuffle=False)
  4. Initialize the model, loss function, and optimizer:

     model = SimpleCNN()
    criteria = nn.CrossEntropyLoss()
    optimizer = optim.Adam(model.parameters(), lr=0.001) # Use Adam Optimizer
  5. Training the model:

     epochs = 2
    for epoch in range(epochs):
        running_loss = 0.0
        for i, data in enumerate(train_loader, 0):
            inputs, labels = data
            optimizer.zero_grad()
            outputs = model(inputs)
            loss = criteria(outputs, labels)
            loss.backward()
            optimizer.step()
            running_loss = loss.item()
            if i % 100 == 99:
                print(f'[{epoch 1}, {i 1}] loss: {running_loss / 100:.3f}')
                running_loss = 0.0
    print('Finished Training')
  6. Model evaluation:

     correct = 0
    total = 0
    with torch.no_grad():
        for data in test_loader:
            images, labels = data
            outputs = model(images)
            _, predicted = torch.max(outputs.data, 1)
            total = labels.size(0)
            correct = (predicted == labels).sum().item()
    
    print(f'Accuracy: {100 * correct / total}%')

This example provides a basic framework. You can modify the model structure, dataset, and hyperparameters according to your needs. Remember to create the ./data directory before running. This example uses the Adam optimizer and generally converges faster than SGD. The input size of the fully connected layer is also adjusted to suit the output after the pooling layer.

The above is the detailed content of How to conduct deep learning in PyTorch under CentOS. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Who is suitable for stablecoin DAI_ Analysis of decentralized stablecoin usage scenarios Who is suitable for stablecoin DAI_ Analysis of decentralized stablecoin usage scenarios Jul 15, 2025 pm 11:27 PM

DAI is suitable for users who attach importance to the concept of decentralization, actively participate in the DeFi ecosystem, need cross-chain asset liquidity, and pursue asset transparency and autonomy. 1. Supporters of the decentralization concept trust smart contracts and community governance; 2. DeFi users can be used for lending, pledge, and liquidity mining; 3. Cross-chain users can achieve flexible transfer of multi-chain assets; 4. Governance participants can influence system decisions through voting. Its main scenarios include decentralized lending, asset hedging, liquidity mining, cross-border payments and community governance. At the same time, it is necessary to pay attention to system risks, mortgage fluctuations risks and technical threshold issues.

The flow of funds on the chain is exposed: What new tokens are being bet on by Clever Money? The flow of funds on the chain is exposed: What new tokens are being bet on by Clever Money? Jul 16, 2025 am 10:15 AM

Ordinary investors can discover potential tokens by tracking "smart money", which are high-profit addresses, and paying attention to their trends can provide leading indicators. 1. Use tools such as Nansen and Arkham Intelligence to analyze the data on the chain to view the buying and holdings of smart money; 2. Use Dune Analytics to obtain community-created dashboards to monitor the flow of funds; 3. Follow platforms such as Lookonchain to obtain real-time intelligence. Recently, Cangming Money is planning to re-polize LRT track, DePIN project, modular ecosystem and RWA protocol. For example, a certain LRT protocol has obtained a large amount of early deposits, a certain DePIN project has been accumulated continuously, a certain game public chain has been supported by the industry treasury, and a certain RWA protocol has attracted institutions to enter.

Bitcoin, Chainlink, and RWA resonance rise: crypto market enters institutional logic? Bitcoin, Chainlink, and RWA resonance rise: crypto market enters institutional logic? Jul 16, 2025 am 10:03 AM

The coordinated rise of Bitcoin, Chainlink and RWA marks the shift toward institutional narrative dominance in the crypto market. Bitcoin, as a macro hedging asset allocated by institutions, provides a stable foundation for the market; Chainlink has become a key bridge connecting the reality and the digital world through oracle and cross-chain technology; RWA provides a compliance path for traditional capital entry. The three jointly built a complete logical closed loop of institutional entry: 1) allocate BTC to stabilize the balance sheet; 2) expand on-chain asset management through RWA; 3) rely on Chainlink to build underlying infrastructure, indicating that the market has entered a new stage driven by real demand.

Which is better, DAI or USDC?_Is DAI suitable for long-term holding? Which is better, DAI or USDC?_Is DAI suitable for long-term holding? Jul 15, 2025 pm 11:18 PM

Is DAI suitable for long-term holding? The answer depends on individual needs and risk preferences. 1. DAI is a decentralized stablecoin, generated by excessive collateral for crypto assets, suitable for users who pursue censorship resistance and transparency; 2. Its stability is slightly inferior to USDC, and may experience slight deansal due to collateral fluctuations; 3. Applicable to lending, pledge and governance scenarios in the DeFi ecosystem; 4. Pay attention to the upgrade and governance risks of MakerDAO system. If you pursue high stability and compliance guarantees, it is recommended to choose USDC; if you attach importance to the concept of decentralization and actively participate in DeFi applications, DAI has long-term value. The combination of the two can also improve the security and flexibility of asset allocation.

How much is a stablecoin USD How much is a stablecoin USD Jul 15, 2025 pm 09:57 PM

The value of stablecoins is usually pegged to the US dollar 1:1, but it will fluctuate slightly due to factors such as market supply and demand, investor confidence and reserve assets. For example, USDT fell to $0.87 in 2018, and USDC fell to around $0.87 in 2023 due to the Silicon Valley banking crisis. The anchoring mechanism of stablecoins mainly includes: 1. fiat currency reserve type (such as USDT, USDC), which relies on the issuer's reserves; 2. cryptocurrency mortgage type (such as DAI), which maintains stability by over-collateralizing other cryptocurrencies; 3. Algorithmic stablecoins (such as UST), which relies on algorithms to adjust supply, but have higher risks. Common trading platforms recommendations include: 1. Binance, providing rich trading products and strong liquidity; 2. OKX,

The latest market forecast for altcoins_Which currencies have potential for explosion? The latest market forecast for altcoins_Which currencies have potential for explosion? Jul 15, 2025 pm 11:03 PM

Which altcoins have explosive potential in 2025? The answers are as follows: 1. In the Layer2 expansion track, Arbitrum (ARB) has been expanding rapidly, with obvious daily active users, and Optimism (OP) as an Ethereum optimization protocol continues to be adopted by large-scale protocols, which are all worth paying attention; 2. Among the DeFi protocol altcoins, Aave (AAVE) has enhanced lending logic, attracted stable capital inflows due to the new version, and Curve (CRV) maintains an advantageous position in the stablecoin exchange track and has strong competitiveness; 3. In the combination of artificial intelligence projects, Fetch.ai (FET) increases attention by integrating AI and blockchain, and Ocean Pro

Crypto market value exceeds US$3 trillion: Which sectors are funds betting on? Crypto market value exceeds US$3 trillion: Which sectors are funds betting on? Jul 16, 2025 am 09:45 AM

Crypto market value exceeded US$3 trillion, and funds mainly bet on seven major sectors. 1. Artificial Intelligence (AI) Blockchain: Popular currencies include FET, RNDR, AGIX, Binance and OKX launch related trading pairs and activities, funds bet on AI and decentralized computing power and data integration; 2. Layer2 and modular blockchain: ARB, OP, ZK series, TIA are attracting attention, HTX launches modular assets and provides commission rebates, funds are optimistic about their support for DeFi and GameFi; 3. RWA (real world assets): ONDO, POLYX, XDC and other related assets, OKX adds an RWA zone, and funds are expected to migrate on traditional financial chains; 4. Public chain and platform coins: SOL, BNB, HT, OKB are strong

Pre-sales of Filecoin, Render, and AI storage are heating up: Is the explosion point of Web3 infrastructure coming? Pre-sales of Filecoin, Render, and AI storage are heating up: Is the explosion point of Web3 infrastructure coming? Jul 16, 2025 am 09:51 AM

Yes, Web3 infrastructure is exploding expectations as demand for AI heats up. Filecoin integrates computing power through the "Compute over Data" plan to support AI data processing and training; Render Network provides distributed GPU computing power to serve AIGC graph rendering; Arweave supports AI model weights and data traceability with permanent storage characteristics; the three are combining technology upgrades and ecological capital promotion, and are moving from the edge to the underlying core of AI.

See all articles