The principal components analysis that I'm doing happens to live in
this function called doPCA.
And it looks very familiar to a lot of the stuff we've done
before in scikit-learn.
You have an import statement where you
actually get the module out that has the code that you want.
You create, in this case, the principal components analysis.
You fit it.
And then you can return that as an object.
And so what I do is I, I get my principal components that, analysis that way.
And I can ask some very interesting,
some very important questions of it by accessing the attributes.
So let's explain these three lines.
This is how I actually get the information out of my PCA object.
The first, the explained variance ratio is actually where the eigenvalues live.
So by printing out this, this line here.
This is the way that I know that the first principle component has about 90,
91 percent of the variation in the data, and the second one has about 9, or
10 percent.
Those numbers come from this statement.
And then the second thing that I do is I look at the first and
second principle components.
I get these out of the components attribute of my PCA object.
So the components is going to be a list,
a Python list that has as many principle components in it.
As I ask for as a parameter.
So in that case, I have two principal components that I'm getting.
So I name them the first and second pc.
So in previous quizzes where we were talking about,
what's the direction in of, say, x prime in the xy original feature space,
we came up with two numbers that were sort of packaged together into a vector.
You can access that directional information through these components.
Once I've fit my principle components analysis I have to,
in order to do anything, perform something like a transformation of the data.
And this code I will just give you in the starter code for the quiz.
What I'm doing here is, I'm visualizing it.
The first line is in red.
I'll be plotting the first principle component,
the locations of all the points along that principle component.
As well as the direction of the principle components.
I'm accessing that information by using the elements of the first PC vector.
Then in Cyan or kind of a teal color, I'll be accessing the second
principle component, and in blue I have the original data.
So let me show you what this looks like,
and then you give it a try yourself in the quiz.
The first thing that you get is that you print out the eigenvalues.
Remember that's this explained variance ratio information.
And then the second thing is that you'll get a scatter plot.
And it should look something like this.
So you remember the red was the direction of our first principle component.
And that's hopefully exactly where you guessed it was.
Certainly intuitively seems like it's in the right place.
The cyan is perpendicular to that.
And then the blue is the original data points.
One thing that I'll add is that it looks to the eye like the red and
the cyan are not perfectly orthogonal.
This doesn't quite look like a 90 degree angle.
But remember that our axis have different scales.
That this one goes all the way out to ten million,
the y axis only goes out to less than half of that, about four million.
So, in reality, if we were to plot everything proportionally,
this graph should be twice as long as it is tall.
And if we were to visualize it in exactly that way, they would be orthogonal
يوجد تحليل المكونات الرئيسية الذي أستخدمه في هذه
الدالة التي تسمى doPCA.
وهي تبدو شبيهةً جدًا للكثير مما قمنا به من قبل في
scikit-learn.
حيث توجد هنا عبارة استيراد نحصل من خلالها
على الوحدة التي تحتوي على التعليمة البرمجية التي نريدها.
وفي هذه الحالة، سنقوم بإنشاء تحليل المكونات الرئيسية.
ثم نقوم بملاءمته.
ثم يمكننا إرجاع ذلك ككائن.
ما أقوم به هو، أنني أحصل على تحليل المكونات الرئيسية بتلك الطريقة.
ويمكنني طرح بعض الأسئلة المشوقة،
والهامة بشأنه عن طريق الوصول إلى السمات.
إذن، لنشرح هذه الأسطر الثلاثة.
هذه هي الطريقة التي أحصل بها فعليًا على المعلومات من كائن PCA.
السطر الأول، نسبة التباين الموضحة هي بالفعل الموقع الذي توجد بها قيم آيغن.
وبالتالي، بإدخال هذا السطر الموجود هنا،
بهذه الطريقة أعرف أن المكون الرئيسي الأول يحتوى على نسبة 90، أو
91 بالمائة من التباين في البيانات، والثاني يحتوى على نسبة 9،
أو 10 بالمائة.
وتأتي تلك الأرقام من هذه العبارة.
الخطوة الثانية التي أقوم بها هي النظر إلى
المكونين الرئيسيين الأول والثاني.
واستخرجها من سمة المكونات الخاصة بكائن PCA.
وستكون المكونات عبارة عن قائمة،
قائمة Python تحتوي على العديد من المكونات الرئيسية.
وهو ما أطلبه كمعلمة.
وفي هذه الحالة، لدي مكونان رئيسيان أريد الحصول عليهما.
لذا أسميتهما first pc وsecond pc.
في الاختبارات القصيرة السابقة عندما كنا نتحدث عن
اتجاه x في فضاء الميزات الأصلية xy،
توصلنا إلى رقمين تم وضعهما معًا في متجه.
ويمكن الوصول إلى المعلومات الاتجاهية من خلال هذين المكونين.
وبمجرد ملاءمة تحليل المكونات الرئيسية يجب علي أن أقوم بما يشبه تحويل البيانات،
حتى أتمكن من القيام بأي شيء.
وسأعطيكم هذه التعليمة البرمجية في تعليمة بادئ التشغيل البرمجية من أجل الاختبار.
ما أقوم به هنا هو وضع تصور لها.
سيكون الخط الأول باللون الأحمر.
سأقوم بتخطيط المكون الرئيسي،
ومواقع جميع النقاط بالنسبة لهذا المكون الرئيسي.
وكذلك اتجاه المكونات الرئيسية.
وأصل إلى هذه المعلومات باستخدام عناصر متجه المكون الرئيسي الأول.
وباللون الأزرق السماوي أو نوع من الأزرق الفاتح، سأصل إلى المكون الرئيسي
الثاني، وستكون البيانات الأصلية باللون الأزرق.
دعوني أوضح لكم كيف يبدو ذلك،
وبعدها يمكنكم تجربته بأنفسكم في الاختبار القصير.
أول ما نقوم به هو إدخال قيم آيغن.
وتذكروا أن هذه هي معلومات نسبة التباين الموضحة.
وبعد ذلك ستحصلون على رسم مبعثر،
وسيبدو شكله قريبًا من هذا الشكل.
وكما تذكرون، كان اللون الأحمر يرمز إلى اتجاه المكون الرئيسي الأول.
وأتمنى أن يكون هذا هو الموضع الذي خمنتم أنه موجود به.
بالطبع من الناحية البديهية يبدو أنه في الموضع الصحيح.
ويتعامد عليه اللون الأزرق السماوي.
وأخيرًا، لدينا اللون الأزرق وهو يمثل نقاط البيانات الأصلية.
سأضيف أمرًا آخر وهو أنه يبدو للعيان أن اللونين الأحمر
والأزرق السماوي ليسا متعامدين تمامًا.
فهذا لا يبدو تمامًا كزاوية 90 درجة.
ولكن تذكروا أن المحور هنا له قياسات مختلفة.
وأن هذا المحور يمتد حتى 10 ملايين،
وأن محور y يمتد إلى أقل من نصف ذلك ،أي حوالي 4 ملايين.
إذن، إذا أردنا أن نخطط كل شيء بشكل متناسب في الواقع،
ينبغي أن يكون طول هذا الرسم البياني ضعف ارتفاعه.
وإذا تصورناه بهذا الشكل بالضبط، فسيكونان متعامدين.
A análise de componentes principais que eu estou fazendo fica nessa
função chamada doPCA.
E ela se parece bastante com muitas outras que nós já fizemos
anteriormente no scikit-learn.
Você tem uma declaração import, na qual você,
na verdade, retira o módulo que possui o código desejado.
Você cria, nesse caso, a análise de componentes principais.
Você a ajusta.
E, então, você a retorna como um objeto.
E aí o que faço é: uso minha análise de componentes principais desse modo.
E posso fazer algumas perguntas
muito interessantes, muito importantes sobre isso acessando os atributos.
Então, vamos explicar estas três linhas.
É assim que obtenho realmente as informações do meu objeto PCA.
A primeira, explained_variance_ratio, é onde estão realmente os autovalores.
Então, imprimindo isso, essa linha aqui,
é como sei que o primeiro componente de princípio tem aproximadamente 90,
91 por cento da variação nos dados, e o segundo tem cerca de 9 ou
10 por cento.
Esses números resultam desta instrução.
Depois, a segunda coisa que faço é verificar o primeiro e
o segundo componentes de princípio.
Eu faço isso através do atributo components do meu objeto PCA.
O components consiste em uma lista,
uma lista Python, que possui tantos componentes de princípio
quantos eu solicitar como um parâmetro.
Neste caso, tenho dois componentes principais.
Eu os nomeio como first_pc e second_pc.
Em testes anteriores, em que conversamos sobre
a direção de x' no espaço de característica original xy,
descobrimos dois números que estavam, de certa forma, empacotados juntos em um vetor.
Você pode acessar essa informação direcional por meio desses componentes.
Depois de ajustar minha análise de componentes de princípio,
para poder fazer alguma coisa, tenho que fazer uma espécie de transformação dos dados.
E este código eu darei a você no código base para o teste.
Aqui eu estou apenas visualizando-o.
A primeira linha está em vermelho.
Plotarei o primeiro componente de princípio,
a localização de todos os pontos ao longo desse componente.
Bem como a direção dos componentes de princípio.
Estou acessando essa informação por meio dos elementos do vetor first_pc.
Depois, em ciano, ou azul-petróleo, acessarei o segundo
componente de princípio e, em azul, eu tenho os dados originais.
Mostrarei a você a aparência disso,
e depois você tentará sozinho no teste.
A primeira coisa que você tem é a exibição dos autovalores.
Lembre-se de que essa é a informação de explained_variance_ratio.
Depois, você vê um gráfico de dispersão.
Ele terá mais ou menos essa aparência.
Lembre-se de que a linha vermelha era a direção do nosso primeiro componente de princípio.
E ela está exatamente onde você achou que estaria.
Intuitivamente, ela já aparenta estar no lugar certo.
A linha em ciano é perpendicular a ela.
E, em azul, estão os pontos de dados originais.
Uma coisa que eu gostaria de acrescentar é que as linhas vermelha e
ciana não parecem perfeitamente ortogonais.
Parece que elas não formam um perfeito ângulo de 90 graus.
Mas lembre-se de que nossos eixos têm escalas diferentes.
Este aqui vai até dez milhões,
e o eixo y chega a menos da metade disso, por volta de quatro milhões.
Na verdade, se fôssemos plotar tudo de modo proporcional,
a largura deste gráfico deveria ser equivalente ao dobro da sua altura.
E se fôssemos visualizá-lo exatamente dessa maneira, ele seria ortogonal.
我进行的主成分分析刚好是在
该名为 doPCA 的函数中进行的,
而且它看起来与我们之前在 scikit-learn 中
执行的操作很相似。
您采用了导入语句,
其实您在该语句中就取得了包含您需要的代码的模块。
在该案例中,您创建主成分分析,
进行调整,
然后将其作为对象返回。
我要做的是通过该方法获得我的主成分分析。
而且我可以通过访问其属性提出
一些非常有趣和重要的问题。
我们介绍一下这三条线。
我其实正是借此从 PCA 对象中获取信息。
第一个是已经介绍过的方差比,它其实是特征值的具体表现形式。
通过打印此处的该行内容,
我借此认识到第一个主成分占数据变动的 90%
或 91%,而第二个主成分的占比约为 9%
或 10%。
这些数字都来自该语句。
然后我要做的第二件事是研究第一个和
第二个主成分。
我是从 PCA 对象的成分属性中获得的这些数据,
也就是说成分就是一份列表,
一份 Python 列表,其中包含的主成分与
我通过参数要求的一样多。
因此在该案例中,我获得了两个主成分,
然后将其命名为第一个和第二个 pc。
在之前我们讨论 xy 原始特征空间中
x prime 使用何种方向的小测试中,
我们使用了打包成向量的两个数字。
您可以通过这些成分访问该方向信息。
完成对主成分分析的调整后,
无论出于何种目的,我都必须要执行数据转换这种操作。
我会在小测试的启动代码中向您提供该代码。
我现在的任务是将其可视化。
第一行是红色。
我将标绘出第一个主成分,
该主成分所有点的位置
以及主成分的方向。
我通过使用第一个 PC 向量的元素访问该信息。
然后我会访问蓝绿色或青色的第二个
主成分,并将初始数据标绘成蓝色。
然后我会向您展示上色之后的效果,
然后您可以在小测试中亲自尝试一下。
您要做的第一件事是打印出特征值。
请记住,该值可以解释方差比信息。
然后第二件事是画出散点图,
该图看起来应该是这样的。
请注意,红色代表第一个主成分的方向,
希望您能精确地猜到。
当然直觉上好像位置不错。
青色预制垂直,
而蓝色是初始数据点。
我要补充的是肉眼看起来,红色和青色
并不是绝对垂直,
看起来好像不是 90 度角。
但请记住我们的轴有不同的刻度。
该轴会一直延伸到 1000 万,
y 轴延伸程度不到它的一半,仅为约 400 万。
在现实中,如果我们要均衡地绘图,
那么该图的长度应该是高度的两倍。
如果我们完全按照这种方法将其可视化,那么它们就是垂直的。