IBM Watson has built a model for analyzing personalities. It takes as input texts and it returns some personality insights by applying linguistic analytics and personality theory to infer attributes from a person’s unstructured text. You can play with the personality insights demo of IBM Watson just to get an idea of what analytics it provides. In this tutorial, we will show how you get the Personality Insights from IBM Watson using Python.
Get Personality Insights from IBM Watson in Python.
First, you will need to create an IBM Cloud account to get an API Key. Note that the API calls are not free, however, you can make 1000 calls per month free of charge.
Below we represent the analysis of Oprah’s Twitter account (@Oprah (EN)) that we get from the IBM Personality Insights Demo.
Let’s see how we can analyze a document in Python.
Let’s assume that we want to analyze the following speech which is stored in our local computer as profile.txt:
Vice President Johnson, Mr. Speaker, Mr. Chief Justice, President Eisenhower, Vice President Nixon, President Truman, Reverend Clergy, fellow citizens: We observe today not a victory of party but a celebration of freedom -- symbolizing an end as well as a beginning -- signifying renewal as well as change. For I have sworn before you and Almighty God the same solemn oath our forbears prescribed nearly a century and three-quarters ago. The world is very different now. For man holds in his mortal hands the power to abolish all forms of human poverty and all forms of human life. And yet the same revolutionary beliefs for which our forebears fought are still at issue around the globe -- the belief that the rights of man come not from the generosity of the state but from the hand of God. We dare not forget today that we are the heirs of that first revolution. Let the word go forth from this time and place, to friend and foe alike, that the torch has been passed to a new generation of Americans -- born in this century, tempered by war, disciplined by a hard and bitter peace, proud of our ancient heritage -- and unwilling to witness or permit the slow undoing of those human rights to which this nation has always been committed, and to which we are committed today at home and around the world. Let every nation know, whether it wishes us well or ill, that we shall pay any price, bear any burden, meet any hardship, support any friend, oppose any foe to assure the survival and the success of liberty. This much we pledge -- and more. To those old allies whose cultural and spiritual origins we share, we pledge the loyalty of faithful friends. United there is little we cannot do in a host of cooperative ventures. Divided there is little we can do -- for we dare not meet a powerful challenge at odds and split asunder. To those new states whom we welcome to the ranks of the free, we pledge our word that one form of colonial control shall not have passed away merely to be replaced by a far more iron tyranny. We shall not always expect to find them supporting our view. But we shall always hope to find them strongly supporting their own freedom -- and to remember that, in the past, those who foolishly sought power by riding the back of the tiger ended up inside. To those people in the huts and villages of half the globe struggling to break the bonds of mass misery, we pledge our best efforts to help them help themselves, for whatever period is required -- not because the communists may be doing it, not because we seek their votes, but because it is right. If a free society cannot help the many who are poor, it cannot save the few who are rich. To our sister republics south of our border, we offer a special pledge -- to convert our good words into good deeds -- in a new alliance for progress -- to assist free men and free governments in casting off the chains of poverty. But this peaceful revolution of hope cannot become the prey of hostile powers. Let all our neighbors know that we shall join with them to oppose aggression or subversion anywhere in the Americas. And let every other power know that this Hemisphere intends to remain the master of its own house. To that world assembly of sovereign states, the United Nations, our last best hope in an age where the instruments of war have far outpaced the instruments of peace, we renew our pledge of support -- to prevent it from becoming merely a forum for invective -- to strengthen its shield of the new and the weak -- and to enlarge the area in which its writ may run. Finally, to those nations who would make themselves our adversary, we offer not a pledge but a request: that both sides begin anew the quest for peace, before the dark powers of destruction unleashed by science engulf all humanity in planned or accidental self-destruction. We dare not tempt them with weakness. For only when our arms are sufficient beyond doubt can we be certain beyond doubt that they will never be employed. But neither can two great and powerful groups of nations take comfort from our present course -- both sides overburdened by the cost of modern weapons, both rightly alarmed by the steady spread of the deadly atom, yet both racing to alter that uncertain balance of terror that stays the hand of mankind's final war. So let us begin anew -- remembering on both sides that civility is not a sign of weakness, and sincerity is always subject to proof. Let us never negotiate out of fear. But let us never fear to negotiate. Let both sides explore what problems unite us instead of belaboring those problems which divide us. Let both sides, for the first time, formulate serious and precise proposals for the inspection and control of arms -- and bring the absolute power to destroy other nations under the absolute control of all nations. Let both sides seek to invoke the wonders of science instead of its terrors. Together let us explore the stars, conquer the deserts, eradicate disease, tap the ocean depths and encourage the arts and commerce. Let both sides unite to heed in all corners of the earth the command of Isaiah -- to "undo the heavy burdens ... (and) let the oppressed go free." And if a beachhead of cooperation may push back the jungle of suspicion, let both sides join in creating a new endeavor, not a new balance of power, but a new world of law, where the strong are just and the weak secure and the peace preserved. All this will not be finished in the first one hundred days. Nor will it be finished in the first one thousand days, nor in the life of this Administration, nor even perhaps in our lifetime on this planet. But let us begin. In your hands, my fellow citizens, more than mine, will rest the final success or failure of our course. Since this country was founded, each generation of Americans has been summoned to give testimony to its national loyalty. The graves of young Americans who answered the call to service surround the globe. Now the trumpet summons us again -- not as a call to bear arms, though arms we need -- not as a call to battle, though embattled we are -- but a call to bear the burden of a long twilight struggle, year in and year out, "rejoicing in hope, patient in tribulation" -- a struggle against the common enemies of man: tyranny, poverty, disease and war itself. Can we forge against these enemies a grand and global alliance, North and South, East and West, that can assure a more fruitful life for all mankind? Will you join in that historic effort? In the long history of the world, only a few generations have been granted the role of defending freedom in its hour of maximum danger. I do not shrink from this responsibility -- I welcome it. I do not believe that any of us would exchange places with any other people or any other generation. The energy, the faith, the devotion which we bring to this endeavor will light our country and all who serve it -- and the glow from that fire can truly light the world. And so, my fellow Americans: ask not what your country can do for you -- ask what you can do for your country. My fellow citizens of the world: ask not what America will do for you, but what together we can do for the freedom of man. Finally, whether you are citizens of America or citizens of the world, ask of us here the same high standards of strength and sacrifice which we ask of you. With a good conscience our only sure reward, with history the final judge of our deeds, let us go forth to lead the land we love, asking His blessing and His help, but knowing that here on earth God's work must truly be our own.
from ibm_watson import PersonalityInsightsV3 import pandas as pd import json API_key = "LG6Xlnb8XLToVAz5BmqbXCle85ppxxxxxxxxxxxxx" URL = "https://gateway-lon.watsonplatform.net/personality-insights/api" personality_insights = PersonalityInsightsV3( version='2019-01-01', iam_apikey=API_key, url=URL ) with open('myfile/profile.txt') as profile_json: profile = personality_insights.profile( profile_json.read(), 'application/json', content_type='text/plain;charset=utf-8', consumption_preferences=True, raw_scores=True ).get_result() # print(json.dumps(profile, indent=2)) # personality tuple personality = profile['personality'] personality_tuple = [(i['name'], i['percentile']) for i in personality] # openness tuple openness = personality openness_tuple = [(i['name'], i['percentile']) for i in openness['children']] # conscientiousness tuple conscientiousness = personality conscientiousness_tuple = [(i['name'], i['percentile']) for i in conscientiousness['children']] # extraversion tuple extraversion = personality extraversion_tuple = [(i['name'], i['percentile']) for i in extraversion['children']] # agreeableness tuple agreeableness = personality agreeableness_tuple = [(i['name'], i['percentile']) for i in agreeableness['children']] # emotional_range tuple emotional_range = personality emotional_range_tuple = [(i['name'], i['percentile']) for i in emotional_range['children']] # values tuple values_tuple = [(i['name'], i['percentile']) for i in profile['values']] # needs tuple needs_tuple = [(i['name'], i['percentile']) for i in profile['needs']] All = (personality_tuple+openness_tuple+conscientiousness_tuple+extraversion_tuple+ agreeableness_tuple+emotional_range_tuple+values_tuple+needs_tuple) df = pd.DataFrame(dict(All), index=) df.T
0 Openness 0.997081 Conscientiousness 0.986402 Extraversion 0.085301 Agreeableness 0.187535 Emotional range 0.389882 Adventurousness 0.789745 Artistic interests 0.994658 Emotionality 0.767163 Imagination 0.311677 Intellect 0.996520 Authority-challenging 0.797907 Achievement striving 0.840373 Cautiousness 0.944187 Dutifulness 0.794628 Orderliness 0.761074 Self-discipline 0.712865 Self-efficacy 0.699430 Activity level 0.962402 Assertiveness 0.919861 Cheerfulness 0.229364 Excitement-seeking 0.210242 Outgoing 0.708519 Gregariousness 0.224586 Altruism 0.971330 Cooperation 0.822993 Modesty 0.761319 Uncompromising 0.947148 Sympathy 0.999118 Trust 0.830111 Fiery 0.013938 Prone to worry 0.062026 Melancholy 0.352858 Immoderation 0.011684 Self-consciousness 0.193471 Susceptible to stress 0.069945 Conservation 0.506593 Openness to change 0.628752 Hedonism 0.005254 Self-enhancement 0.001194 Self-transcendence 0.342961 Challenge 0.003255 Closeness 0.370228 Curiosity 0.845180 Excitement 0.115056 Harmony 0.466422 Ideal 0.022634 Liberty 0.108030 Love 0.011895 Practicality 0.018888 Self-expression 0.184898 Stability 0.394623 Structure 0.888013
As we can see, we got 52 attributes related to the personality based on the analysis of the “profile.txt” document.
Applications of the Personality Insights
From an unstructured text document we managed to return a structured data frame of 52 numeric attributes. Clearly, we can utilize the IBM Watson Personality Insights for many NLP and Machine Learning projects.