Okay, so now what I've done is I've gone to the Gaussian Naive Bayes
documentation page.
sklearn.naive_bayes.GaussianNB.
This was that algorithm that I set out to find and
now that I've, now I've found the SK Learn documentation page.
So the first thing that I see right here, actually this is one of the things I
love about the SK Learn documentation, is it's full of examples.
When I was actually developing the code for this class, this was one of
the first things that I would always do is I would come find the example code
and I would try to just run in my Python interpreter,
see if I could get it working.
And almost invariably it works right out of the box.
So here's something that's just very simple.
There's only a few lines here that are really important.
So let me point them out to you and
then I'll show you the code I've actually written for the example we just saw,
and you'll start to recognize some of these lines.
But first let's introduce them.
So the first one that's really important is this one right here.
Above this it's just creating some, some training points that we can use,
it's not that important.
This is where the real meat starts, is with this import statement and if you've
programmed in Python before, you're well acquainted with import statements.
This is the way that you bring in external modules into the code that you're
writing so that you don't have to completely re-implement everything every time,
you can use code that someone else has already written.
So we say from sklearn.naive_bayes going to import GaussianNB.
Very good.
The next thing that we're going to do is we're going to use that to
create a classifier.
So classifier equals GaussianNB.
If you miss your import statement.
If you forget this line for
some reason, then this line is going to throw an error.
So if you end up seeing some kind of error that says that it doesn't recognize
this function.
It's probably a problem with your import statement.
So, okay, we've created our classifier.
So now the code is all sort of ready to go.
The next thing that we need to do is we need to fit it.
And we've been using the word train interchangeably with fit.
So this is where we actually give it the training data,
and it learns the patterns.
So we have the classifier that we just created.
We're calling the fit function on it, and then the two arguments that we pass to
fit are x, which in this case are the features and y which are the labels.
This is always going to be true in supervised classification.
Is that it's going to call this fit function and
then it's going to have the features.
And then the labels.
And then the last thing that we do is we ask the classifier that
we've just trained for some predictions.
So we give it a new point.
In this case the point is negative 0.8, negative 1.
And we ask for this what do you think the label is for this particular point?
What's the, what class does it belong to?
So in this particular case it says it belongs to class number one.
Or you could imagine for some other point it might say class number two.
So of course you have to have already fit the classifier before you
can call predict on it.
Because when it's fitting the data that's where it's
actually learning the patterns.
Then here is where it's using those patterns to make a prediction.
So, that's it.
That's kind of, now you know most all there is to
know to get this working in the first example that I've done.
حسنًا، ما فعلته الآن هو أنني انتقلت إلى صفحة الوثائق
الخاصة بمصنِّف بايز المبسط الغاوسي.
sklearn.naive_bayes.GaussianNB.
وهذه كانت الخوارزمية التي عمدت إلى إيجادها
والآن عثرت على صفحة وثائق SK Learn.
إن أول ما أراه هنا، وهو في الواقع أحد الأمور التي تعجبني في
وثائق SK Learn، هو أنها مليئة بالأمثلة.
وأثناء وضع التعليمة البرمجية لهذا الدرس، كان أول
ما قمت به كما أقوم به دائمًا هو البحث عن مثال تعليمة برمجية،
ثم محاولة تشغيلها في مترجم Python،
لمعرفة ما إذا كنت قادرة على جعلها تعمل.
وكانت دائمًا ما تعمل دون تعديل تقريبًا.
وإليكم أمر بسيط للغاية.
توجد هنا بضعة أسطر فقط تُعد مهمة حقًا.
فدعوني أوضحها لكم
وبعدها سأعرض لكم التعليمة البرمجية التي كتبتها بالفعل للمثال الذي رأيناه للتو،
وستبدؤون في التعرف على بعض هذه الأسطر.
ولكن لنقدمها أولاً.
هذا السطر الموجود هنا هو أول الأسطر الهامة حقًا.
والأسطر الموجودة فوقه هي لمجرد إنشاء بعض نقاط التدريب التي يمكننا استخدامها،
وهي ليست على درجة كبيرة من الأهمية.
هنا يبدأ الجزء الأساسي، وهو يبدأ بعبارة الاستيراد هذه، وإذا كنتم قد قمتم
بالبرمجة باستخدام لغة Python من قبل، فأنتم تعرفون عبارات الاستيراد جيدًا.
وهذه هي الطريقة التي تجلبون بها الوحدات الخارجية إلى التعليمة البرمجية التي
تكتبونها كي لا تضطروا إلى إعادة تنفيذ كل شيء بالكامل في كل مرة،
ويمكنكم استخدام تعليمة برمجية كتبها شخص آخر بالفعل.
إذن سنقول، من sklearn.naive_bayes يتم استيراد GaussianNB.
جيد جدًا.
ما سنقوم به بعد ذلك هو استخدام ذلك
لإنشاء مصنف.
إذن، المصنف يساوي GaussianNB.
وإذا فاتتكم عبارة الاستيراد.
و إذا نسيتم هذا السطر لسبب ما،
فسيقوم هذا السطر بإظهار خطأ.
وبالتالي إذا انتهى بكم الأمر برؤية خطأ ما يقول أنه لا يتعرف على
هذه الدالة،
فهذا يعني على الأرجح وجود مشكلة في عبارة الاستيراد.
حسنًا إذن، لقد قمنا بإنشاء المصنف.
والآن أصبحت التعليمة البرمجية كلها نوعًا ما جاهزة للعمل.
ما نحتاج إلى القيام به بعد ذلك هو ملاءمتها.
وقد كنا نستخدم المصطلحين "تدريب" و"ملاءمة" بالتبادل.
إذن، هذه هي الخطوة التي نقوم فيها بالفعل بإعطائها بيانات التدريب،
وهي تتعلم الأنماط.
لدينا المصنف الذي قمنا للتو بإنشائه.
وسنقوم بطلب دالة الاحتواء له، ثم الوسيطين اللذين نمررهما للملاءمة وهما x،
التي تكون الميزات في هذه الحالة، وy وهي التسميات.
وسيكون ذلك صحيحًا دائمًا بالنسبة للتصنيف الخاضع للإشراف.
وهو أنه سيقوم بطلب دالة الاحتواء هذه،
ثم سيكون لديه الميزات،
ثم التسميات.
وآخر ما سنقوم به هو أننا سنطلب من المصنف
الذي دربناه للتو القيام ببعض التنبؤات.
سنعطيه نقطة جديدة،
وفي هذه الحالة ستكون النقطة هي سالب 0.8 وسالب 1.
ثم سنسأله عن هذه النقطة، ما هي التسمية لهذه النقطة بالتحديد؟
ما هي الفئة التي تنتمي إليها؟
في هذه الحالة بالتحديد يخبرنا بأن النقطة تنتمي إلى الفئة رقم 1.
أو تخيلوا أنه سيجيب بالنسبة لنقطة أخرى أنها تنتمي إلى الفئة رقم 2.
بالطبع يجب أن تكونوا قد قمتم بالفعل بملاءمة المصنف قبل أن
تتمكنوا من طلب تنبؤ منه.
لأنه يتعلم الأنماط فعليًا
أثناء ملاءمة البيانات.
ثم يستخدم هنا هذه الأنماط للقيام بتنبؤ ما.
إذن هذا هو الأمر.
هذا نوعًا ما كل ما يمكن معرفته حتى الآن
لإجراء ذلك في المثال الأول الذي قدمته.
Okay, so now what I've done is I've gone to the Gaussian Naive Bayes
documentation page.
sklearn.naive_bayes.GaussianNB.
This was that algorithm that I set out to find and
now that I've, now I've found the sklearn documentation page.
So the first thing that I see right here, actually this is one of the things I
love about the SK Learn documentation, is it's full of examples.
When I was actually developing the code for this class, this was one of
the first things that I would always do is I would come find the example code
and I would try to just run in my Python interpreter,
see if I could get it working.
And almost invariably it works right out of the box.
So here's something that's just very simple.
There's only a few lines here that are really important.
So let me point them out to you and
then I'll show you the code I've actually written for the example we just saw,
and you'll start to recognize some of these lines.
But first let's introduce them.
So the first one that's really important is this one right here.
Above this it's just creating some, some training points that we can use,
it's not that important.
This is where the real meat starts, is with this import statement and if you've
programmed in Python before, you're well acquainted with import statements.
This is the way that you bring in external modules into the code that you're
writing so that you don't have to completely re-implement everything every time,
you can use code that someone else has already written.
So we say from sklearn.naive_bayes going to import GaussianNB.
Very good.
The next thing that we're going to do is we're going to use that to
create a classifier.
So classifier equals GaussianNB.
If you miss your import statement.
If you forget this line for
some reason, then this line is going to throw an error.
So if you end up seeing some kind of error that says that it doesn't recognize
this function.
It's probably a problem with your import statement.
So, okay, we've created our classifier.
So now the code is all sort of ready to go.
The next thing that we need to do is we need to fit it.
And we've been using the word train interchangeably with fit.
So this is where we actually give it the training data,
and it learns the patterns.
So we have the classifier that we just created.
We're calling the fit function on it, and then the two arguments that we pass to
fit are x, which in this case are the features and y which are the labels.
This is always going to be true in supervised classification.
Is that it's going to call this fit function and
then it's going to have the features.
And then the labels.
And then the last thing that we do is we ask the classifier that
we've just trained for some predictions.
So we give it a new point.
In this case the point is negative 0.8, negative 1.
And we ask for this what do you think the label is for this particular point?
What's the, what class does it belong to?
So in this particular case it says it belongs to class number one.
Or you could imagine for some other point it might say class number two.
So of course you have to have already fit the classifier before you
can call predict on it.
Because when it's fitting the data that's where it's
actually learning the patterns.
Then here is where it's using those patterns to make a prediction.
So, that's it.
That's kind of, now you know most all there is to
know to get this working in the first example that I've done.
それではGaussian Naive Bayesの
ドキュメントを読んでみましょう。
"sklearn.naive_bayes.GaussianNB"です。
これは探していたアルゴリズムの名前で、
検索した結果sklearnのドキュメントを見つけました。
最初に見るのは、そしてsklearnのドキュメントの素晴らしいところですが
たくさんの使用例が記載されています。
私は実際にコードを書くときは
いつでもまず最初にサンプルコードを探し出して
それから自分のpythonインタプリタで実行し
それらがちゃんと動作するか確認するようにしています。
そしてたいていの場合それはうまく動きます。
さて、ここにとてもシンプルなサンプルがありますね。
ここに何行かありますが、これはとても重要です。
ですから少し着目して
実際にサンプルコードを書いて動くところをお見せしましょう。
コードの意味が理解できると思います。
最初にライブラリをimportします。
ですからここ、この1行はとても重要です。
この上のコードは、学習用のデータを生成しているだけです。
なのでそれほど重要ではありません。
本題はこのimport文から始まります。
pythonプログラミングの経験があれば、import文は知っていますね。
importは外部のライブラリを使うための構文です。
既に存在するプログラムを再作成する無駄を省き、
誰かが作ってくれたコードを使い回すことができます。
ここではsklearn.naive_bayesからGaussianNBライブラリを使います、と宣言しています。
いいですね。
次に私たちがやろうとしていることは
分類器の作成です。
分類器はGaussianNBです。
import文が失敗していると
この行を何かの拍子に書き忘れたりすると
この行でエラーが出ます。
もし実行時にエラーが出て、このファンクションを
認識できませんと言ったメッセージなら
import文にミスがあります。
OK、分類器を作成しました。
これで準備は万端です。
次に私たちがしなくてはいけないのは分類器の"fit"です。
私たちは訓練するという言葉の代わりに"fit"を使います。
つまりここで実際に学習用データを与え
パターンを学習させているのです。
さっき作成した分類器の
fit() ファンクションを実行します。渡す引数は二つです。
引数の X は feature 、そして Y は label です。
"supervised classification"においては共通なのですが
fit() ファンクションを実行し
引数にfeatureと
labelを渡します。
そして最後に、学習させたばかりの分類器に
推定をさせています。
新しいデータを与えてみます。
与えるデータは [-0.8, -1] です。
皆さんはこのデータの label はなんだと思いますか。
つまりどの分類に所属すると思いますか。
分類器は「1」の分類だと推定しました。
では「2」の分類だと推定されるデータを思いつきますか。
もちろん分類器に推定をさせる前には
分類器を fit させておく必要があります。
データに対してfitを行なっている時が、
実際にパターンを学習している部分だからです。
そしてここは学習したパターンを使って推定を行なっている部分です。
というわけで、
このコードの動作について知っておくべきことを説明しました。
これが機械学習の最初のサンプルコードです。
Certo. Então, agora, acessei a página de documentação do
Gaussian Naive Bayes.
sklearn.naive_bayes.GaussianNB.
Esse era o algoritmo que eu pretendia descobrir.
Encontrei a página de documentação do SK Learn.
A primeira coisa que vejo aqui — aliás, isso é uma das coisas que
adoro em relação à documentação do SK Learn — é que há muitos exemplos.
Quando estava desenvolvendo o código para esta aula, uma das
primeiras coisas que eu sempre fazia era procurar o código de exemplo
e tentar executá-lo em meu interpretador Python para
ver se funcionava.
Quase que invariavelmente, funcionava sem alterações.
Bem, aqui está algo bastante simples.
Há apenas algumas linhas aqui que são realmente importantes.
Vou indicá-las para você e,
depois, mostrarei o código que realmente escrevi para o exemplo que acabamos de ver,
e você começará a reconhecer algumas delas.
Mas, primeiro, vou apresentá-las.
A primeira linha realmente importante é esta aqui.
Acima dela, vemos apenas a criação de alguns pontos de treinamento que podemos usar;
nada tão importante.
É aqui que começa a parte principal, com esta declaração import; se você já
tiver programado no Python antes, estará familiarizado com as declarações import.
Essa é a maneira de incorporar módulos externos no código que você
está escrevendo, de modo que não precise sempre reimplementar tudo.
Você pode usar o código que outra pessoa já escreveu.
Então, dizemos que sklearn.naive_bayes importará GaussianNB.
Muito bem.
Em seguida, usaremos isso para
criar um classificador.
Portanto, o classificador é igual a GaussianNB.
Se você esquecer a declaração import,
se você esquecer esta linha por
algum motivo, ela lançará um erro.
Assim, se você receber algum tipo de erro indicando que essa função não
foi reconhecida,
provavelmente, o problema está na sua declaração import.
Muito bem, criamos nosso classificador,
Agora, o código está pronto para uso.
Depois, precisamos ajustá-lo.
Estávamos usando a palavra treinar de modo intercambiável com ajustar.
Então, aqui é onde realmente fornecemos os dados de treinamento
e ele reconhece os padrões.
Então, temos o classificador que acabamos de criar.
Estamos chamando a função fit nele. Depois, os dois argumentos que passamos para
fit são x, que, neste caso, são as características, e y, que são os rótulos.
Isso sempre acontecerá na classificação supervisionada.
A função fit será chamada e, em seguida,
haverá as características.
E, depois, os rótulos.
Por último, solicitamos ao classificador que
acabamos de treinar algumas previsões.
Então, damos a ele um novo ponto.
Neste caso, o ponto é 0,8 negativo e 1 negativo.
E perguntamos qual deve ser o rótulo para este ponto específico?
A que classe ele pertence?
Portanto, neste caso, ele diz que pertence a uma classe de número um.
Ou você pode imaginar que, para outro ponto, pudesse ser a classe número dois.
É claro que você já deve ter ajustado o classificador antes de
solicitar uma previsão.
Porque, quando ele está ajustando os dados, está,
na verdade, reconhecendo os padrões.
É aqui que ele está usando esses padrões para fazer uma previsão.
Bem, é isso.
Parece que, agora, você já sabe quase tudo
para que possa colocar isso em funcionamento no primeiro exemplo que eu fiz.
现在我们已经来到了高斯朴素贝叶斯的文档页面
现在我们已经来到了高斯朴素贝叶斯的文档页面
sklearn.naive_bayes.GaussianNB
这就是我要找的算法
我找到了 sklearn 文档页面
我在这里看到的最明显的内容 这也是我喜欢 SK Learn 文档的一个原因
就是有大量的实例
当我在编写用在这门课程里的代码时
我总是先找到样本代码
然后在我的 Python 解释器里运行一遍
看看能不能运行成功
几乎所有代码都能正常运行
这样事情就很简单了
只需要关注几行重要的代码就可以了
我先为你指出这些代码
然后我会向你展示之前给实例编写的代码
之后你就能识别这些代码了
我们先来介绍一下
第一行非常重要的代码就是这里
上面的代码只是用来生成一些可以利用的训练点而已
就没有那么重要了
这是重点的开始部分 就是这个 import 语句
如果你之前用过 Python 那你应该对 import 语句很熟悉
这个语句的作用是把外部模块引入你编写的代码里
所以你没有必要每次都完全重新实现所有代码
你可以使用他人编写好的代码
所以我们从 sklearn.naive_bayes 引入 GaussianNB 模块
很好
接下来 我们要利用这些内容
创建分类器
把 GaussianNB 赋值给 clf(分类器)
如果你缺少 import 语句
如果你忘了添加这行
那么运行时这一行就会报错
所以如果你看到某些错误显示无法识别这个函数
所以如果你看到某些错误显示无法识别这个函数
那么问题很可能就出在你的 import 语句上
我们创建好了分类器
代码也可以投入使用了
接下来要做的就是调整这些代码
我们已使用字词“fit”替换了“train”
这里是我们实际提供训练数据的地方
它会学习各种模式
然后就形成了我们刚刚创建的分类器
我们在分类器上调用 fit 函数 接下来将两个参数传递给 fit 函数
一个是特征 x 一个是标签 y
在监督分类中这个过程都是如此
即先调用此 fit 函数
然后依次获得特征
和标签
最后我们让已完成了训练的分类器
进行一些预测
我们为它提供一个新点
本示例中是 -0.8、-1
我们想知道的是 这个特定点的标签是什么?
它属于什么类?
在这个示例中 分类器将该点归在了 “1” 这个分类下
或者你可以设想一下 对于其他点分类器可能会将其归在 “2” 这个分类下
当然了 你必须先训练好分类器
才能调用分类器上的预测函数
因为使用数据训练的过程就是
它实际学习模式的过程
然后分类器能利用学得的模式来进行预测
这就是整个过程
现在你能知道我在这里做的大部分操作
都是为了让这些代码在第一个示例中运行