整理了27个Python人工智能库,一定要收藏(2)

上一篇 / 下一篇  2022-08-22 11:06:34

  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、spaCy
  spaCy 是一个免费的开源库,用于 Python 中的高级 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
  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、Pandas
  Pandas 是一个快速、强大、灵活且易于使用的开源数据分析和操作工具, Pandas 可以从各种文件格式比如 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()
Pandas
  15、Matplotlib
  Matplotlib 是Python的绘图库,它提供了一整套和 matlab 相似的命令 API,可以生成出版质量级别的精美图形,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()
Matplotlib
  16、Seaborn
  Seaborn 是在 Matplotlib 的基础上进行了更高级的API封装的Python数据可视化库,从而使得作图更加容易,应该把 Seaborn 视为 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()
seaborn
  17、Orange
  Orange 是一个开源的数据挖掘和机器学习软件,提供了一系列的数据探索、可视化、预处理以及建模组件。Orange 拥有漂亮直观的交互式用户界面,非常适合新手进行探索性数据分析和可视化展示;同时高级用户也可以将其作为 Python 的一个编程模块进行数据操作和组件开发。
  使用 pip 即可安装 Orange,好评~
  $ pip install orange3
  安装完成后,在命令行输入 orange-canvas 命令即可启动 Orange 图形界面:
  $ orange-canvas
  启动完成后,即可看到 Orange 图形界面,进行各种操作。
Orange
  18、PyBrain
  PyBrain 是 Python 的模块化机器学习库。它的目标是为机器学习任务和各种预定义的环境提供灵活、易于使用且强大的算法来测试和比较算法。PyBrain 是 Python-Based Reinforcement Learning, Artificial Intelligence and Neural Network Library 的缩写。
  我们将利用一个简单的例子来展示 PyBrain 的用法,构建一个多层感知器 (Multi Layer Perceptron, 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
  MILK(MACHINE LEARNING TOOLKIT) 是 Python 语言的机器学习工具包。它主要是包含许多分类器比如 SVMS、K-NN、随机森林以及决策树中使用监督分类法,它还可执行特征选择,可以形成不同的例如无监督学习、密切关系传播和由 MILK 支持的 K-means 聚类等分类系统。
  使用 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作为示例,展示在 TensorFlow2.x 中构建卷积神经网络 (Convolutional Neural Network, CNN)。
  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))

TAG: 软件开发 Python

 

评分:0

我来说两句

Open Toolbar