Pythonデータサイエンスライブラリの実践事例27選(コード付き)

誰もが人工知能で一般的に使用される Python ライブラリを予備的に理解し、学習のニーズを満たすことができるライブラリを選択できるように、より一般的な人工知能ライブラリについての簡潔かつ包括的な紹介を提供します。

1、ナンピー

NumPy(Numerical Python)これは、 Python多数の次元配列と行列演算をサポートする拡張プログラム ライブラリです。さらに、配列演算用の多数の数学関数ライブラリも提供します。基本的な使用方法が記述されています。オブジェクトは、配列ではなく配列に直接格納されNumpyますC语言。オブジェクトポインタを使用するため、操作効率が大幅に向上します纯Python代例のリストの sin 値の計算纯Pythonと速度を比較できますNumpy库

import numpy as np
import math
import random
import time

start = time.time()
for i in range(10):
    list_1 = list(range(1,10000))
    for j in range(len(list_1)):
        list_1[j] = math.sin(list_1[j])
print("使用纯Python用时{}s".format(time.time()-start))

start = time.time()
for i in range(10):
    list_1 = np.array(np.arange(1,10000))
    list_1 = np.sin(list_1)
print("使用Numpy用时{}s".format(time.time()-start))

Numpy 次の実行結果から、ライブラリを使用した方が純粋な Python で書かれたコードよりも高速であることがわかります 。

 
 

純粋な Python を使用した場合は 0.017444372177124023 秒、
Numpy を使用した場合は 0.001619577407836914 秒

2、OpenCV

OpenCV は、Linux、Windows、および Mac OS オペレーティング システムで実行できるクロスプラットフォームのコンピューター ビジョン ライブラリです。これは軽量で効率的であり、一連の C 関数といくつかの C++ クラスで構成されており、 Python 画像処理やコンピューター ビジョンにおける多くの一般的なアルゴリズムを実装するインターフェイスも提供します。次のコードは、画像のスムージング、ガウスぼかしなどのいくつかの単純なフィルターの使用を試みます。

import numpy as np
import cv2 as cv
from matplotlib import pyplot as plt
img = cv.imread('h89817032p0.png')
kernel = np.ones((5,5),np.float32)/25
dst = cv.filter2D(img,-1,kernel)
blur_1 = cv.GaussianBlur(img,(5,5),0)
blur_2 = cv.bilateralFilter(img,9,75,75)
plt.figure(figsize=(10,10))
plt.subplot(221),plt.imshow(img[:,:,::-1]),plt.title('Original')
plt.xticks([]), plt.yticks([])
plt.subplot(222),plt.imshow(dst[:,:,::-1]),plt.title('Averaging')
plt.xticks([]), plt.yticks([])
plt.subplot(223),plt.imshow(blur_1[:,:,::-1]),plt.title('Gaussian')
plt.xticks([]), plt.yticks([])
plt.subplot(224),plt.imshow(blur_1[:,:,::-1]),plt.title('Bilateral')
plt.xticks([]), plt.yticks([])
plt.show()

OpenCV

3、Scikit画像

scikit-imageは、画像を配列として処理するscipy、 に基づく画像処理ライブラリです。numpyたとえば、 を使用してscikit-image画像のスケールを変更したり、、 などの機能scikit-imageを提供したりできますrescaleresizedownscale_local_mean

from skimage import data, color, io
from skimage.transform import rescale, resize, downscale_local_mean

image = color.rgb2gray(io.imread('h89817032p0.png'))

image_rescaled = rescale(image, 0.25, anti_aliasing=False)
image_resized = resize(image, (image.shape[0] // 4, image.shape[1] // 4),
                       anti_aliasing=True)
image_downscaled = downscale_local_mean(image, (4, 3))
plt.figure(figsize=(20,20))
plt.subplot(221),plt.imshow(image, cmap='gray'),plt.title('Original')
plt.xticks([]), plt.yticks([])
plt.subplot(222),plt.imshow(image_rescaled, cmap='gray'),plt.title('Rescaled')
plt.xticks([]), plt.yticks([])
plt.subplot(223),plt.imshow(image_resized, cmap='gray'),plt.title('Resized')
plt.xticks([]), plt.yticks([])
plt.subplot(224),plt.imshow(image_downscaled, cmap='gray'),plt.title('Downscaled')
plt.xticks([]), plt.yticks([])
plt.show()

Scikit イメージ

4、ピル

Python Imaging Library(PIL) 機能が非常に強力でありながら、APIが非常にシンプルで使いやすいため、Python デファクトの画像処理標準ライブラリ となっています 。PILしかし、PIL は 1 までしかサポートしておらず 、長らく放置されていた ため、 Python 2.7有志のグループが PIL . use をベースに互換バージョンを作成しました  PillowPython 3.xPILPillow

5、枕

以下を使用して Pillow 文字キャプチャ画像を生成します。

from PIL import Image, ImageDraw, ImageFont, ImageFilter

import random

# 随机字母:
def rndChar():
    return chr(random.randint(65, 90))

# 随机颜色1:
def rndColor():
    return (random.randint(64, 255), random.randint(64, 255), random.randint(64, 255))

# 随机颜色2:
def rndColor2():
    return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))

# 240 x 60:
width = 60 * 6
height = 60 * 6
image = Image.new('RGB', (width, height), (255, 255, 255))
# 创建Font对象:
font = ImageFont.truetype('/usr/share/fonts/wps-office/simhei.ttf', 60)
# 创建Draw对象:
draw = ImageDraw.Draw(image)
# 填充每个像素:
for x in range(width):
    for y in range(height):
        draw.point((x, y), fill=rndColor())
# 输出文字:
for t in range(6):
    draw.text((60 * t + 10, 150), rndChar(), font=font, fill=rndColor2())
# 模糊:
image = image.filter(ImageFilter.BLUR)
image.save('code.jpg', 'jpeg')

検証コード

6、シンプルCV

SimpleCV は、コンピュータ ビジョン アプリケーションを構築するためのオープンソース フレームワークです。これを使用すると、ビット深度、ファイル形式、色空間、バッファー管理、固有値、行列などの用語を最初に理解する必要がなく、OpenCV などの高性能コンピューター ビジョン ライブラリにアクセスできます。ただし、Python3 のサポートは非​​常に不十分です。Python3.7 では次のコードを使用します。

from SimpleCV import Image, Color, Display
# load an image from imgur
img = Image('http://i.imgur.com/lfAeZ4n.png')
# use a keypoint detector to find areas of interest
feats = img.findKeypoints()
# draw the list of keypoints
feats.draw(color=Color.RED)
# show the  resulting image. 
img.show()
# apply the stuff we found to the image.
output = img.applyLayers()
# save the results.
output.save('juniperfeats.png')

次のエラーが報告されるため、次の Python3 場合には使用しないことをお勧めします。

SyntaxError: Missing parentheses in call to 'print'. Did you mean pr

 

7、マホタス

MahotasNumpy は、その上に 構築された高速コンピュータ ビジョン アルゴリズムのライブラリであり 、現在 100 を超える画像処理およびコンピュータ ビジョン関数があり、成長しています。を使用して 画像を読み込みMahotas 、ピクセルを操作します。

import numpy as np
import mahotas
import mahotas.demos

from mahotas.thresholding import soft_threshold
from matplotlib import pyplot as plt
from os import path
f = mahotas.demos.load('lena', as_grey=True)
f = f[128:,128:]
plt.gray()
# Show the data:
print("Fraction of zeros in original image: {0}".format(np.mean(f==0)))
plt.imshow(f)
plt.show()

マホタス

8、弾性

Ilastik 機械学習アルゴリズムを使用して、細胞やその他の実験データを簡単にセグメント化、分類、追跡、カウントする優れた機械学習ベースのバイオインフォマティクス画像分析サービスをユーザーに提供できます。ほとんどの操作は対話型であり、機械学習の専門知識は必要ありません。

9、Scikit-Learn

Scikit-learnPython は、プログラミング言語用のフリーウェア機械学習ライブラリ です 。サポート ベクター マシン、ランダム フォレスト、勾配ブースティング、K 平均法、DBSCAN、その他多くの機械学習アルゴリズムを含む、さまざまな分類、回帰、クラスタリング アルゴリズムを備えています。以下を使用してアルゴリズムScikit-learnを実装しますKMeans

import time

import numpy as np
import matplotlib.pyplot as plt

from sklearn.cluster import MiniBatchKMeans, KMeans
from sklearn.metrics.pairwise import pairwise_distances_argmin
from sklearn.datasets import make_blobs

# Generate sample data
np.random.seed(0)

batch_size = 45
centers = [[1, 1], [-1, -1], [1, -1]]
n_clusters = len(centers)
X, labels_true = make_blobs(n_samples=3000, centers=centers, cluster_std=0.7)

# Compute clustering with Means

k_means = KMeans(init='k-means++', n_clusters=3, n_init=10)
t0 = time.time()
k_means.fit(X)
t_batch = time.time() - t0

# Compute clustering with MiniBatchKMeans

mbk = MiniBatchKMeans(init='k-means++', n_clusters=3, batch_size=batch_size,
                      n_init=10, max_no_improvement=10, verbose=0)
t0 = time.time()
mbk.fit(X)
t_mini_batch = time.time() - t0

# Plot result
fig = plt.figure(figsize=(8, 3))
fig.subplots_adjust(left=0.02, right=0.98, bottom=0.05, top=0.9)
colors = ['#4EACC5', '#FF9C34', '#4E9A06']

# We want to have the same colors for the same cluster from the
# MiniBatchKMeans and the KMeans algorithm. Let's pair the cluster centers per
# closest one.
k_means_cluster_centers = k_means.cluster_centers_
order = pairwise_distances_argmin(k_means.cluster_centers_,
                                  mbk.cluster_centers_)
mbk_means_cluster_centers = mbk.cluster_centers_[order]

k_means_labels = pairwise_distances_argmin(X, k_means_cluster_centers)
mbk_means_labels = pairwise_distances_argmin(X, mbk_means_cluster_centers)

# KMeans
for k, col in zip(range(n_clusters), colors):
    my_members = k_means_labels == k
    cluster_center = k_means_cluster_centers[k]
    plt.plot(X[my_members, 0], X[my_members, 1], 'w',
            markerfacecolor=col, marker='.')
    plt.plot(cluster_center[0], cluster_center[1], 'o', markerfacecolor=col,
            markeredgecolor='k', markersize=6)
plt.title('KMeans')
plt.xticks(())
plt.yticks(())

plt.show()

K平均値

10、サイピー

SciPy このライブラリは、数値積分、内挿、最適化、線形代数など、多くの使いやすく効率的な数値計算を提供します。SciPy このライブラリは、楕円関数、ベッセル関数、ガンマ関数、ベータ関数、超幾何関数、放物線円筒関数などを含む、数理物理学用の多くの特殊関数を定義します。

from scipy import special
import matplotlib.pyplot as plt
import numpy as np

def drumhead_height(n, k, distance, angle, t):
    kth_zero = special.jn_zeros(n, k)[-1]
    return np.cos(t) * np.cos(n*angle) * special.jn(n, distance*kth_zero)

theta = np.r_[0:2*np.pi:50j]
radius = np.r_[0:1:50j]
x = np.array([r * np.cos(theta) for r in radius])
y = np.array([r * np.sin(theta) for r in radius])
z = np.array([drumhead_height(1, 1, r, theta, 0.5) for r in radius])


fig = plt.figure()
ax = fig.add_axes(rect=(0, 0.05, 0.95, 0.95), projection='3d')
ax.plot_surface(x, y, z, rstride=1, cstride=1, cmap='RdBu_r', vmin=-0.5, vmax=0.5)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_xticks(np.arange(-1, 1.1, 0.5))
ax.set_yticks(np.arange(-1, 1.1, 0.5))
ax.set_zlabel('Z')
plt.show()

サイピー

11、NLTK

NLTK は、自然言語を処理する Python プログラムを構築するためのライブラリです。50 を超えるコーパスおよび語彙リソース ( など) への使いやすいインターフェイス WordNet と、分類、トークン化、ステミング、トークン化、解析、および意味論的推論のための一連のテキスト処理ライブラリを提供します。 (Natural Language Processing, NLP) ライブラリ 。NLTK と呼ばれます “a wonderful tool for teaching, and working in, computational linguistics using Python”

import nltk
from nltk.corpus import treebank

# 首次使用需要下载
nltk.download('punkt')
nltk.download('averaged_perceptron_tagger')
nltk.download('maxent_ne_chunker')
nltk.download('words')
nltk.download('treebank')

sentence = """At eight o'clock on Thursday morning Arthur didn't feel very good."""
# Tokenize
tokens = nltk.word_tokenize(sentence)
tagged = nltk.pos_tag(tokens)

# Identify named entities
entities = nltk.chunk.ne_chunk(tagged)

# Display a parse tree
t = treebank.parsed_sents('wsj_0001.mrg')[0]
t.draw()

NLTK

12、スペイシー

spaCyPython は、NLP における高度な NLP のための無料のオープンソース ライブラリです 。大量のテキストを処理するアプリケーションの構築に使用できます。また、情報抽出システムや自然言語理解システムの構築、深層学習用のテキストの前処理にも使用できます。

  import spacy

  texts = [
      "Net income was $9.4 million compared to the prior year of $2.7 million.",
      "Revenue exceeded twelve billion dollars, with a loss of $1b.",
  ]

  nlp = spacy.load("en_core_web_sm")
  for doc in nlp.pipe(texts, disable=["tok2vec", "tagger", "parser", "attribute_ruler", "lemmatizer"]):
      # Do something with the doc here
      print([(ent.text, ent.label_) for ent in doc.ents])

nlp.pipe Doc オブジェクトを生成して、それらを反復処理して名前付きエンティティの予測にアクセスできるようにします。

[('$9.4 million', 'MONEY'), ('the prior year', 'DATE'), ('$2.7 million', 'MONEY')]
[('twelve billion dollars', 'MONEY'), ('1b', 'MONEY')]

13、ピンクブック

librosa は、音楽情報検索システムを作成するために必要な機能と機能を提供する、音楽およびオーディオ分析用の Python ライブラリです。

# Beat tracking example
import librosa

# 1. Get the file path to an included audio example
filename = librosa.example('nutcracker')

# 2. Load the audio as a waveform `y`
#    Store the sampling rate as `sr`
y, sr = librosa.load(filename)

# 3. Run the default beat tracker
tempo, beat_frames = librosa.beat.beat_track(y=y, sr=sr)
print('Estimated tempo: {:.2f} beats per minute'.format(tempo))

# 4. Convert the frame indices of beat events into timestamps
beat_times = librosa.frames_to_time(beat_frames, sr=sr)

14、パンダ

PandasPandas これは、CSV、JSON、SQL、Microsoft Excel などのさまざまなファイル形式からデータをインポートでき、次のようなさまざまなデータに対して操作を実行できる、高速、強力、柔軟で使いやすい オープンソース データ分析および操作ツールです。 マージと再形成、選択、データ クリーニングとデータ処理の機能。Pandas 学術、金融、統計などのさまざまなデータ分析分野で広く使用されています。

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

ts = pd.Series(np.random.randn(1000), index=pd.date_range("1/1/2000", periods=1000))
ts = ts.cumsum()

df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=list("ABCD"))
df = df.cumsum()
df.plot()
plt.show()

パンダ

15、Matplotlib

Matplotlibmatlab これは、出版品質のレベルで美しいグラフィックスを生成できる 完全なセットと同様のコマンド API を提供する Python 用の描画ライブラリであり 、Matplotlib 描画を非常にシンプルにし、使いやすさとパフォーマンスの優れたバランスを実現します。次を使用して Matplotlib 複数のプロットをプロットします。

# plot_multi_curve.py
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0.1, 2 * np.pi, 100)
y_1 = x
y_2 = np.square(x)
y_3 = np.log(x)
y_4 = np.sin(x)
plt.plot(x,y_1)
plt.plot(x,y_2)
plt.plot(x,y_3)
plt.plot(x,y_4)
plt.show()

マットプロットリブ

16.シーボーン

SeabornMatplotlib これは、 に基づくより高度な API パッケージを備えた Seaborn Python データ視覚化ライブラリ です Matplotlib 。

import seaborn as sns
import matplotlib.pyplot as plt
sns.set_theme(style="ticks")

df = sns.load_dataset("penguins")
sns.pairplot(df, hue="species")
plt.show()

シーボーン

17、オレンジ

Orange これは、一連のデータ探索、視覚化、前処理、およびモデリングのコンポーネントを提供するオープンソースのデータ マイニングおよび機械学習ソフトウェアです。Orange 美しく直感的なインタラクティブなユーザー インターフェイスを備えているため、初心者が探索的なデータ分析や視覚的な表示を行うのに非常に適していますが、同時に上級ユーザーはデータ操作やコンポーネント開発のためのプログラミング モジュールとしても使用できます Python 。使用 pip 後に取り付けることができます Orange、賞賛〜

$ pip install orange3

インストールが完了したら、コマンド ラインに次のコマンドを入力して  グラフィカル インターフェイスorange-canvas を起動します 。Orange

$ orange-canvas

起動が完了すると、 Orange グラフィカルインターフェースが表示され、さまざまな操作が可能になります。

オレンジ

18、パイブレイン

PyBrain はい、 Python モジュール式機械学習ライブラリです。その目標は、機械学習タスクやさまざまな事前定義された環境のアルゴリズムをテストおよび比較するための、柔軟で使いやすく強力なアルゴリズムを提供することです。PyBrain 「はい」 の頭字語Python-Based Reinforcement Learning, Artificial Intelligence and Neural Network Library 。簡単な例を使用して の使用法を示し PyBrain 、多層パーセプトロン (MLP) を構築します。まず、新しいフィードフォワード ネットワーク オブジェクトを作成します。

from pybrain.structure import FeedForwardNetwork
n = FeedForwardNetwork()

次に、入力層、非表示層、出力層を構築します。

from pybrain.structure import LinearLayer, SigmoidLayer

inLayer = LinearLayer(2)
hiddenLayer = SigmoidLayer(3)
outLayer = LinearLayer(1)

構築されたレイヤーを使用するには、それらをネットワークに追加する必要があります。

n.addInputModule(inLayer)
n.addModule(hiddenLayer)
n.addOutputModule(outLayer)

複数の入出力モジュールを追加できます。誤差を前方に計算して後方に伝播するには、ネットワークはどの層が入力でどの層が出力であるかを認識する必要があります。これには、接続方法を明確に決定する必要があります。このために、最も一般的なタイプの接続である完全接続層を使用します。これは FullConnection クラスによって実装されます。

from pybrain.structure import FullConnection
in_to_hidden = FullConnection(inLayer, hiddenLayer)
hidden_to_out = FullConnection(hiddenLayer, outLayer)

レイヤーの場合と同様に、レイヤーをネットワークに明示的に追加する必要があります。

n.addConnection(in_to_hidden)
n.addConnection(hidden_to_out)

これですべての要素が配置されました。最後に、.sortModules() メソッドを呼び出して MLP を使用できるようにする必要があります。

n.sortModules()

この呼び出しは、ネットワークを使用する前に必要な内部初期化を実行します。

19、牛乳

MILK(MACHINE LEARNING TOOLKIT) Python 言語の機械学習ツールキットです。主にSVMS、K-NN、ランダムフォレスト、教師付き分類法を使用したデシジョンツリーなどの多くの分類器が含まれており、教師なし学習、親和性伝播、MILKがサポートするKなどのさまざまな手法を形成できる特徴選択も実行できます。 as - はクラスタリングを意味します。以下を使用して MILK 分類器をトレーニングします。

import numpy as np
import milk
features = np.random.rand(100,10)
labels = np.zeros(100)
features[50:] += .5
labels[50:] = 1
learner = milk.defaultclassifier()
model = learner.train(features, labels)

# Now you can use the model on new examples:
example = np.random.rand(10)
print(model.apply(example))
example2 = np.random.rand(10)
example2 += .5
print(model.apply(example2))

20、TensorFlow

TensorFlow は、エンドツーエンドのオープンソース機械学習プラットフォームです。包括的で柔軟なエコシステムを備えており、一般に TensorFlow1.x と TensorFlow2.x に分類できます。TensorFlow1.x と TensorFlow2.x の主な違いは、TF1.x は静的グラフを使用するのに対し、TF2.x は Eager Mode 動的グラフを使用することです。 。ここでは、主に TensorFlow2.x での畳み込みニューラル ネットワーク (Convolutional Neural Network、CNN) の構築を示す例として TensorFlow2.x を使用します。

import tensorflow as tf

from tensorflow.keras import datasets, layers, models

# 数据加载
(train_images, train_labels), (test_images, test_labels) = datasets.cifar10.load_data()

# 数据预处理
train_images, test_images = train_images / 255.0, test_images / 255.0

# 模型构建
model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.Flatten())
model.add(layers.Dense(64, activation='relu'))
model.add(layers.Dense(10))

# 模型编译与训练
model.compile(optimizer='adam',
              loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
              metrics=['accuracy'])
history = model.fit(train_images, train_labels, epochs=10, 
                    validation_data=(test_images, test_labels))

21、パイトーチ

PyTorch Torch の前身は Torch で、その最下層は Torch フレームワークと同じですが、多くのコンテンツが Python で書き直されており、より柔軟で動的グラフをサポートしているだけでなく、Python インターフェイスも提供されています。

# 导入库
import torch
from torch import nn
from torch.utils.data import DataLoader
from torchvision import datasets
from torchvision.transforms import ToTensor, Lambda, Compose
import matplotlib.pyplot as plt

# 模型构建
device = "cuda" if torch.cuda.is_available() else "cpu"
print("Using {} device".format(device))

# Define model
class NeuralNetwork(nn.Module):
    def __init__(self):
        super(NeuralNetwork, self).__init__()
        self.flatten = nn.Flatten()
        self.linear_relu_stack = nn.Sequential(
            nn.Linear(28*28, 512),
            nn.ReLU(),
            nn.Linear(512, 512),
            nn.ReLU(),
            nn.Linear(512, 10),
            nn.ReLU()
        )

    def forward(self, x):
        x = self.flatten(x)
        logits = self.linear_relu_stack(x)
        return logits

model = NeuralNetwork().to(device)

# 损失函数和优化器
loss_fn = nn.CrossEntropyLoss()
optimizer = torch.optim.SGD(model.parameters(), lr=1e-3)

# 模型训练
def train(dataloader, model, loss_fn, optimizer):
    size = len(dataloader.dataset)
    for batch, (X, y) in enumerate(dataloader):
        X, y = X.to(device), y.to(device)

        # Compute prediction error
        pred = model(X)
        loss = loss_fn(pred, y)

        # Backpropagation
        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

        if batch % 100 == 0:
            loss, current = loss.item(), batch * len(X)
            print(f"loss: {loss:>7f}  [{current:>5d}/{size:>5d}]")

 

22、テアノ

Theano は、NumPy 上に構築された、多次元配列を含む数式の定義、最適化、効率的な評価を可能にする Python ライブラリです。Theano ヤコビアンの計算は次のように実装されています。 

import theano
import theano.tensor as T
x = T.dvector('x')
y = x ** 2
J, updates = theano.scan(lambda i, y,x : T.grad(y[i], x), sequences=T.arange(y.shape[0]), non_sequences=[y,x])
f = theano.function([x], J, updates=updates)
f([4, 4])

23、ハード

Keras Python で書かれた高レベルのニューラル ネットワーク API で、バックエンドとして TensorFlow、CNTK、または Theano で実行できます。Keras の開発は高速実験のサポートに重点を置いており、最小限の遅延でアイデアを実験結果に変換できます。

from keras.models import Sequential
from keras.layers import Dense

# 模型构建
model = Sequential()
model.add(Dense(units=64, activation='relu', input_dim=100))
model.add(Dense(units=10, activation='softmax'))

# 模型编译与训练
model.compile(loss='categorical_crossentropy',
              optimizer='sgd',
              metrics=['accuracy'])
model.fit(x_train, y_train, epochs=5, batch_size=32)         

24、カフェ

Caffe2 の公式 Web サイトには、次のように書かれています。NowCaffe2 は の PyTorch 一部です。これらの API は引き続き機能しますが、PyTorch API の使用をお勧めします。

25、MXネット

MXNet は、効率性と柔軟性を考慮して設計された深層学習フレームワークです。これにより、記号的プログラミングと命令的プログラミングを混合して、効率と生産性を最大化することができます。以下を使用して 手書き数字認識モデルを構築しますMXNet 。

import mxnet as mx
from mxnet import gluon
from mxnet.gluon import nn
from mxnet import autograd as ag
import mxnet.ndarray as F

# 数据加载
mnist = mx.test_utils.get_mnist()
batch_size = 100
train_data = mx.io.NDArrayIter(mnist['train_data'], mnist['train_label'], batch_size, shuffle=True)
val_data = mx.io.NDArrayIter(mnist['test_data'], mnist['test_label'], batch_size)

# CNN模型
class Net(gluon.Block):
    def __init__(self, **kwargs):
        super(Net, self).__init__(**kwargs)
        self.conv1 = nn.Conv2D(20, kernel_size=(5,5))
        self.pool1 = nn.MaxPool2D(pool_size=(2,2), strides = (2,2))
        self.conv2 = nn.Conv2D(50, kernel_size=(5,5))
        self.pool2 = nn.MaxPool2D(pool_size=(2,2), strides = (2,2))
        self.fc1 = nn.Dense(500)
        self.fc2 = nn.Dense(10)

    def forward(self, x):
        x = self.pool1(F.tanh(self.conv1(x)))
        x = self.pool2(F.tanh(self.conv2(x)))
        # 0 means copy over size from corresponding dimension.
        # -1 means infer size from the rest of dimensions.
        x = x.reshape((0, -1))
        x = F.tanh(self.fc1(x))
        x = F.tanh(self.fc2(x))
        return x
net = Net()
# 初始化与优化器定义
# set the context on GPU is available otherwise CPU
ctx = [mx.gpu() if mx.test_utils.list_gpus() else mx.cpu()]
net.initialize(mx.init.Xavier(magnitude=2.24), ctx=ctx)
trainer = gluon.Trainer(net.collect_params(), 'sgd', {'learning_rate': 0.03})

# 模型训练
# Use Accuracy as the evaluation metric.
metric = mx.metric.Accuracy()
softmax_cross_entropy_loss = gluon.loss.SoftmaxCrossEntropyLoss()

for i in range(epoch):
    # Reset the train data iterator.
    train_data.reset()
    for batch in train_data:
        data = gluon.utils.split_and_load(batch.data[0], ctx_list=ctx, batch_axis=0)
        label = gluon.utils.split_and_load(batch.label[0], ctx_list=ctx, batch_axis=0)
        outputs = []
        # Inside training scope
        with ag.record():
            for x, y in zip(data, label):
                z = net(x)
                # Computes softmax cross entropy loss.
                loss = softmax_cross_entropy_loss(z, y)
                # Backpropogate the error for one iteration.
                loss.backward()
                outputs.append(z)
        metric.update(label, outputs)
        trainer.step(batch.data[0].shape[0])
    # Gets the evaluation result.
    name, acc = metric.get()
    # Reset evaluation result to initial state.
    metric.reset()
    print('training acc at epoch %d: %s=%f'%(i, name, acc))

26、パドルパドル

Flying Paddle (PaddlePaddle) は、Baidu の長年にわたる深層学習テクノロジーの研究とビジネス アプリケーションに基づいており、深層学習のコア トレーニングと推論フレームワーク、基本モデル ライブラリ、エンドツーエンドの開発キット、豊富なツール コンポーネントが統合されています。これは、中国初の自社開発、完全に機能する、オープンソースの産業レベルの深層学習プラットフォームです。PaddlePaddle を達成するために 使用します LeNtet5:

# 导入需要的包
import paddle
import numpy as np
from paddle.nn import Conv2D, MaxPool2D, Linear

## 组网
import paddle.nn.functional as F

# 定义 LeNet 网络结构
class LeNet(paddle.nn.Layer):
    def __init__(self, num_classes=1):
        super(LeNet, self).__init__()
        # 创建卷积和池化层
        # 创建第1个卷积层
        self.conv1 = Conv2D(in_channels=1, out_channels=6, kernel_size=5)
        self.max_pool1 = MaxPool2D(kernel_size=2, stride=2)
        # 尺寸的逻辑:池化层未改变通道数;当前通道数为6
        # 创建第2个卷积层
        self.conv2 = Conv2D(in_channels=6, out_channels=16, kernel_size=5)
        self.max_pool2 = MaxPool2D(kernel_size=2, stride=2)
        # 创建第3个卷积层
        self.conv3 = Conv2D(in_channels=16, out_channels=120, kernel_size=4)
        # 尺寸的逻辑:输入层将数据拉平[B,C,H,W] -> [B,C*H*W]
        # 输入size是[28,28],经过三次卷积和两次池化之后,C*H*W等于120
        self.fc1 = Linear(in_features=120, out_features=64)
        # 创建全连接层,第一个全连接层的输出神经元个数为64, 第二个全连接层输出神经元个数为分类标签的类别数
        self.fc2 = Linear(in_features=64, out_features=num_classes)
    # 网络的前向计算过程
    def forward(self, x):
        x = self.conv1(x)
        # 每个卷积层使用Sigmoid激活函数,后面跟着一个2x2的池化
        x = F.sigmoid(x)
        x = self.max_pool1(x)
        x = F.sigmoid(x)
        x = self.conv2(x)
        x = self.max_pool2(x)
        x = self.conv3(x)
        # 尺寸的逻辑:输入层将数据拉平[B,C,H,W] -> [B,C*H*W]
        x = paddle.reshape(x, [x.shape[0], -1])
        x = self.fc1(x)
        x = F.sigmoid(x)
        x = self.fc2(x)
        return x

27、CNTK

CNTK(Cognitive Toolkit) は、有向グラフを介してニューラル ネットワークを一連の計算ステップとして記述する深層学習ツールキットです。この有向グラフでは、リーフ ノードは入力値またはネットワーク パラメーターを表し、他のノードは入力に対する行列演算を表します。CNTK などの一般的なモデル タイプは、簡単に実装して組み合わせることができます CNN 。CNTK ネットワーク記述言語で (network description language, NDL) ニューラル ネットワークを記述します。簡単に言うと、入力特徴量、入力ラベル、いくつかのパラメータ、パラメータと入力の間の計算関係、ターゲットノードが何であるかを記述する必要があります。

NDLNetworkBuilder=[
    
    run=ndlLR
    
    ndlLR=[
      # sample and label dimensions
      SDim=$dimension$
      LDim=1
    
      features=Input(SDim, 1)
      labels=Input(LDim, 1)
    
      # parameters to learn
      B0 = Parameter(4) 
      W0 = Parameter(4, SDim)
      
      
      B = Parameter(LDim)
      W = Parameter(LDim, 4)
    
      # operations
      t0 = Times(W0, features)
      z0 = Plus(t0, B0)
      s0 = Sigmoid(z0)   
      
      t = Times(W, s0)
      z = Plus(t, B)
      s = Sigmoid(z)    
    
      LR = Logistic(labels, s)
      EP = SquareError(labels, s)
    
      # root nodes
      FeatureNodes=(features)
      LabelNodes=(labels)
      CriteriaNodes=(LR)
      EvalNodes=(EP)
      OutputNodes=(s,t,z,s0,W0)
    ]   

 

おすすめ

転載: blog.csdn.net/AbnerAI/article/details/130195499