Expect Lai
INFOR35th Network Management
& ML Introduction
Richard Lai
環境建置、第一支程式
python filename.py
print('Hello World!')
# 這是註解啦
# 上方的程式碼代表輸出Hello World並換行
恭喜你撰寫完 Python 的第一支程式!
我要怎麼像 C++ 一樣輸入呢?
name = input("hi, how may i call you?")
print("Hello, "+name)
# 將輸入的東西存入 name ,印出 Hello, name
# input()中的字串,有點像輸入前顯示的字串
#,沒什麼用
變數與他的快樂夥伴
number = 7122
# 整數
sentence = "Hello world!"
# 字串
float_num = 7.122
# 小數
flag = True
# 布林值 (邏輯)
print(type(sentence))
# 印出變數的型別
當我們寫:
number = 7122
時,
代表我們為 number 賦值7122,存入記憶體中
Python 的變數不需宣告型別,且可重複使用
a = 765 * 432 + 9900
# +-*/分別代表著加、減、乘、除
# //代表除之後,取整數
b = 2022
b += a
# 宣告變數 b = 2022,再把 b 的值加上 a。
print(b>=a)
# 輸出的為b>=a的布林值,
# <、>、<=、==、>=
條件與迴圈
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("我很喜歡重補修,但是...")
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 中的內容 (等等會講)
比較需要提的:
range(n)
: 從0數到n-1range(s,e)
: 從s數到e-1range(s,e,d)
: 從s數到e-1,間隔為d。(若d為負,則倒著數)陣列跟函式
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))
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]
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
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
Machine Learning
真的只是稍微帶到
解決人類找不出規律的問題
語音辨識
影像辨識
數值預測
自駕車
金融分析
機器人、腦波分析等應用於醫療等領域
到底什麼是機器學習?
把以下的 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()
有觀察到哪些東西呢?
print('OwO')
By Expect Lai
INFOR35th 大社課-Python基礎