Python basic

& ML Introduction

Richard Lai

Index

prior knowledge

環境建置、第一支程式

  • 一個直譯式、物件導向的高階語言
  • 簡潔易學、可讀性高
  • 人工智慧、遊戲設計、區塊鏈、大數據

What is it?

  • 速度慢、強制縮排(不打4space縮排會報錯)
  • 很多函式庫可以玩
  • 可攜性&相容性高

Features

Python

  • 下載 Python (安裝時記得勾選 Add Python 3.10 to PATH )
  • 下載 Visual Studio Code
  • 存檔後要如何執行呢? 
  • 在 terminal 中打 python filename.py

環境

Hello world

print('Hello World!')

# 這是註解啦
# 上方的程式碼代表輸出Hello World並換行

恭喜你撰寫完 Python 的第一支程式!

我要怎麼像 C++ 一樣輸入呢?

name = input("hi, how may i call you?")
print("Hello, "+name)
# 將輸入的東西存入 name ,印出 Hello, name
# input()中的字串,有點像輸入前顯示的字串
#,沒什麼用

variable & operator

變數與他的快樂夥伴

  • 變數就是為了方便在程式中調用記憶體中的值,而宣告的名稱
  • 運算子可以四則運算、位元運算、比較,用途相當廣泛

什麼是變數&運算子

變數的宣告

number = 7122
# 整數
sentence = "Hello world!"
# 字串
float_num = 7.122
# 小數
flag = True
# 布林值 (邏輯)
print(type(sentence))
# 印出變數的型別

當我們寫:

number = 7122 時,

代表我們為 number 賦值7122,存入記憶體中

Python 的變數不需宣告型別,且可重複使用

Operator

a = 765 * 432 + 9900
# +-*/分別代表著加、減、乘、除
# //代表除之後,取整數
b = 2022
b += a
# 宣告變數 b = 2022,再把 b 的值加上 a。
print(b>=a)
# 輸出的為b>=a的布林值,
# <、>、<=、==、>=

當我們寫:

b += a 時,

同義於 b = b+a

以此類推。

更多運算子請見 here

condition & loop

條件與迴圈

a = 33
b = 200
if b > a:
  print("b is greater than a")
# 注意縮排!
password = "infor35th7122"
if input("請輸入密碼!") != password:
  print("logged in!")
else:
  print("QQ")
# 注意縮排!
score = 72
if score>=90:
  print("ORZ")
elif score>=60:
  print("pass")
elif score>=40:
  print("非常好補考")
else:
  print("我很喜歡重補修,但是...")

conditions

if statement:

    blablabla

代表statement如果

為真,則執行下方的扣

 

elif等同於c++的else if

若上個if/elif中不成立,

改執行該elif中的扣

 

都不成立

執行else中的內容

for i in range(10):
  print(i)
# 從0數到9,並印出來
n = int(input())
while n>=0:
  n = n-5
  print(n)
# 當n>=0這個statement為True時
# ,會重複執行冒號下的部分
lessons = ["Chinese","English","math",
           "computer","society","science"]
for class in lessons:
  print(class,end=",")
# 遍歷陣列 lessons 中的內容 (等等會講)

loops 迴圈

比較需要提的:

  1. range(n): 從0數到n-1
  2. range(s,e): 從s數到e-1
  3. range(s,e,d): 從s數到e-1,間隔為d。(若d為負,則倒著數)

list & function

陣列跟函式

Array (list)

  • 以一個變數存多個資料。(應該沒有人會在題目有100個資料時,宣告100個變數ㄅ)
  • 可以透過index存取list中的資料。                    註: 程式語言大都為0-base,也就是說陣列中首項index為0
  • 以[]包起資訊,不同項以 , 隔開,一個list可存不同型別。
  • Python的list其實跟C++的vector有點像
cars = ["Ford", "Volvo", "BMW"]
fruit = ["Apple","Orange",7122,
         True,"Watemelon","etc"]
# 宣告方式

print(cars[2])
# 印出BMW

print(fruit[6])
# 出錯了,並沒有第6項

若我們想擷取特定的片段?
==> arrayname[起始項:最終項:間隔]

# EX
print(arrayname[4:0:-1])

# 陣列長度
print(len(cars))

list的很多操作

a = [99,1,2,3,4,5,6,7,8]
for i in a:
  print(i)
a.append(7122)
# 從後方加入7122,
# [99,1,2,3,4,5,6,7,8,7122]
a.pop(1)
# 移除a[1]
# [99,2,3,4,5,6,7,8,7122]
a.remove(5)
# 移除a[5]
# [99,2,3,4,5,7,8,7122]
a.sort()
# 排序該list
# [2,3,4,5,7,8,99,7122]

真的很多

here

Python的list是不定長度的

Function

def hello():
  print("Hello INFOR!")

hello()
#呼叫一個函式

def add_three(a,b,c):
  return a+b+c
# 括號中的a,b,c叫做參數,可以傳入函式中進行許多事情
print(add_three(12,15,34))
# a=12,b=15,c=34傳入add_three中,回傳a+b+c

對於函式,可以指派他們參數,也可以把他們當作引數傳給其他函式,以及回傳值。運用函式,

我們可以節省不少時間

更多用法

Function 的種種

def sumNumber(*params):
    total = 0
    for param in params:
        total +=param
    return total
# 不定數目參數

def rightFunction(first, second = 12):
    return first
def wrongFunction(first=12, second):  
# 出錯 non-default argument follows default argument
    return first
# 函示也可以宣告預設值

除此之外, Python也有許多內建函式

如: pow(a,b)、round()、sum

ML?

Machine Learning

真的只是稍微帶到

機器學習能幹嘛

複雜的事情

解決人類找不出規律的問題

應用

  1. 語音辨識

  2. 影像辨識

  3. 數值預測

  4. 自駕車

  5. 金融分析

未來性

機器人、腦波分析等應用於醫療等領域

什麼是AI?無處不在的科技

  • 能推理
  • 能解決問題
  • 具有知覺
  • 有自我意識的
  • 不真正擁有智慧

強人工智慧

  • 不真正擁有智慧
    不會有自主意識

弱人工智慧

到底什麼是機器學習?

  • 實現人工智慧的方法之一
  • 會用到概率論、統計學、逼近論、凸分析、計算複雜性理論
  • 學習:從已知資料分析獲得規律

把以下的 code 複製到google colab中執行

玩耍

# generating training and testing data
import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation
import numpy as np
import random as rd
import matplotlib.pyplot as plt

d=2
n=1000
test_n=100
x_train=[]
y_train=[]
x_test=[]
y_test=[]
mua=[-2,2]
mub=[2,-2]
sigma=[[5,0],[0,5]]
for i in range(n):
    if rd.randint(0,1)==0:
        x_train.append(np.random.multivariate_normal(mua,sigma))
        y_train.append([1,0])
    else:
        x_train.append(np.random.multivariate_normal(mub,sigma))
        y_train.append([0,1])
for i in range(test_n):
    if rd.randint(0,1)==0:
        x_test.append(np.random.multivariate_normal(mua,sigma))
        y_test.append([1,0])
    else:
        x_test.append(np.random.multivariate_normal(mub,sigma))
        y_test.append([0,1])
x_train=np.array(x_train)
y_train=np.array(y_train)
x_test=np.array(x_test)
y_test=np.array(y_test)

for i in range(n):
    if y_train[i][0]==0:
        plt.scatter(x_train[i][0],x_train[i][1],c="red",marker=".")
    else:
        plt.scatter(x_train[i][0],x_train[i][1],c="blue",marker=".")
plt.show()
# training

import keras
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation

model = Sequential()
model.add(Dense(100, input_dim=d, activation='sigmoid'))
model.add(Dense(100, input_dim=d, activation='sigmoid'))
model.add(Dense(100, input_dim=d, activation='sigmoid'))
model.add(Dense(100, input_dim=d, activation='sigmoid'))
model.add(Dense(100, input_dim=d, activation='sigmoid'))
model.add(Dense(2,activation='softmax'))
model.compile(loss='categorical_crossentropy',
              optimizer='adam',
              metrics=['accuracy'])
model.summary()
history=model.fit(x_train, y_train, epochs=50, batch_size=128, validation_split=0.2)
score = model.evaluate(x_test, y_test, batch_size=128)
print(f"score: {score}")

# Plot training & validation accuracy values
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.title('Model accuracy')
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper right')
plt.show()

# Plot training & validation loss values
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('Model loss')
plt.ylabel('Loss')
plt.xlabel('Epoch')
plt.legend(['Train', 'Test'], loc='upper right')
plt.show()

有觀察到哪些東西呢?

the end

print('OwO')

Thanks for your listening.

Resources: w3schoolsnakify李弘毅課程

Made with Slides.com