深度学习xiangmu
时间: 2024-12-28 20:28:39 浏览: 4
### 关于深度学习项目的资源汇总
#### 使用 PyTorch 进行分类任务的实战教程
为了帮助理解如何应用深度学习解决实际问题,下面提供了一个基于 PyTorch 的简单实例来处理表格数据分类的任务。此案例不仅涵盖了基础理论知识,还包含了完整的实现过程。
```python
import torch
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_iris
from torch.utils.data import DataLoader, TensorDataset
from torchvision import transforms
from torch.nn import Linear, ReLU, CrossEntropyLoss, Sequential
from torch.optim import Adam
def prepare_data():
iris = load_iris()
X_train, X_test, y_train, y_test = train_test_split(
iris['data'], iris['target'], test_size=0.2, random_state=42)
transform = transforms.ToTensor()
train_dataset = TensorDataset(transform(X_train), torch.tensor(y_train))
test_dataset = TensorDataset(transform(X_test), torch.tensor(y_test))
return DataLoader(train_dataset, batch_size=16), DataLoader(test_dataset, batch_size=len(test_dataset))
class SimpleNN(torch.nn.Module):
def __init__(self):
super(SimpleNN, self).__init__()
layers = []
input_dim = 4
output_dim = 3
hidden_units = [8, 16]
for h in hidden_units:
layers.append(Linear(input_dim, h))
layers.append(ReLU())
input_dim = h
layers.append(Linear(hidden_units[-1], output_dim))
model_layers = Sequential(*layers)
setattr(self, "model", model_layers)
train_loader, test_loader = prepare_data()
net = SimpleNN().float()
criterion = CrossEntropyLoss()
optimizer = Adam(net.parameters(), lr=0.01)
for epoch in range(5):
running_loss = 0.0
for i, data in enumerate(train_loader, 0):
inputs, labels = data
optimizer.zero_grad()
outputs = net(inputs.view(-1, 4).float())
loss = criterion(outputs, labels.long())
loss.backward()
optimizer.step()
running_loss += loss.item()
print('Finished Training')
```
这段代码展示了如何利用 `PyTorch` 构建并训练一个多层感知器网络来进行鸢尾花种类预测[^1]。
#### MNIST 手写数字识别入门指南
另一个经典的深度学习应用场景是对手写字体图片进行分类。这里选取了著名的 MNIST 数据集作为例子,该数据集中包含了大量的灰度图像以及对应的标签信息。通过解析这些二进制文件并将它们转换成易于操作的形式,可以为进一步的研究打下坚实的基础[^2]。
```python
import numpy as np
import matplotlib.pyplot as plt
from tensorflow.keras.datasets import mnist
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten
from tensorflow.keras.utils import to_categorical
(x_train, y_train), (x_test, y_test) = mnist.load_data()
plt.figure(figsize=(10, 10))
for i in range(25):
plt.subplot(5, 5, i + 1)
plt.imshow(x_train[i])
plt.axis('off')
num_classes = 10
y_train = to_categorical(y_train, num_classes)
y_test = to_categorical(y_test, num_classes)
input_shape = (28 * 28,)
x_train = x_train.reshape((len(x_train), 28*28)).astype('float32') / 255.
x_test = x_test.reshape((len(x_test), 28*28)).astype('float32') / 255.
model = Sequential([
Flatten(),
Dense(units=128, activation='relu', input_shape=input_shape),
Dense(num_classes, activation="softmax")
])
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
history = model.fit(x=x_train,
y=y_train,
epochs=5,
validation_data=(x_test, y_test))
```
上述脚本实现了从加载到展示再到构建模型直至最终评估整个流程的操作。
阅读全文