More Related Content Similar to A brief introduction to Machine Learning (20) More from Wen-Tien Chang (20) A brief introduction to Machine Learning2. 我是谁
• 张⽂文钿 a.k.a. ihower
• https://ihower.tw
• Ruby on Rails 实战圣经 作者
• 全栈营研究员
• Ruby Developer user since 2006
• 过去两年年业余关注机器学习技术
11. 历史数据
年年紀 性別 資產 ⾏行行業 … 會不會買
21 M 120 … 會
50 F 800 … 不會
41 F 400 … 會
35 M 300 … 會
36 M 500 … 不會
28 M 60 … 不會
55 F 950 … 會
14. 怎么求权重 w ?
假设只有两个 feature,就会是个⼆二维问题可以做图⽰示意
Credit: 林林軒⽥田老師 http://www.csie.ntu.edu.tw/~htlin/mooc/ 機器學習課程
35. 常⻅见的监督式学习算法
• Linear Regression 、Linear Classifier
• Logistic Regression
• Decision Tree、Random forest
• Naive Bayes classifiers
• Support Vector Machine (SVM)
• Artificial Neural Network (ANN)
47. # https://github.com/daugaard/linear-regression
# gem install ruby_linear_regression
require 'ruby_linear_regression'
x_data = [ [1,1], [2,2], [3,3], [4,4] ]
y_data = [ 1,2,3,4 ]
linear_regression = RubyLinearRegression.new
linear_regression.load_training_data(x_data, y_data)
linear_regression.train_gradient_descent(0.0005, 1000, true)
prediction_x = [5, 5]
prediction_y = linear_regression.predict(prediction_x)
puts prediction_y
50. # gem install liblinear-ruby
# https://github.com/kei500/liblinear-ruby
# https://www.practicalai.io/implementing-classification-using-
logistic-regression-in-ruby/
require 'liblinear'
model = Liblinear.train(
{ solver_type: Liblinear::L2R_LR }, # L2-regularized logistic
[-1, -1, 1, 1], # labels
[[-2, -2], [-1, -1], [1, 1], [2, 2]], # training data
)
puts Liblinear.predict(model, [0.5, 0.5])
54. # https://github.com/igrigorik/decisiontree
# gem install decisiontree
# gem install graphr
require 'decisiontree'
attributes = ['Age', 'Education', 'Income', 'Marital Status']
training = [
['36-55', 'Masters', 'High', 'Single', 1],
['18-35', 'High School', 'Low', 'Single', 0],
['< 18', 'High School', 'Low', 'Married', 1]
]
dec_tree = DecisionTree::ID3Tree.new(attributes, training,
1, :discrete)
dec_tree.train
test = ['< 18', 'High School', 'Low', 'Single', 0]
decision = dec_tree.predict(test)
puts "Predicted: #{decision} ... True decision: #{test.last}";
dec_tree.graph("discrete")
55. ⽀支持向量量機 SVM
(Support Vector Machine)
• 如何让分类器更更能抵抗杂讯?找⼀一条最胖(margin)的线
• 离边界最近的点就决定线 (这些点就叫做 support
vector candidate),其他点不影响结果
• 优点:精确度好、但计算很花时间,不适合巨量量数据
Credit: 林林軒⽥田老師 http://www.csie.ntu.edu.tw/~htlin/mooc/ 機器學習課程
56. # gem install rb-libsvm
# https://www.practicalai.io/implementing-classification-using-a-svm-
in-ruby/
require 'libsvm'
# This library is namespaced.
problem = Libsvm::Problem.new
parameter = Libsvm::SvmParameter.new
parameter.cache_size = 1 # in megabytes
parameter.eps = 0.001
parameter.c = 10
examples = [ [1,0,1], [-1,0,-1] ].map {|ary|
Libsvm::Node.features(ary) }
labels = [1, -1]
problem.set_examples(labels, examples)
model = Libsvm::Model.train(problem, parameter)
pred = model.predict(Libsvm::Node.features(1, 1, 1))
puts "Example [1, 1, 1] - Predicted #{pred}"
62. • 数据如何收集?
• 会不会有缺漏或错误? 数据需要清理理
• Features 如何决定? 把所有 Features 全部丢进算法可以吗?
• 计算需要数字,可是很多数据是字符串串啊
• 原始数据怎么处理理?例例如图片、影像、声⾳音
• 有的 feature 数字很⼤大、有的 feature 数字很⼩小怎么办?
• 如何挑选和评估模型?
• 如何整合进应⽤用中?
• 数据量量超级⼤大怎么办?
64. 机器学习的完整流程
• 数据收集、撷取
• 数据探索 (Exploratory data analysis)、视觉化
• 数据清理理、预处理理
• 数据切分 (Train data, Test data)
• 选择算法、建立模型、评估模型
• 整合进应⽤用程序 (或进⾏行行发表)
66. 预处理理
• 缺失值处理理: 删除或补全
• 标准化数值
• 让平均是0、标准差是 1
• 让不同 features 的数值能够公平,消除数量量级的影响
• 类别 (categorical) 资料编码
• 有顺序的,可⽤用数字
• 没顺序的,⽤用 one-hot encoding
67. One-Hot-Encoding
• 例例如 { “IE”, “Chrome”, “Safari” } 三个分类
• 转成三种 features
• “IE” => [ 1 0 0 ]
• “Chrome” => [ 0 1 0 ]
• “Safari” => [ 0 0 1 ]
• 如果维度太多,可以考虑进⼀一步做 Feature Hashing
68. Feature Extraction (特征萃取)
• 将数据中有利利于分类的特征撷取出来, 可能需要将数据视觉化,帮助
我们理理解数据进⾏行行挑选
• 需要 Domain Knowledge,引入額外特徵
• 已知⽤用⼾戶 Geolocation,增加該地點的⼈人⼝口統計數據(平均收入、⼈人
⼝口密度等等)
• 家庭⽤用電隨著溫度升⾼高,因此預測⽤用電量量時,應該把溫度加入特徵
• 原始数据若若是非数字的,需要想办法撷取出数字特征
• 例例如:图片/声⾳音/⾃自然语⾔言⽂文字
69. Bag of Words (词袋模型)
(1) John likes to watch movies. Mary likes movies too.
(2) John also likes to watch football games.
[1, 2, 1, 1, 2, 0, 0, 0, 1, 1]
[1, 1, 1, 1, 0, 1, 1, 1, 0, 0]
[
"John",
"likes",
"to",
"watch",
"movies",
"also",
"football",
"games",
"Mary",
"too"
]
https://zh.wikipedia.org/zh-cn/词袋模型
76. Overfitting 怎么解?
• 当 features 太多,或模型太厉害的时候
• Overfitting 怎么解
• 减少 features,挑选真正有⽤用的
• 减少模型复杂度,例例如增加 regularization 正则化、剪枝、
Early Stop…etc 在计算过程中去惩罚复杂模型
78. 数据切分和模型评估
如何得知⽬目前是⽋欠拟合还是过拟合?需要仪表板
• 切分 Training Dataset 和 Testing Dataset,通常约 7:3
• 当 Training dataset 跟 Validation dataset 准确率都不好 =>
Underfitting
• 当 Training dataset 准确率提⾼高,但是 Validation dataset 准确率
却下降时 => Overfitting
• 如何挑选和评估模型?
• 需要换不同 model 进⾏行行实验
• 如果⽤用 Gradient Descent 梯度下降法:需要调整超参数
80. 现成的 Ruby ML ⼯工具
• ⽤用法都不同
• 缺乏 预处理理功能
• 缺乏 Cross-Validation 功能
• 缺乏维护....
• 很像是 Toy Project…
83. Python ⼯工具介紹
• Scikit-learn: Python 的 Machine Learning 框架
• Pandas: 提供 Data frames 數據分析
• Matplotlib 視覺化⼯工具
• Jupyter notebook 實驗簿
• PySpark ⼤大數據處理理
110. # https://github.com/tangledpath/ruby-fann
require 'ruby-fann'
train = RubyFann::TrainData.new(:inputs=>[[0.3, 0.4, 0.5], [0.1,
0.2, 0.3]], :desired_outputs=>[[0.7], [0.8]])
fann = RubyFann::Standard.new(:num_inputs=>3, :hidden_neurons=>[2,
8, 4, 3, 4], :num_outputs=>1)
fann.train_on_data(train, 1000, 10, 0.1) # 1000 max_epochs, 10
errors between reports and 0.1 desired MSE (mean-squared-error)
puts fann.run([0.3, 0.2, 0.4])
122. 深度学习⼯工具
• Google 的 Tensorflow
• Facebook 的 Caffe
• 微軟的 CNTK
• MXNet (Amazon官⽅方推薦)
• PyTorch
• Theano
123. 硬件战场
• Nvidia GPU (CUDA 架構)
• Google TPU
• Intel Movidius
• Apple “Neural Engine” chip (iPhone X)
125. model = Sequential()
model.add(Dense(512, input_shape=(784,)))
model.add(Activation('relu'))
model.add(Dropout(0.2))
model.add(Dense(512))
model.add(Activation('relu'))
model.add(Dropout(0.2))
model.add(Dense(10))
model.add(Activation('softmax'))
model.summary()
model.compile(loss='categorical_crossentropy',
optimizer=RMSprop(),
metrics=['accuracy'])
history = model.fit(X_train, Y_train,
batch_size=batch_size, nb_epoch=nb_epoch,
verbose=1, validation_data=(X_test, Y_test))
score = model.evaluate(X_test, Y_test, verbose=0)
print('Test score:', score[0])
print('Test accuracy:', score[1])
129. 预测部分
• 汇出 model 参数,⽤用 Ruby 实作预测
• But…. How about feature engineering part?
• 调⽤用 Python 程序
• Web API ⽅方案: ⽤用 flask
• RPC ⽅方案 grpc
• pycall 直接調⽤用 python function
• 第三⽅方 API (GCP,AWS,Azure)
133. Google Cloud
• ⽤用⾃自⼰己的资料做训练
• Cloud Machine Learning Engine
• Machine Learning as API ⽤用现成的模型
• Cloud Vision
• Cloud Speech
• Cloud Natural Language
• Cloud Translation API
• Cloud Video Intelligence
139. # gem install google-cloud-vision
# export GOOGLE_CLOUD_PROJECT=“<project-id>“
# export GOOGLE_CLOUD_KEYFILE=“<json-key-file>“
require "google/cloud/vision"
vision = Google::Cloud::Vision.new
image = vision.image "demo-image.jpg"
puts image.labels
https://cloud.google.com/vision/
143. ⼀一些想法
• 数据科学家(Data Scientist) v.s. 数据⼯工程师(Data Engineer)
• 不⼀一定要成为数据科学家才能利利⽤用机器学习
• A.I. is a feature,we will just use it as a gem
• ⼯工程师及早参与,最后才能成功进入产品,⽽而不是只是数据
科学报告
144. 如何学机器学习
• Top-down 或 bottom-up 学习法?
• 机器学习开发者的现代化路路径:不需要从统计学微积分
开始
http://www.csdn.net/article/2015-08-27/2825551
https://machinelearningmastery.com/dont-implement-
machine-learning-algorithms/
• Coursera 的机器学习课程则偏理理论
145. 参考资料
• 台灣⼤大學 林林軒⽥田 / 機器學習基⽯石、機器學習技術
http://www.csie.ntu.edu.tw/~htlin/mooc/
• 台灣⼤大學 李宏毅 / ⼀一天搞懂深度學習
https://www.slideshare.net/tw_dsconf/ss-62245351
• edX BerkeleyX: CS190.1x Scalable Machine Learning
• SciRuby Machine Learning Current Status and Future
https://speakerdeck.com/mrkn/sciruby-machine-learning-current-status-and-future
• 李俊良 / Feature Engineering in Machine Learning
https://www.slideshare.net/tw_dsconf/feature-engineering-in-machine-learning
• Python Machine Learning, Packt Publishing
• Data Science from Scratch, O’Reilly