首页 / PYTHON / 接触 Python 人工智能
接触 Python 人工智能
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了接触 Python 人工智能,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含33843字,纯文字阅读大概需要49分钟。
内容图文
![接触 Python 人工智能](/upload/InfoBanner/zyjiaocheng/599/473bd8b6aec7409ba6730d46d29edc2c.jpg)
Python 的人工智能
- 前言
- 什么是人工智能
- Python 在人工智能的应用
- 人工智能前沿
- 后记
1、前言
Hello World
人工智能,这个名词相信大家并不陌生,但很少有人能理解人工智能是什么,人工智能在生活中有什么应用,人工智能是不是传闻中那样能威胁到人类,这些疑问都是常常出现在我们思考中的并且难以解决,这次分享的内容适合没接触过人工智能的和刚开始接触人工智能的朋友,帮助对人工智能以及 Python 更进一步的理解和认识。
2、什么是人工智能
AI
Artificial Intelligence 译为人工智能,缩写为 AI,是计算机科学的分支,最开始的目的着重于模仿人类,硬件和软件上都趋于还原人类和人类行为,当然这并非易事,更非一朝一夕,所以细化出来,趋于模拟人类理论和扩展计算机作业人类工作,这样强大又神秘的理想,自然会被人们误解。
AI 也分类别,有高度 AI 和低度 AI 之分。高度 AI 顾名思义,拥有高强度和高思维能力的 AI,应用在实现最初目的和高度人类模式。当然,现阶段最高等 AI 仍无法通过算法和程序达到人类模式级别,其拥有的神经网络和机器算法可以超越人类擅长的部分专业和领域,但并不能做到自我优化和本能上的提升,所以现阶段大部分 AI 处于帮助人类作业和提供便利为主流,服务于人类,这些就是低度 AI。
我把理想状态的人工智能归类于机种类,如果有一天实现了最初目的,那么人类最好创造出适合人类和机种类的生存链,这样才可以避免源源不断的矛盾和难以挽回的结局。
3、Python 在人工智能的应用
应用
① Python 作为胶水语言,自然有利有弊,在人工智能中,核心算法是由 C/C++ 提供,Python 实现上层的接口调用和逻辑实现,比如,要实现一个完整的积木工程,就像小孩子拿各种各样的积木拼出一个积木城堡或是积木机器人,首先需要的就是积木,而积木则由 C/C++ 提供,Python 就是把这些积木搭起来的技巧和方法,做积木工程的人,就不需要自己把积木造出来,只需要知道完成这个积木工程的技巧和方法。
② Python 可以使人工智能的系统更加安全和稳定,因为 Python 可以完全对外暴露出封装的对象而不会被攻击底层,底层已经由 C/C++ 实现并且编译完成且不会被反编译,使用 Python 来实现逻辑和接口调用不会出现崩溃,错误和异常可以被处理,这些正是 Python 在人工智能大放异彩的理由之一,除此之外,还有简洁的语法和强大的原生数据类型作为支持以及开源的社区和广泛的应用,小到 shell 脚本大到企业 Web 应用,开发效率更是得到开发者的青睐。
③ Python 图像处理 —— pillow 模块,可以使用 pip 命令安装,API 简洁强大,功能丰富。可以打开和显示图像,打印和返回图像属性,保存图像,屏幕截图,图像裁剪和粘贴,转换图像文件格式,可以增强图像对比图,缩放图像大小,渲染图像等等。
④ Python 图像识别 —— pytesseract 模块,需要安装 tesseract-ocr 引擎,安装之后,需要修改 pytesseract 模块的引擎路径,路径改为在 tesseract-ocr 引擎安装目录下的 tesseract.exe 文件,也可以直接用 pip 命令安装 pytesseract 和 tesseract。pytesseract 模块可以识别图像中的文字并打印出来,需要注意的是,识别中文需要去下载中文识别库,找到简体中文(chi_sim.traineddata)的语言包,其他需要的也可以下载下来,放到 tesseract-ocr 引擎安装目录下的 tessdata 目录,使用时指定语言包,示例如下:
from PIL import Image
import pytesseract
im = Image.open(r'C:\demo.jpg')
print(pytesseract.image_to_string(im, lang='chi_sim'))
–
⑤ Python 语音识别 —— baidu-aip 模块,还有音频处理 pyaudio 模块,可以录制和播放音频,可以使用 pip 命令安装,有需要也可以安装音频转换工具 FFmpeg, 配置好 path 就可以了,也有文字转语音 —— pyttsx3,pip 安装即可,示例如下:
import pyttsx3
engine = pyttsx3.init()
engine.say("_Scale is handsome")
engine.runAndWait()
–
⑥ Python 机器学习也是 AI 的应用之一,因为 Python 拥有 AI 绝大部分需要的库,matplotlib,SimpleAI,nltk,Numpy 等,机器学习有监督机器学习算法,无监督机器学习算法和加固机器学习算法,这些机器学习算法可以支持计算机学习和可塑性记忆,避免一些不必要的重复编程。
监督机器学习算法的例子有随机森林、knn、决策树、逻辑回归。有白色黑色这些分类输出的分类问题和克,千克,米,厘米这些实际值输出的回归问题,而监督学习算法有输入和输出的映射函数 y = f(x) 用以训练出的数据集,输入 x 得以预测 y 值,下面看看这些例子的示例代码:
一、随机森林(来源于 https://github.com/eriklindernoren/ML-From-Scratch):
from __future__ import division, print_function
import numpy as np
import math
import progressbar
# 导入相关函数
from mlfromscratch.utils import divide_on_feature, train_test_split, get_random_subsets, normalize
from mlfromscratch.utils import accuracy_score, calculate_entropy
from mlfromscratch.unsupervised_learning import PCA
from mlfromscratch.supervised_learning import ClassificationTree
from mlfromscratch.utils.misc import bar_widgets
from mlfromscratch.utils import Plot
class RandomForest():
"""随机森林分类器。 使用分类树的集合
使用特征的随机子集训练数据的随机子集。
参数:
-----------
n_estimators:整数
使用的分类树的数量。
max_features:整数
分类树允许的最大要素数量
使用。
min_samples_split:整数
构造树时进行分割所需的最少样本数。
min_gain:浮点数
进一步拆分树所需的最小杂质。
max_depth:整数
一棵树的最大深度。
"""
def __init__(self, n_estimators=100, max_features=None, min_samples_split=2,
min_gain=0, max_depth=float("inf")):
self.n_estimators = n_estimators # 决策树数量
self.max_features = max_features # 每棵树的最大特征数
self.min_samples_split = min_samples_split
self.min_gain = min_gain # 获取最低限度信息
self.max_depth = max_depth # 树的最大深度
self.progressbar = progressbar.ProgressBar(widgets=bar_widgets)
# 初始化决策树
self.trees = []
for _ in range(n_estimators):
self.trees.append(
ClassificationTree(
min_samples_split=self.min_samples_split,
min_impurity=min_gain,
max_depth=self.max_depth))
def fit(self, X, y):
n_features = np.shape(X)[1]
# 如果尚未定义 max_features => 将其选择为
# sqrt(n_features)
if not self.max_features:
self.max_features = int(math.sqrt(n_features))
# 为每棵树选择一个随机的数据子集
subsets = get_random_subsets(X, y, self.n_estimators)
for i in self.progressbar(range(self.n_estimators)):
X_subset, y_subset = subsets[i]
# 特征封装(选择特征的随机子集)
idx = np.random.choice(range(n_features), size=self.max_features, replace=True)
# 保存元素索引以进行预测
self.trees[i].feature_indices = idx
# 选择与索引相对应的特征
X_subset = X_subset[:, idx]
# 决策树适合的数据
self.trees[i].fit(X_subset, y_subset)
def predict(self, X):
y_preds = np.empty((X.shape[0], len(self.trees)))
# 让每棵树都对数据进行预测
for i, tree in enumerate(self.trees):
# 树已训练的特征的索引
idx = tree.feature_indices
# 根据这些特征做出预测
prediction = tree.predict(X[:, idx])
y_preds[:, i] = prediction
y_pred = []
# 针对每个样本
for sample_predictions in y_preds:
# 选择最常见的决策
y_pred.append(np.bincount(sample_predictions.astype('int')).argmax())
return y_pred
–
主函数:
from __future__ import division, print_function
import numpy as np
import sys
sys.path.append("/content/drive/My Drive/learn/ML-From-Scratch/")
from sklearn import datasets
from mlfromscratch.utils import train_test_split, accuracy_score, Plot
from mlfromscratch.supervised_learning import RandomForest
def main():
data = datasets.load_digits()
X = data.data
y = data.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4, seed=2)
clf = RandomForest(n_estimators=100)
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print ("Accuracy:", accuracy)
Plot().plot_in_2d(X_test, y_pred, title="Random Forest", accuracy=accuracy, legend_labels=data.target_names)
if __name__ == "__main__":
main()
–
二、knn(来源于 https://github.com/eriklindernoren/ML-From-Scratch):
from __future__ import print_function, division
import numpy as np
from mlfromscratch.utils import euclidean_distance
class KNN():
""" K 最近邻分类器。
参数:
-----------
k:整数
决定其类别的最接近邻居的数量
我们希望预测的样本。
"""
def __init__(self, k=5):
self.k = k
def _vote(self, neighbor_labels):
""" 返回相邻样本中最常见的类 """
counts = np.bincount(neighbor_labels.astype('int'))
return counts.argmax()
def predict(self, X_test, X_train, y_train):
y_pred = np.empty(X_test.shape[0])
# 确定每个样本的类别
for i, test_sample in enumerate(X_test):
# 按训练样本与测试样本之间的距离对训练样本进行排序,并获得最接近的 K
idx = np.argsort([euclidean_distance(test_sample, x) for x in X_train])[:self.k]
# 提取最近的 K 个训练样本的标签
k_nearest_neighbors = np.array([y_train[i] for i in idx])
# 将样本标签作为最常见的类别标签
y_pred[i] = self._vote(k_nearest_neighbors)
return y_pred
–
主函数:
from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
from sklearn import datasets
from mlfromscratch.utils import train_test_split, normalize, accuracy_score
from mlfromscratch.utils import euclidean_distance, Plot
from mlfromscratch.supervised_learning import KNN
def main():
data = datasets.load_iris()
X = normalize(data.data)
y = data.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33)
clf = KNN(k=5)
y_pred = clf.predict(X_test, X_train, y_train)
accuracy = accuracy_score(y_test, y_pred)
print ("Accuracy:", accuracy)
# 使用 pca 将尺寸缩小到 2d 并绘制结果
Plot().plot_in_2d(X_test, y_pred, title="K Nearest Neighbors", accuracy=accuracy, legend_labels=data.target_names)
if __name__ == "__main__":
main()
–
三、决策树(来源于 https://github.com/eriklindernoren/ML-From-Scratch):
from __future__ import division, print_function
import numpy as np
from mlfromscratch.utils import divide_on_feature, train_test_split, standardize, mean_squared_error
from mlfromscratch.utils import calculate_entropy, accuracy_score, calculate_variance
class DecisionNode():
"""表示决策树中的决策节点或叶子的类
参数:
-----------
feature_i:整数
我们想要用作阈值度量的特征索引。
门槛:浮点数
我们将feature_i上的要素值与进行比较的值
确定预测。
值:浮点数
如果是分类树,则为类预测;如果是回归树,则为浮点值。
true_branch:DecisionNode
特征值满足阈值的样本的下一个决策节点。
false_branch:DecisionNode
特征值未达到阈值的样本的下一个决策节点。
"""
def __init__(self, feature_i=None, threshold=None,
value=None, true_branch=None, false_branch=None):
self.feature_i = feature_i # 测试功能的索引
self.threshold = threshold # 功能的索引,即功能的测试阈值
self.value = value # 如果节点是树中的叶子的值
self.true_branch = true_branch # '左'子树
self.false_branch = false_branch # '右'子树
# 回归树和分类树的超类
class DecisionTree(object):
"""447 / 5000
翻译结果
RegressionTree和ClassificationTree的超类。
参数:
-----------
min_samples_split:整数
构造树时进行分割所需的最少样本数。
min_impurity:浮点数
进一步拆分树所需的最小杂质。
max_depth:整数
一棵树的最大深度。
损失:功能
用于梯度增强模型以计算杂质的损失函数。
"""
def __init__(self, min_samples_split=2, min_impurity=1e-7,
max_depth=float("inf"), loss=None):
self.root = None # 初始化树的的根节点
# 最少 n 个样本以证明拆分合理
self.min_samples_split = min_samples_split
# 证明分裂的最小杂质
self.min_impurity = min_impurity
# 决策树的最大深度
self.max_depth = max_depth
# 计算杂质的功能(分类=>信息增益,regr =>减少方差。)
self._impurity_calculation = None
# 确定叶的 y 预测的功能
self._leaf_value_calculation = None
# 如果 y 是一热编码(multi-dim)或不是(一维)
self.one_dim = None
# 如果渐变增强
self.loss = loss
def fit(self, X, y, loss=None):
""" 建立决策树 """
self.one_dim = len(np.shape(y)) == 1
self.root = self._build_tree(X, y)
self.loss=None
def _build_tree(self, X, y, current_depth=0):
""" 建立决策树并将 X 和 y 分别分解的递归方法
X 的特征(基于杂质)最能区分数据"""
largest_impurity = 0
best_criteria = None # 特征索引和阈值
best_sets = None # 数据子集
# 检查是否需要扩展 y
if len(np.shape(y)) == 1:
y = np.expand_dims(y, axis=1)
# 将 y 添加为 X 的最后一列
Xy = np.concatenate((X, y), axis=1)
n_samples, n_features = np.shape(X)
if n_samples >= self.min_samples_split and current_depth <= self.max_depth:
# 计算每个特征的杂质
for feature_i in range(n_features):
# Feature_i 的所有值
feature_values = np.expand_dims(X[:, feature_i], axis=1)
unique_values = np.unique(feature_values)
# 遍历要素列 i 和 i 的所有唯一值
# 计算杂质
for threshold in unique_values:
# 根据 X 的特征值是否在索引 feature_i 上除以 X 和 y
# 达到门槛
Xy1, Xy2 = divide_on_feature(Xy, feature_i, threshold)
if len(Xy1) > 0 and len(Xy2) > 0:
# 选择两组的 y 值
y1 = Xy1[:, n_features:]
y2 = Xy2[:, n_features:]
# 计算杂质
impurity = self._impurity_calculation(y, y1, y2)
# 如果此阈值导致比以前更高的信息获取
# 记录保存阈值和特征
# 索引
if impurity > largest_impurity:
largest_impurity = impurity
best_criteria = {"feature_i": feature_i, "threshold": threshold}
best_sets = {
"leftX": Xy1[:, :n_features], # 左子树的 X
"lefty": Xy1[:, n_features:], # 左子树的 y
"rightX": Xy2[:, :n_features], # 右子树的 X
"righty": Xy2[:, n_features:] # 右子树的 y
}
if largest_impurity > self.min_impurity:
# 为左右分支建立子树
true_branch = self._build_tree(best_sets["leftX"], best_sets["lefty"], current_depth + 1)
false_branch = self._build_tree(best_sets["rightX"], best_sets["righty"], current_depth + 1)
return DecisionNode(feature_i=best_criteria["feature_i"], threshold=best_criteria[
"threshold"], true_branch=true_branch, false_branch=false_branch)
# 我们在叶子=>确定价值
leaf_value = self._leaf_value_calculation(y)
return DecisionNode(value=leaf_value)
def predict_value(self, x, tree=None):
""" 在树上进行递归搜索,并通过
我们最终得到的叶子的价值 """
if tree is None:
tree = self.root
# 如果我们有一个值(即我们在一片叶子上)=>返回值作为预测
if tree.value is not None:
return tree.value
# 选择我们要测试的功能
feature_value = x[tree.feature_i]
# 确定我们将遵循左分支还是右分支
branch = tree.false_branch
if isinstance(feature_value, int) or isinstance(feature_value, float):
if feature_value >= tree.threshold:
branch = tree.true_branch
elif feature_value == tree.threshold:
branch = tree.true_branch
# 测试子树
return self.predict_value(x, branch)
def predict(self, X):
"""逐个分类样本并返回标签集"""
y_pred = [self.predict_value(sample) for sample in X]
return y_pred
def print_tree(self, tree=None, indent=" "):
""" 递归打印决策树"""
if not tree:
tree = self.root
# 如果我们在叶子=>打印标签
if tree.value is not None:
print (tree.value)
# 深入树下
else:
# Print test
print ("%s:%s? " % (tree.feature_i, tree.threshold))
# Print the true scenario
print ("%sT->" % (indent), end="")
self.print_tree(tree.true_branch, indent + indent)
# Print the false scenario
print ("%sF->" % (indent), end="")
self.print_tree(tree.false_branch, indent + indent)
class XGBoostRegressionTree(DecisionTree):
"""
XGBoost的回归树
- 参考 -
http://xgboost.readthedocs.io/en/latest/model.html
"""
def _split(self, y):
""" y 在中间列的左半部分包含 y_true,并且
y_pred 在右半部分,拆分并返回两个矩阵"""
col = int(np.shape(y)[1]/2)
y, y_pred = y[:, :col], y[:, col:]
return y, y_pred
def _gain(self, y, y_pred):
nominator = np.power((y * self.loss.gradient(y, y_pred)).sum(), 2)
denominator = self.loss.hess(y, y_pred).sum()
return 0.5 * (nominator / denominator)
def _gain_by_taylor(self, y, y1, y2):
# 分裂
y, y_pred = self._split(y)
y1, y1_pred = self._split(y1)
y2, y2_pred = self._split(y2)
true_gain = self._gain(y1, y1_pred)
false_gain = self._gain(y2, y2_pred)
gain = self._gain(y, y_pred)
return true_gain + false_gain - gain
def _approximate_update(self, y):
# y 分为 y,y_pred
y, y_pred = self._split(y)
# 牛顿法
gradient = np.sum(y * self.loss.gradient(y, y_pred), axis=0)
hessian = np.sum(self.loss.hess(y, y_pred), axis=0)
update_approximation = gradient / hessian
return update_approximation
def fit(self, X, y):
self._impurity_calculation = self._gain_by_taylor
self._leaf_value_calculation = self._approximate_update
super(XGBoostRegressionTree, self).fit(X, y)
class RegressionTree(DecisionTree):
def _calculate_variance_reduction(self, y, y1, y2):
var_tot = calculate_variance(y)
var_1 = calculate_variance(y1)
var_2 = calculate_variance(y2)
frac_1 = len(y1) / len(y)
frac_2 = len(y2) / len(y)
# 计算方差减少
variance_reduction = var_tot - (frac_1 * var_1 + frac_2 * var_2)
return sum(variance_reduction)
def _mean_of_y(self, y):
value = np.mean(y, axis=0)
return value if len(value) > 1 else value[0]
def fit(self, X, y):
self._impurity_calculation = self._calculate_variance_reduction
self._leaf_value_calculation = self._mean_of_y
super(RegressionTree, self).fit(X, y)
class ClassificationTree(DecisionTree):
def _calculate_information_gain(self, y, y1, y2):
# 计算信息增益
p = len(y1) / len(y)
entropy = calculate_entropy(y)
info_gain = entropy - p * \
calculate_entropy(y1) - (1 - p) * \
calculate_entropy(y2)
return info_gain
def _majority_vote(self, y):
most_common = None
max_count = 0
for label in np.unique(y):
# 用标签计数样品的出现次数
count = len(y[y == label])
if count > max_count:
most_common = label
max_count = count
return most_common
def fit(self, X, y):
self._impurity_calculation = self._calculate_information_gain
self._leaf_value_calculation = self._majority_vote
super(ClassificationTree, self).fit(X, y)
–
主函数:
from __future__ import division, print_function
import numpy as np
from sklearn import datasets
import matplotlib.pyplot as plt
import sys
import os
import sys
sys.path.append("/content/drive/My Drive/learn/ML-From-Scratch/")
# Import helper functions
from mlfromscratch.utils import train_test_split, standardize, accuracy_score
from mlfromscratch.utils import mean_squared_error, calculate_variance, Plot
from mlfromscratch.supervised_learning import ClassificationTree
def main():
print ("-- Classification Tree --")
data = datasets.load_iris()
X = data.data
y = data.target
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4)
clf = ClassificationTree()
clf.fit(X_train, y_train)
y_pred = clf.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
print ("Accuracy:", accuracy)
Plot().plot_in_2d(X_test, y_pred,
title="Decision Tree",
accuracy=accuracy,
legend_labels=data.target_names)
if __name__ == "__main__":
main()
–
回归主函数:
from __future__ import division, print_function
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import sys
sys.path.append("/content/drive/My Drive/learn/ML-From-Scratch/")
from mlfromscratch.utils import train_test_split, standardize, accuracy_score
from mlfromscratch.utils import mean_squared_error, calculate_variance, Plot
from mlfromscratch.supervised_learning import RegressionTree
def main():
print ("-- Regression Tree --")
# 负载温度数据
data = pd.read_csv('mlfromscratch/data/TempLinkoping2016.txt', sep="\t")
time = np.atleast_2d(data["time"].values).T
temp = np.atleast_2d(data["temp"].values).T
X = standardize(time) # 时间、年份的小数[0,1]
y = temp[:, 0] # 减少到一
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3)
model = RegressionTree()
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
y_pred_line = model.predict(X)
# 色彩图
cmap = plt.get_cmap('viridis')
mse = mean_squared_error(y_test, y_pred)
print ("Mean Squared Error:", mse)
# 绘制结果
m1 = plt.scatter(366 * X_train, y_train, color=cmap(0.9), s=10)
m2 = plt.scatter(366 * X_test, y_test, color=cmap(0.5), s=10)
m3 = plt.scatter(366 * X_test, y_pred, color='black', s=10)
plt.suptitle("Regression Tree")
plt.title("MSE: %.2f" % mse, fontsize=10)
plt.xlabel('Day')
plt.ylabel('Temperature in Celcius')
plt.legend((m1, m2, m3), ("Training data", "Test data", "Prediction"), loc='lower right')
plt.savefig("test2.png")
plt.show()
if __name__ == "__main__":
main()
–
四、逻辑回归(来源于 https://github.com/yunshuipiao/sw_machine_learning/tree/master/machine_learning_algorithm/logistic_regression):
import math
import numpy as np
import matplotlib.pyplot as plt
def sigmoid(z):
return 1 / (1 + np.exp(-z))
def init_data():
data = np.loadtxt('data.csv')
dataMatIn = data[:, 0:-1]
classLabels = data[:, -1]
dataMatIn = np.insert(dataMatIn, 0, 1, axis=1) #特征数据集,添加1是构造常数项x0
return dataMatIn, classLabels
def grad_ascent(dataMatIn, classLabels):
dataMatrix = np.mat(dataMatIn) #(m,n)
labelMat = np.mat(classLabels).transpose()
m, n = np.shape(dataMatrix)
weights = np.ones((n, 1)) #初始化回归系数(n, 1)
alpha = 0.001 #步长
maxCycle = 500 #最大循环次数
for i in range(maxCycle):
h = sigmoid(dataMatrix * weights) #sigmoid 函数
error = labelMat - h #y-h, (m - 1)
weights = weights + alpha * dataMatrix.transpose() * error
return weights
def plotBestFIt(weights):
dataMatIn, classLabels = init_data()
n = np.shape(dataMatIn)[0]
xcord1 = []
ycord1 = []
xcord2 = []
ycord2 = []
for i in range(n):
if classLabels[i] == 1:
xcord1.append(dataMatIn[i][1])
ycord1.append(dataMatIn[i][2])
else:
xcord2.append(dataMatIn[i][1])
ycord2.append(dataMatIn[i][2])
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(xcord1, ycord1,s=30, c='red', marker='s')
ax.scatter(xcord2, ycord2, s=30, c='green')
x = np.arange(-3, 3, 0.1)
y = (-weights[0, 0] - weights[1, 0] * x) / weights[2, 0] #matix
ax.plot(x, y)
plt.xlabel('X1')
plt.ylabel('X2')
plt.show()
# 随机梯度上升法的思想是,每次只使用一个数据样本点来更新回归系数。这样就大大减小计算开销
def stoc_grad_ascent(dataMatIn, classLabels):
m, n = np.shape(dataMatIn)
alpha = 0.01
weights = np.ones(n)
for i in range(m):
h = sigmoid(sum(dataMatIn[i] * weights)) #数值计算
error = classLabels[i] - h
weights = weights + alpha * error * dataMatIn[i]
return weights
# 随机梯度上升法的思想是,每次只使用一个数据样本点来更新回归系数。这样就大大减小计算开销
def stoc_grad_ascent_one(dataMatIn, classLabels, numIter=150):
m, n = np.shape(dataMatIn)
weights = np.ones(n)
for j in range(numIter):
dataIndex = list(range(m))
for i in range(m):
alpha = 4 / (1 + i + j) + 0.01 #保证多次迭代后新数据仍然有影响力
randIndex = int(np.random.uniform(0, len(dataIndex)))
h = sigmoid(sum(dataMatIn[i] * weights)) # 数值计算
error = classLabels[i] - h
weights = weights + alpha * error * dataMatIn[i]
del(dataIndex[randIndex])
return weights
# 评价算法优劣势看它是或否收敛,是否达到稳定值,收敛越快,算法越优。
if __name__ == '__main__':
dataMatIn, classLabels = init_data()
r = stoc_grad_ascent_one(dataMatIn, classLabels)
r = np.mat(r).transpose()
plotBestFIt(r)
–
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def show_sigmoid():
x = [1, 2, 3, 4, 6, 7, 8, 9, 10]
y = [0, 0, 0, 0, 1, 1, 1, 1, 1]
train_X = np.asarray(x)
train_Y = np.asarray(y)
fig = plt.figure()
plt.xlim(-1, 12)
plt.ylim(-0.5, 1.5)
plt.scatter(train_X, train_Y)
s_X = np.linspace(-2, 12, 100)
s_Y = 1 / (1 + np.exp(-6 * (s_X - 5)))
plt.plot(s_X, s_Y)
plt.show()
def init_data():
x = [1, 2, 3, 4, 6, 7, 8, 9, 10]
y = [0, 0, 0, 0, 1, 1, 1, 1, 1]
train_X = np.asarray(np.row_stack((np.ones(shape=(1, len(x))), x)), dtype=np.float64)
train_Y = np.asarray(y, dtype=np.float64)
train_W = np.asarray([-1, 1], dtype=np.float64).reshape(1, 2)
return train_X, train_Y, train_W
def sigmoid(X):
return 1 / (1 + np.exp(-X))
def lossfunc(X, Y, W):
n = len(Y)
return (-1 / n) * np.sum(Y * np.log(sigmoid(np.matmul(W, X))) + (1 - Y) * np.log((1 - sigmoid(np.matmul(W, X)))))
def gradient_descent(X, Y, W, learningrate=0.001, trainingtimes=500):
n = len(Y)
for i in range(trainingtimes):
W = W - (learningrate / n) * np.sum((sigmoid(np.matmul(W, X)) - Y) * X, axis=1)
#for gif
if 0 == i % 1000 or (100 > i and 0 == i % 2):
b_Trace.append(W[0, 0])
w_Trace.append(W[0, 1])
loss_Trace.append(lossfunc(X, Y, W))
return W
def update(i):
try:
ax.lines.pop(0)
except Exception:
pass
plot_X = np.linspace(-1, 12, 100)
W = np.asarray([b_Trace[i], w_Trace[i]]).reshape(1, 2)
X = np.row_stack((np.ones(shape=(1, len(plot_X))), plot_X))
plot_Y = sigmoid(np.matmul(W, X))
line = ax.plot(plot_X, plot_Y[0], 'r-', lw=1)
ax.set_xlabel(r"$Cost\ %.6s$" % loss_Trace[i])
return line
if __name__ == '__main__':
# 初始化数据
loss_Trace = []
w_Trace = []
b_Trace = []
x = [1, 2, 3, 4, 6, 7, 8, 9, 10]
y = [0, 0, 0, 0, 1, 1, 1, 1, 1]
train_X = np.asarray(np.row_stack((np.ones(shape=(1, len(x))), x)), dtype=np.float64)
train_Y = np.asarray(y, dtype=np.float64)
train_W = np.asarray([-1, 1], dtype=np.float64).reshape(1, 2)
final_W = gradient_descent(train_X, train_Y, train_W, 0.3, 100000)
print(final_W)
print(np.asarray([b_Trace, w_Trace]))
print(loss_Trace)
fig, ax = plt.subplots()
ax.scatter(x, y)
ani = animation.FuncAnimation(fig, update, frames=len(w_Trace), interval=100)
plt.show()
–
data.csv:
-0.017612 14.053064 0
-1.395634 4.662541 1
-0.752157 6.538620 0
-1.322371 7.152853 0
0.423363 11.054677 0
0.406704 7.067335 1
0.667394 12.741452 0
-2.460150 6.866805 1
0.569411 9.548755 0
-0.026632 10.427743 0
0.850433 6.920334 1
1.347183 13.175500 0
1.176813 3.167020 1
-1.781871 9.097953 0
-0.566606 5.749003 1
0.931635 1.589505 1
-0.024205 6.151823 1
-0.036453 2.690988 1
-0.196949 0.444165 1
1.014459 5.754399 1
1.985298 3.230619 1
-1.693453 -0.557540 1
-0.576525 11.778922 0
-0.346811 -1.678730 1
-2.124484 2.672471 1
1.217916 9.597015 0
-0.733928 9.098687 0
-3.642001 -1.618087 1
0.315985 3.523953 1
1.416614 9.619232 0
-0.386323 3.989286 1
0.556921 8.294984 1
1.224863 11.587360 0
-1.347803 -2.406051 1
1.196604 4.951851 1
0.275221 9.543647 0
0.470575 9.332488 0
-1.889567 9.542662 0
-1.527893 12.150579 0
-1.185247 11.309318 0
-0.445678 3.297303 1
1.042222 6.105155 1
-0.618787 10.320986 0
1.152083 0.548467 1
0.828534 2.676045 1
-1.237728 10.549033 0
-0.683565 -2.166125 1
0.229456 5.921938 1
-0.959885 11.555336 0
0.492911 10.993324 0
0.184992 8.721488 0
-0.355715 10.325976 0
-0.397822 8.058397 0
0.824839 13.730343 0
1.507278 5.027866 1
0.099671 6.835839 1
-0.344008 10.717485 0
1.785928 7.718645 1
-0.918801 11.560217 0
-0.364009 4.747300 1
-0.841722 4.119083 1
0.490426 1.960539 1
-0.007194 9.075792 0
0.356107 12.447863 0
0.342578 12.281162 0
-0.810823 -1.466018 1
2.530777 6.476801 1
1.296683 11.607559 0
0.475487 12.040035 0
-0.783277 11.009725 0
0.074798 11.023650 0
-1.337472 0.468339 1
-0.102781 13.763651 0
-0.147324 2.874846 1
0.518389 9.887035 0
1.015399 7.571882 0
-1.658086 -0.027255 1
1.319944 2.171228 1
2.056216 5.019981 1
-0.851633 4.375691 1
-1.510047 6.061992 0
-1.076637 -3.181888 1
1.821096 10.283990 0
3.010150 8.401766 1
-1.099458 1.688274 1
-0.834872 -1.733869 1
-0.846637 3.849075 1
1.400102 12.628781 0
1.752842 5.468166 1
0.078557 0.059736 1
0.089392 -0.715300 1
1.825662 12.693808 0
0.197445 9.744638 0
0.126117 0.922311 1
-0.679797 1.220530 1
0.677983 2.556666 1
0.761349 10.693862 0
-2.168791 0.143632 1
1.388610 9.341997 0
0.317029 14.739025 0
–
无监督机器学习算法的例子有 Apriori 算法和 K 均值。有数据中的固有分组这些聚类问题和需要发现描述大部分数据的规则的关联问题,而无监督学习算法没有监督学习法那样的映射输出,而是有助于发现数据中的规律,下面看看这些例子的示例代码:
一、Apriori 算法(来源于 https://www.jb51.net/article/130219.htm):
import numpy as np
from itertools import combinations # 迭代工具
data = [[1,2,5], [2,4], [2,3], [1,2,4], [1,3], [2,3], [1,3], [1,2,3,5], [1,2,3]]
minsp = 2
d = []
for i in range(len(data)):
d.extend(data[i])
new_d = list(set(d))
def satisfy(s, s_new, k): # 更新确实存在的L
e =[]
ss_new =[]
for i in range(len(s_new)):
for j in combinations(s_new[i], k): # 迭代产生所有元素可能性组合
e.append(list(j))
if ([l for l in e if l not in s]) ==[] :
ss_new.append(s_new[i])
e = []
return ss_new # 筛选满足条件的结果
def count(s_new): # 返回narray格式的C
num = 0
C = np.copy(s_new)
C = np.column_stack((C, np.zeros(C.shape[0])))
for i in range(len(s_new)):
for j in range(len(data)):
if ([l for l in s_new[i] if l not in data[j]]) ==[] :
num = num+1
C[i,-1] = num
num = 0
return C
def limit(L): # 删掉不满足阈值的C
row = []
for i in range(L.shape[0]):
if L[i,-1] < minsp :
row.append(i)
L = np.delete(L, row, 0)
return L
def generate(L, k): # 实现由L至C的转换
s = []
for i in range(L.shape[0]):
s.append(list(L[i,:-1]))
s_new = []
# L = L.delete(L, -1, 1)
# l = L.shape[1]
for i in range(L.shape[0]-1):
for j in range(i+1, L.shape[0]):
if (L[j,-2]>L[i,-2]):
t = list(np.copy(s[i]))
t.append(L[j,-2])
s_new.append(t) # s_new为列表
s_new = satisfy(s, s_new, k)
C = count(s_new)
return C
# 初始的C与L
C = np.zeros([len(new_d), 2])
for i in range(len(new_d)):
C[i:] = np.array([new_d[i], d.count(new_d[i])])
L = np.copy(C)
L = limit(L)
# 开始迭代
k = 1
while (np.max(L[:,-1]) > minsp):
C = generate(L, k) # 由L产生C
L = limit(C) # 由C产生L
k = k+1
# 对最终结果去重复
print((list(set([tuple(t) for t in L])))
# 结果为 [(1.0, 2.0, 3.0, 2.0), (1.0, 2.0, 5.0, 2.0)]
–
二、K 均值(来源于 https://www.jb51.net/article/48154.htm):
import pylab as pl
# calc Euclid squire
def calc_e_squire(a, b):
return (a[0]- b[0]) ** 2 + (a[1] - b[1]) **2
# init the 20 point
a = [2,4,3,6,7,8,2,3,5,6,12,10,15,16,11,10,19,17,16,13]
b = [5,6,1,4,2,4,3,1,7,9,16,11,19,12,15,14,11,14,11,19]
# define two k_value
k1 = [6,3]
k2 = [6,1]
# defint tow cluster
sse_k1 = []
sse_k2 = []
while True:
sse_k1 = []
sse_k2 = []
for i in range(20):
e_squire1 = calc_e_squire(k1, [a[i], b[i]])
e_squire2 = calc_e_squire(k2, [a[i], b[i]])
if (e_squire1 <= e_squire2):
sse_k1.append(i)
else:
sse_k2.append(i)
# change k_value
k1_x = sum([a[i] for i in sse_k1]) / len(sse_k1)
k1_y = sum([b[i] for i in sse_k1]) / len(sse_k1)
k2_x = sum([a[i] for i in sse_k2]) / len(sse_k2)
k2_y = sum([b[i] for i in sse_k2]) / len(sse_k2)
if k1 != [k1_x, k1_y] or k2 != [k2_x, k2_y]:
k1 = [k1_x, k1_y]
k2 = [k2_x, k2_y]
else:
break
kv1_x = [a[i] for i in sse_k1]
kv1_y = [b[i] for i in sse_k1]
kv2_x = [a[i] for i in sse_k2]
kv2_y = [b[i] for i in sse_k2]
pl.plot(kv1_x, kv1_y, 'o')
pl.plot(kv2_x, kv2_y, 'or')
pl.xlim(1, 20)
pl.ylim(1, 20)
pl.show()
–
加固(增强)机器学习算法的例子有马尔可夫决策过程(MDP),计算机使用试错法进行学习,不断优化。
⑦ AI 还可应用于金融贸易、诊断、远程通讯和游戏音乐等等。应用范围广泛,可以说,如今世界上遍布最广泛的就是电子产业,在人们的生活中无处不在,而 AI 更是电子产业的灵魂,所以在未来,掌握 AI 核心技术是非常重要的,Python 也是。AI 领域的研究还包括机器人、语言识别、图像识别、自然语言处理和专家系统等等。
4、人工智能前沿
前沿技术
① 智能语音交互,说到人工智能的前沿领域,就要说到高度 AI,说到高度 AI,就要提到最基本的智能语音交互,因为不论是 AI 还是人类,都是要完成信息的 I/O 流,通过信息进行交流,关于信息的学术解释和讨论是数不胜数的,这里就不赘述了,语音交互,当然是指声音和音频上的,而智能语音交互是建立在语音交互的基础上,通过 AI 的算法和训练,使 AI 达到人类正常交流水平的目的,因为智能也意味着拥有更高度的思维能力和意识甚至是自我。要真正做到人机智能语音交互还是很困难的,因为目前为止,还没有出现过高度智能的 AI,而智能语音交互的水平,还停留在人类单方面输入,AI 通过训练得以输出的状态。所以这项技术也是组成高度 AI 的重要部分。
高度 AI 要做到智能语音交互,首先得有基本的接受和处理信息的能力,也就是拥有完整的语音识别系统。语音识别系统的构建大致上有两部分:训练和识别。
训练可以是对线下收集大量的语音和语言库进行信息挖掘和信号处理,得到语音识别系统需要的声学模型和语言模型,识别则是通过线上进行实时演算和处理,最后输出给外界达成交流。识别也分为前端和后端,前端模块主要是进行端点检测,去除多余的静音和非说话声,还有降噪和特征提取;后端模块是利用训练好的声学模型和语言模型对外界输入的说话特征进行向量统计模式识别,得到重要的文字信息,后端模块还有一个自适应的反馈模块,可以对外界输入的语音进行自我学习,对声学模型和语音模型进行校正,提高识别的准确率。
然后是拥有完整的语音和语言输出能力,人类传递信息的方式有很多,比如通过动作、表情、声音和感情。其中,感情就是一种特殊的信息传递方式,人类可以通过简单的一句【我喜欢你】、【我爱你】传递给外界的个体,表达出自己的情感和想法,愿意和对方在一起或是愿意为对方付出什么,而其中包含的信息是要受外界的环境影响的,比如,在未结婚情况下说出【我爱你】,意思是我喜欢你,想和你交往甚至结婚,在已结婚情况下说出【我喜欢你】,意思是我爱你,愿意和你同甘共苦甚至白头偕老。如果高度 AI 不能通过分析外界因素辅助信息处理,那么输出的结果还是可能差强人意。此外,硬件上的要求也是相当的严苛,人类发声通过咽喉的器官对气流进行处理,其中复杂的细节是现代电子设备做不到的,现代电子设备是通过接受外界的原声进行录制和播放,却不能做到人类咽喉那样,通过特殊的振声和压缩以及释放,所以真正做到高度 AI 智能语音交互水平绝非易事。
② 说到感情,AI 前沿里有个情感计算,情感也可计算?是的,你没听错,是情感计算,不是感情计算,情感包含喜怒哀乐,严格来说,这也包含在智能语音交互里面,通过训练和识别,计算出一句话所表达出的情感,是高兴还是伤心,是痛苦还是快乐,是愤怒还是悲伤。
Python 在情感计算上也有涉猎,snownlp 是是受到了 TextBlob 的启发,针对中文处理编写,可以进行中文分词、情感分析、文本分类、繁转简体、提取关键字和文本摘要、词性标注和 tf、idf、Tokenization,snownlp 没有用 NLTK,所有的算法都是本地实现且自带一些训练好的字典,GitHub 地址在 https://github.com/isnowfy/snownlp,pip 可以直接安装 snownlp 模块,示例如下:
from snownlp import SnowNLP
# 演示文本
demo1 = '我今天只吃了两个鸡蛋,真是太糟糕了'
demo2 = '我今天吃了大餐,真是太爽了'
# 返回积极情绪概率,趋近 1 表示积极,趋近 0 表示消极
d1 = SnowNLP(demo1)
d2 = SnowNLP(demo2)
print(demo1, d1.sentiments)
print(demo2, d2.sentiments)
–
③ 数据安全技术,数据安全是越来越受到重视的领域,各大 AI 巨头也在重点关注,包括开发者生态的建立和竞争,以下是数据安全的百度词条【国际标准化组织(ISO)对计算机系统安全的定义是:为数据处理系统建立和采用的技术和管理的安全保护,保护计算机硬件、软件和数据不因偶然和恶意的原因遭到破坏、更改和泄露。由此计算机网络的安全可以理解为:通过采用各种技术和管理措施,使网络系统正常运行,从而确保网络数据的可用性、完整性和保密性。所以,建立网络安全保护措施的目的是确保经过网络传输和交换的数据不会发生增加、修改、丢失和泄露等。】
数据安全技术的代表有数据容错技术和数据通信安全技术。数据容错技术有故障诊断、故障屏蔽和功能转移;数据通信安全技术有【互联网模型应用保密和鉴别技术】与【端对端保密和鉴别通信技术】以及【应用层上加密数据保密和鉴别模块技术】
【互联网模型应用保密和鉴别技术】包括【传输层安全协议(SSL(安全套接层))】,由 SSL 记录协议【涉及应用程序提供的信息的分段、压缩、数据认证和加密】和 SSL 握手协议【用来交换版本号、加密算法、身份认证并交换密钥】组成,和【网络层安全协议(IPSec 协议)】,由 IPSec 三要素【AH(认证协议头)、ESP(安全加载封装)、IKMP(互联网密钥管理协议)】组成,提供认证、数据完整性和机密性,所用到【MD5、SHA-1 和 DES、3DES 和 Diffie-Hellman】算法。
【端对端保密和鉴别通信技术】包括 VPN(虚拟专用网),采用隧道技术、加解密技术、密钥管理技术和身份认证技术。
【应用层上加密数据保密和鉴别模块技术】包括应用层安全服务,可以灵活处理单个文件安全性,常用 PGP、SSH。
5、后记
Goodbye
感谢 CSDN,感谢 C 友们的支持
内容总结
以上是互联网集市为您收集整理的接触 Python 人工智能全部内容,希望文章能够帮你解决接触 Python 人工智能所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。