???一、說明
????????本篇在此對自然語言模型做一個簡短總結,從CNN\RNN\變形金剛,和抱臉的變形金剛庫說起。
二、基本前饋神經網絡:
????????讓我們分解一個基本的前饋神經網絡,也稱為多層感知器(MLP)。此代碼示例將:
- 定義神經網絡的架構。
- 初始化權重和偏差。
- 使用 sigmoid 激活函數實現前向傳播。
- 使用均方誤差損失函數實現訓練的反向傳播。
- 演示在簡單數據集上的訓練。
import numpy as npclass NeuralNetwork:def __init__(self, input_size, hidden_size, output_size):# Initialize weights and biases with random valuesself.weights1 = np.random.randn(input_size, hidden_size)self.weights2 = np.random.randn(hidden_size, output_size)self.bias1 = np.random.randn(1, hidden_size)self.bias2 = np.random.randn(1, output_size)def sigmoid(self, x):return 1 / (1 + np.exp(-x))def sigmoid_derivative(self, x):return x * (1 - x)def forward(self, X):self.hidden = self.sigmoid(np.dot(X, self.weights1) + self.bias1)output = self.sigmoid(np.dot(self.hidden, self.weights2) + self.bias2)return outputdef train(self, X, y, epochs, learning_rate):for epoch in range(epochs):# Forward propagationoutput = self.forward(X)# Compute errorerror = y - output# Backward propagationd_output = error * self.sigmoid_derivative(output)error_hidden = d_output.dot(self.weights2.T)d_hidden = error_hidden * self.sigmoid_derivative(self.hidden)# Update weights and biasesself.weights2 += self.hidden.T.dot(d_output) * learning_rateself.bias2 += np.sum(d_output, axis=0, keepdims=True) * learning_rateself.weights1 += X.T.dot(d_hidden) * learning_rateself.bias1 += np.sum(d_hidden, axis=0, keepdims=True) * learning_rate# Print the error at every 1000 epochsif epoch % 1000 == 0:print(f"Epoch {epoch}, Error: {np.mean(np.abs(error))}")# Sample data for XOR problem
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
y = np.array([[0], [1], [1], [0]])# Create neural network instance and train
nn = NeuralNetwork(input_size=2, hidden_size=4, output_size=1)
nn.train(X, y, epochs=10000, learning_rate=0.1)# Test the neural network
print("Predictions after training:")
for data in X:print(f"{data} => {nn.forward(data)}")
在這個例子中,我們使用神經網絡來解決異或問題,這是一個單層感知器無法解決的經典問題。
這種前饋神經網絡只有一個隱藏層,這使得它能夠學習非線性關系。調整隱藏層大小、學習率和周期數等參數會影響神經網絡的性能和準確性。
三、卷積神經網絡 (CNN)
CNN 專為圖像處理而設計,包括稱為卷積層的層,這些層對輸入數據應用卷積運算,強調局部特征。
3.1 CNN的基本結構:
????????以下是使用 TensorFlow 和 Keras 庫的基本卷積神經網絡 (CNN) 的更全面實現。此示例將:
- 加載 MNIST 數據集,這是一個用于手寫數字識別的常用數據集。
- 對數據進行預處理。
- 定義基本的 CNN 架構。
- 使用優化器、損失函數和度量編譯模型。
- 在 MNIST 數據集上訓練 CNN。
- 評估經過訓練的 CNN 在測試數據上的準確性。
3.2 相關代碼實現
# Import necessary libraries
import numpy as np
import tensorflow as tf
from tensorflow.keras.datasets import mnist
from tensorflow.keras.utils import to_categorical# Load and preprocess the dataset
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
train_images = train_images.reshape((60000, 28, 28, 1)).astype('float32') / 255
test_images = test_images.reshape((10000, 28, 28, 1)).astype('float32') / 255train_labels = to_categorical(train_labels)
test_labels = to_categorical(test_labels)# Define the CNN architecture
model = tf.keras.Sequential([tf.keras.layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)),tf.keras.layers.MaxPooling2D(2, 2),tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),tf.keras.layers.MaxPooling2D(2, 2),tf.keras.layers.Conv2D(64, (3, 3), activation='relu'),tf.keras.layers.Flatten(),tf.keras.layers.Dense(64, activation='relu'),tf.keras.layers.Dense(10, activation='softmax')
])# Compile the model
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])# Train the model
model.fit(train_images, train_labels, epochs=5, batch_size=64)# Evaluate the model's accuracy on the test data
test_loss, test_acc = model.evaluate(test_images, test_labels)
print(f'Test accuracy: {test_acc}')
在此示例中,基本 CNN 有三個卷積層,后跟最大池化層。在卷積層之后,我們將輸出展平,并將其傳遞到兩個密集(全連接)層。
最后的密集層有 10 個神經元,每個神經元代表一個從 0 到 9 的數字,具有 softmax 激活函數來產生類概率。
這是MNIST數據集的一個簡單而有效的CNN。您可以通過添加更多層、使用正則化 dropout 等技術或采用高級優化技術來進一步改進網絡。
四、循環神經網絡 (RNN)
RNN 旨在識別數據序列中的模式,例如文本或時間序列。它們保留對先前輸入的記憶。
4.1 基本RNN結構:
????????讓我們使用 TensorFlow 和 Keras 創建一個基本的遞歸神經網絡 (RNN)。此示例將演示:
- 加載序列數據集(我們將使用 IMDB 情感分析數據集)。
- 預處理數據。
- 定義一個簡單的 RNN 架構。
- 使用優化器、損失函數和度量編譯模型。
- 在數據集上訓練 RNN。
- 評估經過訓練的 RNN 在測試數據上的準確性。
4.2 相關代碼實現
# Import necessary libraries
import tensorflow as tf
from tensorflow.keras.datasets import imdb
from tensorflow.keras.preprocessing.sequence import pad_sequences# Constants
VOCAB_SIZE = 10000
MAX_LEN = 500
EMBEDDING_DIM = 32# Load and preprocess the dataset
(train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=VOCAB_SIZE)# Pad sequences to the same length
train_data = pad_sequences(train_data, maxlen=MAX_LEN)
test_data = pad_sequences(test_data, maxlen=MAX_LEN)# Define the RNN architecture
model = tf.keras.Sequential([tf.keras.layers.Embedding(VOCAB_SIZE, EMBEDDING_DIM, input_length=MAX_LEN),tf.keras.layers.SimpleRNN(32, return_sequences=True),tf.keras.layers.SimpleRNN(32),tf.keras.layers.Dense(1, activation='sigmoid')
])# Compile the model
model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy'])# Train the model
model.fit(train_data, train_labels, epochs=10, batch_size=128, validation_split=0.2)# Evaluate the model's accuracy on the test data
test_loss, test_acc = model.evaluate(test_data, test_labels)
print(f'Test accuracy: {test_acc}')
在此示例中,我們首先使用嵌入層將整數序列轉換為固定大小的密集向量。然后,兩個 RNN 層處理序列。
具有 sigmoid 激活函數的最后一個密集層輸出一個概率,指示評論的情緒(0 表示負面,1 表示正面)。
值得注意的是,在實際應用中,您可能需要考慮使用更高級的遞歸層,如 LSTM 或 GRU,因為它們可以比基本 RNN 更好地捕獲遠程依賴關系。
此外,可以根據特定的應用程序和數據集對超參數(如 、 和)進行微調,以獲得最佳結果。
VOCAB_SIZE
MAX_LEN
EMBEDDING_DIM
五、變形金剛
Transformer 最初是為自然語言處理任務而設計的,具有自注意力機制,允許它們權衡輸入不同部分的重要性。
5.1 Transformer 片段(使用 Hugging Face 的 Transformers 庫):
Hugging Face 的 Transformers 庫使使用 BERT、GPT-2 等 Transformer 架構變得非常容易。讓我們創建一個基本示例:
- 加載用于文本分類的預訓練 BERT 模型。
- 標記化一些輸入句子。
- 通過 BERT 模型傳遞標記化輸入。
- 輸出預測的類概率。
5.2 相關代碼實現
????????在本演示中,讓我們使用 BERT 模型進行序列分類:
# Installation (if you haven't done it yet)
#!pip install transformers# Import required libraries
from transformers import BertTokenizer, BertForSequenceClassification
import torch# Load pretrained model and tokenizer
model_name = 'bert-base-uncased'
model = BertForSequenceClassification.from_pretrained(model_name, num_labels=2) # For binary classification
tokenizer = BertTokenizer.from_pretrained(model_name)# Tokenize input data
input_texts = ["I love using transformers!", "This library is difficult to understand."]
inputs = tokenizer(input_texts, return_tensors='pt', padding=True, truncation=True, max_length=512)# Forward pass: get model predictions
with torch.no_grad():outputs = model(**inputs)logits = outputs.logitsprobabilities = torch.nn.functional.softmax(logits, dim=-1)# Display predicted class probabilities
print(probabilities)
此腳本初始化用于二進制序列分類的 BERT 模型,對輸入句子進行標記,然后根據模型的對數進行預測。
最終輸出 , 包含輸入句子的預測類概率。
probabilities
請注意,此模型已針對二元分類(使用 )進行了初始化,因此它最適合情緒分析等任務。
num_labels=2
對于多類分類或其他任務,您可以調整并可能選擇不同的預訓練模型,或者在特定數據集上微調模型。
num_labels
六、結論
????????深度學習的世界是廣闊的,正如所展示的那樣,其算法可能會根據其應用領域變得復雜。然而,多虧了 TensorFlow 和 Hugging Face 等高級庫,使用這些算法變得越來越容易。
旅程
?