Machine Learning - Python 02

Well, we followed the contents of one, continue to learn Python syntax part of the machine learning. This section be the last one of the Python syntax. That if you really understand the contents of the two sections, in theory or on the direction of the field of machine learning, language is not a problem. It also means that once the real into the core part of the machine learning. Well, then we started our next study it.

  • Tuples

Tuples is a new form of data collection Python in (at least with respect to C ++, objective-C, Java is new. I'm not sure about the other, and avoid being hit face, ha ha). In fact, she and List almost the same, except that two different aspects. The main difference between her and list two different aspects of the following: 1) demonstrate Tuples element created is about the element wrapped in parentheses, brackets and List is used. 2) Tuples once created the elements can not be changed, that it is immutable, and List elements can be changed, that is, the Mutable. Well, here's a look at the tuples show how to create the code, otherwise the lip off skill. Ha ha ha

t = (1,2,3)

The above code is to create a tuple, he has three elements, namely 1,2,3. So why should we now have a list Tuples it? This is mainly because Tuple application scenario is mainly used for those functions that have multiple return values, imagine if a function has multiple return values, how would you get it? Yes, you certainly think of List, right? However List data inside probably because when people co-developed by other colleagues changed, there will be certain of Risk. So naturally we thought of Tuples use this data structure, because he is Immutable, if someone tries to modify her values, he will complain. List summed up is readable and writable, and Tuples are read-only. Consider the following return multiple values ​​you an example.

a = 0.125.as_integer_ratio()

The above function returns two values, the numerator and denominator, respectively, are integer data. The returned data is (1,8).

There is a point on Tuples Individual assignments (translation should be called the assignment alone, do not know the translation wrong, let me put on a B, ha ha ha), meaning here is the value of speaking Tuple can be assigned to different respectively variables, as follows:

numerator,demonstrater = a

The above code is run results: numerator = 1, demonstrater = 8.

  • Dictionary

Well, now accept the final form of the collection, it is the dictionary. This is very much like other languages, is the key-value pairs. Well, take a look below to create our first dictionary of

numbers = {"one":1,"two":2,"three":3}

This and a variety of other languages ​​are the same, let's look at how to retrieve value by Key value.

numbers["one"]

Here are some of the more advanced dictionary but in practice frequently used functions, the syntax looks very fast hardware characteristics, in fact, are paper tigers, ha ha, the attitude we should despise his mother, the operation should pay attention to them Kazakhstan .

1) in operator

in Python keyword is the most common one keyword, not one! ! ! ! Used in the list, using the dictionary, it will be used when the condition determination, in the loop will still use. Since this section talking about the dictionary, we'll look at her application in the dictionary in it.

#create a dictionary
planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
plants_to_initial = {planet:planet[0] for planet in planets}
"Mercury" in plants_to_initial  # the in operator will tell us whether something is a key in the dictionary

The above code is now create a dictionary can not read does not matter, she is to create a dictionary that the key value is the name of the stars, value is the value of the first letter of these stars. What is important here is the last line of code to determine "Mercury" This string is not the dictionary key value. If this is key, returns True, otherwise False.

2) traversal key value

#the for loop will loop over its keys
for key in plants_to_initial:
    print(key,end = " ")

As shown in the code directly to the dictionary traversal, returns the key value for each key-key-value pairs. The above code is the key to print all of the value of this dictionary.

3) colleagues traverse key-value key-value pairs

In the dictionary, if you want to traverse the key-value pairs at the same time, we must pass a method dictionary, called:.. Items () This method returns a list, which elements are tuples, tuples which these elements is key, values ​​words Not much to say, look directly on the code

for planet, initial in plants_to_initial.items():#items()will return its key-value pairs
    print(planet,initial)
  • String

Well, finally into the most commonly used basic data types of -string. Almost in the application used, the production and consumption data, nearly a string accounted for the majority. Of course, the data type most commonly used in machine learning is int and float, but the type of string is often occur. String fact, it can be seen as a string of characters, this string of characters is like a list. English speaking is A string is a sequences of characters. (Is not big moment on, from the garlic into a coffee. Ha ha ha ha). So in Python, you hardly see in the list of methods, are equally applicable to String. 

1) String creation and index

planet = "Pluto"
planet[0]#return P
planet[-3:]#return uto
len(planet)#return 5

2) conventional methods String

#string methods
planet.upper()#return PLUTO
planet.lower()#return pluto
planet.index("uto")#return 2
planet.startswith("Plu")#return True
planet.endswith("asds")#return False

3) conversion between List and String

#going between strings and lists
#string -> list   split method
planets = "Pluto is a planet"
list_planets = planets.split()#return a list of ["Pluto","is","a","planet"]
dates = '2019-10-08'
list_dates = dates.split('-')#returns ["2019","10","08"], the element are also all string types
#list->string  join method
year,month,day = list_dates #individual assignment
'/'.join([year,month,day]) #returns "2019/10/08"

Note whether it is String-> List or List-> String, their basic elements are String, and will not be Int or Float or something strange data types. In other words, both the Split or Join, the object of their operation is String. For example:. '/' Join ([1,2,3]), this code will be given, as data instead are integers 1,2,3 string. Here abstract Kazakhstan, gradually began to feel their own.

4)formatting a string

String is a very flexible data types, such as int can also be converted into a string, and the like. Therefore, we often need different data types spliced ​​together, and then converted into a string. In this case, we often need to use the format method, of course, there are other ways to accomplish this task, but regressed place lies not only in this format, she can also format data representation format, such as reserving a few decimal points , large numbers of forms and the like, may refer to the specific code below.

position = 9
"{}, you will be the {}th planet to me".format(planet,position) #returns 'Pluto, you will be the 9th planet to me'
"{:.2}".format(0.123345) #returns "0.12", the result is converted to string type
"{:,}".format(1234578) #returns '1,234,578' the result is also converted to string type
"{0},{1},{1},{0},{0}".format(12,55)#indexing of format the result is '12,55,55,12,12', the result is also string type
  • Loop comprehension

Loop comprehension in Python is a very popular feature, she was able to quickly create List and dictionary, and very flexible, practical machine learning in the future you will find very easy to use. Having said that, then the next we take a look in the end what is the Loop Comprehension.

1) using the Loop Comprehension to quickly create dictionary.

In fact, this has been reflected in the preceding code, and as shown in the code below, to quickly create a dictionary.

plants_to_initial = {planet:planet[0] for planet in planets}

In fact, use for in the loop, then through the key: in the form of value, generating the bulk of key-value pairs, and finally generate a dictionary.

2) using the Loop Comprehension to create List

List of creation is very flexible and can also operate elements of the cycle, to achieve some of the objectives of some individualized or special needs. She can also be reached even finer control by a combination of the conditional statement, some common ways to create List is shown below

numbers = [1,2,3,4]
squares = [n**2 for n in numbers] #returns [1,4,9,16]
print(squares)    
short_squares = [n for n in squares if n<9] #returns [1,4]
count_number_of_squares = len([n for n in squares if n < 100]) #returns 4

 

Summary: in front of a largely content as well as this section has been introduced most of the characteristics common Python, if already know, I think just learn in this field for the machine, it has been good enough. The contents of these sections is to those who already have experience in other languages ​​ready (if not a little computer language experience, I suggest starting with Hello World)

Guess you like

Origin www.cnblogs.com/tangxiaobo199181/p/12113244.html