6. Python 數據分析技巧
章節內容
-
Python Class & Object
-
Class Inheritance
• Overriding Inheritance
- Super() method
• Composition and Component
-
Module and Package
-
Splitting Module
-
Files
-
Exceptions
-
Generator
• Mini Project – Sentiment Analysis
• Time Series Analysis
-
Data
-
Patterns Recognition
-
Autocorrelation
-
ARIMA
-
Rolling Statistics
Object-oriented programming 物件化程式設計
物件化程式設計(OOP)是一種計算機程式設計模型,它圍繞數據或物件而不是函數和邏輯來組織軟體設計。
在 OOP 概念出現之前,過程程式設計概念被用於早期的程式中,它有許多缺點,但被面向物件程式設計方法所克服。
流行的 OOP 語言:Python,C,Java,PHP,JavaScript,.NET ...
Python Class
Python 是完全面向物件的:您可以定義自己的類,從自己的或內置的類繼承,並實例化您定義的類。Python 類以保留字類開頭,後跟類名。課程名稱必須以大寫字母開頭,作為行業 PEP 指南。
class Staff:
pass
Define a most simple class
init()方法
每個類方法(包括 init()方法)的第一個參數始終是對該類的當前實例的引用。實例是指物件的特定實現。此.init()初始化類的每個新實例,並在每次類創建新物件時調用。
class Staff:
initialize instance variable
def init(self, name, id):
self.name = name
self.id = id
使用 name、id 啟動員工。
自我是必備元素。
Class Method
現在,我們創建了一種處理 Staff 的方法。方法只是類中的一個函數,並且專門針對此類。
class Staff:
# initialize instance attribute
def __init__(self, name, id):
self.name = name
self.id = id
# Instance method
def verify(self):
return f"{self.name} ID: {self.id}"
創建名為 sales_manager by Staff 的實例,如下所示。
此外,我們驗證了此類 sales_manager。
<h3 id="h-163-Create-a-sales-manager-object">Create a sales manager object</h3>
sales_manager = Staff("Alice", 'E12345')
<h3 id="h-163-Verify-the-sales-manager">Verify the sales manager</h3>
print(sales_manager.verify())
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
Alice ID: E12345
編譯代碼,您將看到以下內容:
Alice ID: E12345
Class and Method
您也可以在 Jupyter Notebook 中編寫代碼,並逐塊運行代碼。 嘗試使用屬性和方法調用實例。
In [1]: class Staff:
# initialize instance variable
def __init__(self, name, id):
self.name = name
self.id = id
# Instance method
def verify(self):
return f"{self.name} ID: {self.id}"
In [2]: sales_manager = Staff('Alice', 'E11234')
In [3]: sales_manager.name
Out[3]: 'Alice'
In [4]: sales_manager.id
Out[4]: 'E11234'
In [5]: sales_manager.verify()
Out[5]: 'Alice ID: E11234'
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
'Alice ID: E11234'
試試這個代碼:print(type(sales_manager))
更新屬性 & 刪除實例 Update
In [7]: sales_manager
Out[7]: <main__Staff at 0x112a
In [8]: sales_manager.id = 'A2468'
In [9]: sales_manager.id
Out[9]: 'A2468'
In [10]: del sales_manager
In [11]: sales_manager
NameError
Input In [11], in <cell>
----> 1 sales_manager
NameError: name 'sales_m
注意:出於節省記憶體的目的,有時
通過方法更新屬性 Update at
| 1 | cla | |
| 除了訪問屬性進行 | 2 | |
| 更新外,我們還可以使用一種方法來更新。 | 3 | |
| 讓我們建立另一個名為 update_name | 4 | |
| ()的函數 | 5 | |
| 6 | ||
| 7 | ||
| 8 | ||
| 9 | ||
| 10 | ||
| 11 | ||
| 12 |
現在我們可以像這樣更新名稱實例
sales m print(s
Alice C
attribute & delete instance
ager' is not defined
我們需要使用 del 或 gc(垃圾回收器)删除類。
attribute through a Method
s Staff:
<h3 id="h-165-initialize-instance-attribute">initialize instance attribute</h3>
def __init__(self, name, id):
self.name = name
self.id = id
<h3 id="h-165-Instance-method">Instance method</h3>
def verify(self):
return f"{self.name} ID: {self.id}"
def update_name(self, name):
self.name = name
manager.update_name('Alice Chan')
ales_manager.verify())
han ID: E11234
⚠️ 本頁有 2 段未能本地執行(#1: SyntaxError: unterminated string literal (detected at line 11) (<unkno; #2: SyntaxError: unmatched ')' (
, line 15)),原因見 OCR_run_report.md
Class inheritance
Python 支援類繼承的概念。
繼承允許我們從現有類創建一個新類。
新創建的類稱為子類(子類或派生類),從中派生子類的現有類稱為超類(父類或基類)。
We are going to create 2 classes
Staff
superclass
SalesStaff
subclass
UML Unified Modelling Language
讓我們像系統分析員一樣思考並創建一個UML。
超級員工
包含一個能夠識別員工的方法 verify()
子類 SalesStaff
包含用於 display()註冊銷售人員姓名的方法
| Staff |
| + name: string |
| + verify(): string |
| SalesStaff |
| + name: string |
| + display(name): string |
有關 UML 標準和繪圖技術的更多內容,請訪問
https://drawio-app.com/blog/uml-class-diagrams-in-draw-io/
雖然這超出了我們的教學大綱,但對於程式師和開發人員來說非常重要。
draw.io
Inheritance
When a child class has the same operations and attributes as its parent class, but adds some of its own extras, that's inheritance. Inheritance is a core feature of object oriented programming. You can indicate this in your diagram by drawing an unfilled arrow from the child class to the parent class.
Class inheritance
基於我們在UML中設計的內容,我們在這裡編碼。
請注意,在第6行中,如何定義子類繼承超類!
class Staff:
name = ""
def verify(self):
print(f"Registered staff")
class SalesStaff(Staff):
def display(self):
print("Sales staff name:", self.name)
現在我們可以享受子類及其超類的方法
<h3 id="h-168-create-an-object-of-the-subclass">create an object of the subclass</h3>
sales_1 = SalesStaff()
<h3 id="h-168-access-superclass-attribute-and-method">access superclass attribute and method</h3>
sales_1.name = "Gary Wong"
sales_1 是一個子類物件
1 sales_1
<main__SalesStaff at 0x11086b040>
通過子類物件調用超類方法
<h1 id="h-168-call-subclass-method">call subclass method</h1>
sales_1.display()
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
Sales staff name: Gary Wong
Sales staff name: Gary Wong
<h1 id="h-168-call-superclass-method">call superclass method</h1>
sales_1.verify()
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
Registered staff
Registered staff
如果超類和子類中都存在相同的方法怎麼辦?
在這種情況下,子類中的方法將覆蓋超類中的方法。這個概念在 Python 中被稱為方法覆蓋。
這種機制是合乎邏輯的,因為它方便了子類的活動。或者你可以想像如果它是超類覆蓋呢?對於子類來說,這可能是一場噩夢。
無論如何,我們應該避免定義具有相同名稱的函數和內置的 Python 命名空間。
Method overriding in Inheritance
Superclass Staff 和
子類 SalesStaff 都
有 display()。
當物件調用 display
() 時,它會運行
子類 1 並覆蓋超
類。
class Staff:
name = ""
def display(self):
print(f"Registered staff")
class SalesStaff(Staff):
def display(self):
print("Sales staff name:", self.name)
<h2 id="h-169-create-an-object-of-the-subclass">create an object of the subclass</h2>
sales_1 = SalesStaff()
<h3 id="h-169-access-superclass-attribute-and-method">access superclass attribute and method</h3>
sales_1.name = "Gary Wong"
<h3 id="h-169-subclass-method-overriding">subclass method overriding</h3>
sales_1.display()
Sales staff name: Gary Wong
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
Sales staff name: Gary Wong
super()方法
如果我們需要從子類訪問超類方法,我們使用 super()方法。
Super()傳回代理物件,該物件將方法調用委託給父類或同級類。這對於訪問已在類中重寫的繼承方法非常有用。
如果我們需要放棄子類覆蓋,我們可以在子類函數前面加上 super()。
然後 Python 將 定向到超類 display()。
class Staff:
name = ""
def display(self):
print(f"Registered staff")
class SalesStaff(Staff):
def display(self):
super().display()
sales_1 = SalesStaff()
sales_1.name = "Gary Wong"
sales_1.display()
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
Registered staff
Registered staff
多重繼承 Multiple Inheritance
Python 還支援多重繼承的形式。具有多個超類的子類定義如下所示:
class Parent1: ... class Parent2: ... class Parent3: ... class Child(Parent1, Parent2, Parent3): ...
組成 Composition
組合是一個概念,它類比了具有關係。它允許通過組合其他類型的對象來創建複雜類型。這意味著一個類 Composite 可以包含另一個類 Component 的物件。這種關係意味著複合體具有元件。
表示 Employee 和 Address 之間關係的 Composition UML 圖如下所示:
通過 composition,我們實際上說明瞭這兩個類之間的關係。這樣,代碼可以重複使用。這與繼承的概念有共同的相似之處。因此,我們通過組合不同類型的對象來獲得更複雜的結構。
複合材料和元件 Composite and Component
class Employee:
def __init__(self, name, address):
self.name = name
print('Composite - Employee object created...')
self.address = Address(address)
def emp_info(self):
print(f'Employee name: {self.name}')
print('Composite - emp_info() method executed...')
self.address.print_add()
class Address:
def __init__(self, address):
self.addr = address
print('Component - Address object also created...')
def print_add(self):
print(f'Employee address: {self.addr}')
print('Component - Address print_add() method also executed...')
按類 Employee 建立 staff 物件
1 staff_01 = Employee("John Lee", "28 Mody Road, Tsim Sha Tsui, Kowloon")
Composite - Employee object created...
Component - Address object also created...
1 staff_01.emp_info()
Employee name: John Lee
Composite - emp_info() method executed...
Employee address: 28 Mody Road, Tsim Sha Tsui, Kowloon
Component - Address print_add() method also executed...
1 staff_01
<__main__.Employee at 0x11203d220>
⚠️ 本頁有 1 段未能本地執行(#2: SyntaxError: invalid syntax (
, line 2)),原因見 OCR_run_report.md
模組和封裝 Modules and Packages
模組和包是任何大型專案的核心,也是 Python 安裝本身的核心。
讓我們來瞭解一些涉及模組和包的常見程式設計技術,例如如何:
-
組織包,
-
將大型模組拆分為多個檔,以及
-
創建命名空間包
模組的分層包 Hierarchical Package of Modules
製作包結構很簡單。只需在檔案系統上按照需要組織代碼,並確保每個目錄都定義一個__init__.py 檔案。
graphics/ init.py primitive/ init.py line.py fill.py text.py formats/ init.py png.py jpg.py
完成此操作后,您應該能夠執行各種導入語句,例如:
import graphics.primitive.line
from graphics.primitive import line
import graphics.formats.jpg as jpg
init.py 檔的目的是包含可選的初始化代碼,這些代碼在遇到不同級別的包時運行。例如,如果具有語句 import graphics,則將導入檔 graphics/init_.py 並構成 graphics 命名空間的內容。對於匯入,例如匯入
graphics.formats.jpg,檔 graphics/init.py 和 graphics/formats/init.py 都將在最終導入 graphics/format/jpg.py 檔案之前導入。
更多時候,將__init__.py 檔留空是可以的。但是,在某些情況下,它們可能包含代碼。例如,可以使用__init__.py 檔案自動載入子模組,如下所示:
graphics/formats/__init__.py graphics/
__init__.py
from . import jpg primitive/ init.py from . import png line.py fill.py text.py formats/ init.py png.py jpg.py
將模組拆分為多個檔 Splitting a module into multiple files
您有一個要拆分為多個文件的模組。但是,您希望透過保留單獨的檔案在不破壞現有代碼的情況下執行此操作。
通過將程式模組轉換為包,可以將其拆分為單獨的檔。請考慮以下簡單模組:
mymodule.py
class A:
def spam(self):
print('A.spam')
class B(A):
def bar(self):
print('B.bar')
mymodule/ init.py a.py b.py
In the a.py file, put this code:
In the b.py file, put this code:
<h3 id="h-174-a-py">a.py</h3>
class A:
def spam(self):
print('A.spam')
<h3 id="h-174-b-py">b.py</h3>
from .a import A
class B(A):
def bar(self):
print('B.bar')
Finally, in the init.py file, glue the two files together:
<h3 id="h-174-init-py">__init__.py</h3>
from .a import A
from .b import B
產生的 mymodule 包將顯示為單個邏輯模組,並且可以匯入到其他位置。
>>> import mymodule
>>> a = mymodule.A()
>>> a.span()
A.span
>>> b = mymodule.B()
>>> b.bar()
B.bar
⚠️ 本頁有 2 段未能本地執行(#4: ImportError: attempted relative import with no known parent package; #6: SyntaxError: invalid syntax (
, line 1)),原因見 OCR_run_report.md
將模組作為腳本執行 Execute modules as scripts
當您在命令列中運行 Python 模組時
python fibo.py <arguments>
模組中的代碼將被執行,就像您導入它一樣,但 設置為“ ”。這意味著,通過在模組末尾添加以下代碼:
if __name__ == "__main__":
import sys
fib(int(sys.argv[1]))
您可以使檔既可用作腳本,也可以用作可導入模組,因為解析命令行的代碼僅在模組作為“主”檔執行時運行。
If the module is imported, the code is not run:
>>> import fibo
>>>
這通常用於為模組提供方便的使用者介面,或用於測試目的(將模組作為腳本運行,以執行測試套件)。
⚠️ 本頁有 1 段未能本地執行(#2: NameError: name 'fib' is not defined),原因見 OCR_run_report.md
封装内参考 Intra-package Reference
當包被結構化為子包時(如示例中的聲音包),您可以使用絕對導入來引用同級包的子模組。
sound/
__init__.py
formats/
__init__.py
wavread.py
wavwrite.py
aiffread.py
aiffwrite.py
auread.py
auwrite.py
...
effects/
__init__.py
echo.py
surround.py
reverse.py
...
filters/
__init__.py
equalizer.py
vocoder.py
karaoke.py
...
from . import echo
from .. import formats
from ..filters import equalizer
例如,如果模組 sound.filters.vocoder
需要使用 sound.effects 包中的 echo 模组
目錄()
内置函数 dir()用於找出模組定義的名稱。它傳回一個排序的字串清單:
1 dir()
['Address',
'Child',
'Employee',
'In',
'Out',
'Parent1',
'Parent2',
'Parent3',
'SalesStaff',
'Staff',
⚠️ 本頁有 1 段未能本地執行(#3: SyntaxError: '[' was never closed (
, line 2)),原因見 OCR_run_report.md
檔案處理 File Handling
使用 Python 讀取和寫入文件的數據非常簡單。例如,我們打開一個名為 news.txt 的文本檔,然後將其列印出來。
In [1]: with open('news.txt', 'r') as news:
data = news.read()
In [2]: print(data)
Walmart Chips Away at Amazon's Lead in a Key Area: BySpencer Soper and Brendan Case
9 March 2023 at 23:00 GMT+8
Walmart Inc.'s online subscription service is narr hoppers.
Launched in 2020 as a competitor to Amazon Prime, off inflation. At $98 a year, Walmart+ costs $41 l
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
87032 -0.37562084 -1.42192455 -1.7811513 -0.74790579
-0.36840953 -2.24911813 -1.69367504 0.30364847 -0.40899234 -0.75483059
-0.40751917 -0.81262476 0.92751621 1.63995407 2.07361553 0.70979786
0.74715259 1.46309548 1.73844881 1.46520488 1.21228341 -0.6346525
-1.5996985 0.87715281 -0.09383245 -0.05567103 -0.88942073 -1.30095145
1.40216662 0.46510099 -1.06503262 0.39042061 0.30560017 0.52184949
2.23327081 -0.0347021 -1.27962318 0.03654264 -0.64635659 0.54856784
0.21054246 0.34650175 -0.56705117 0.41367881 -0.51025606 0.51725935
-0.30100513 -1.11840643 0.49852362
…(已截斷)
如果您在雲端伺服器、遠端伺服器上編寫代碼,或者檔與 python 代碼不在同一個資料夾中,則需要指定文件路徑。
file_path = '/home/myPythonCode/news.txt'
with open(file_path, 'r') as news:
data = news.read()
參數'r'告訴 Python 我們要在讀取模式下打開檔。
注意:根據您的操作系統,在 Linux 和 Mac 中,路由斜杠可能是“/”,在 Windows 中可能是“\”。
⚠️ 本頁有 2 段未能本地執行(#1: IndentationError: expected an indented block after 'with' statement on; #3: IndentationError: expected an indented block after 'with' statement on),原因見 OCR_run_report.md
要將文字寫入檔,您需要調用 open( )並帶有第二個參數告訴 Python 您要寫入檔案。要瞭解其工作原理,讓我們編寫一條簡單的消息並將其存儲在檔中。
參數'w'告訴 Python,我們要在寫入模式下打開檔。
filename = 'myfile.txt'
with open(filename, 'w') as file_object:
file_object.write("I love Python.")
jupyter myfile.txt ✓ 11 minutes ago
File Edit View Language
I love Python.
異常和異常處理 Exception and Exception Handling
Python 使用稱為異常的特殊物件來管理程式執行期間出現的錯誤。每當發生錯誤使Python 不確定下一步該做什麼時,它都會創建一個異常物件。
print(1/0)
ZeroDivisionError Traceback (most recent call last)
Input In [20], in <cell line: 1>()
----> 1 print(170)
ZeroDivisionError: division by zero
這些異常確實有助於我們進行調試。但是,我們希望程式繼續運行,以便進行其他重要過程並防止崩潰。然後 try-except 可以提供說明。
try:
print (1/0)
except Exception as e:
print("Error Warning: ", e)
print("I still love Python!")
Error Warning: division by zero
I still love Python!
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
Error Warning: division by zero
I still love Python!
您還可以為不同類型的異常錯誤編寫代碼。
filename = "t.txt"
try:
with open(filename, encoding='utf-8') as f:
contents = f.read()
except FileNotFoundError:
print(f"Sorry, the file {filename} does not exist.")
Sorry, the file t.txt does not exist.
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
Sorry, the file t.txt does not exist.
注意:記錄此類異常是一種很好的做法,在實際場景中,此異常警告應單獨發送到開發人員的錯誤日誌中以供進一步調試。
完整的例外清單可以在 上找到
⚠️ 本頁有 1 段未能本地執行(#1: ZeroDivisionError: division by zero),原因見 OCR_run_report.md
生成器 Generator
生成器 允許你聲明一個行為類似於反覆運算器的函數,即它可以在 for 迴圈中使用。生成器的產出就像回傳值一樣。唯一的區別是,yield 不是回傳值,而是將生成器物件回傳給調用方。
生成器提供了一種有效的方式來反覆運算 大型數據集或動態生成值,而無需將整個序列存儲在記憶體中。
Yield vs Return
yield
創建產生器函數
您將不得不增加收益
關鍵詞。
def yield_hello():
yield "Hello"
3
yield_hello()
返回
def return_hello():
return "Hello"
3
return_hello()
'Hello'
Yield 產出:
- yield
語句用於創建一個生成器函數,該函數可以在執行過程中暫停和恢復,從而允許它隨時間推移生成一系列值。
- 當生成器函數遇到 yield
語句時,它會暫時暫停其執行,並將指定的值提供給調用方。函數的狀態將被保存,允許它在再次調用時從中斷的位置恢復。
-
每次調用生成器函數時,它都會從之前生成的點恢復執行,並一直持續到下一個 yield 語句或函數結束。
-
生成器函數生成的值可以使用 for 循環或通過在產生器物件上顯式調用 next()函數來反覆運算。
Return 回送:
-
return 語句用於指定函數在調用時應返回的結果或值。
-
當函數中遇到 return
語句時,它會立即終止函數執行,並將指定的值(如果有)返回給調用方。
- 執行 return 語句后,函數將完全完成,並且不會執行函數中的任何其他代碼。
⚠️ 本頁有 2 段未能本地執行(#1: IndentationError: expected an indented block after function definition; #2: IndentationError: expected an indented block after function definition),原因見 OCR_run_report.md
Yield 產生一些東西
既然發電機的產量只是「產量」的東西,我們如何從它的產量中讀取呢?
| 使用list() | 1 Y = list(yield_hello())2 print(Y)['Hello'] |
| 使用for迴圈 | 1 for i in yield_hello():2 print(i)Hello |
| 使用以上兩種方法 | 1 Z = list(i for i in yield_hello())2 Z['Hello'] |
Generator 生成器
斐波那契數列生成器
在數學中,斐波那契數列是一個序列,其中每個數位都是前兩個數字的總和。斐波那契數列中的單個數字稱為斐波那契數。讓我們編寫產生器來生成這些數位。
def genFibonacci(max_num):
a, b = 0, 1
count = 0
while count < max_num:
yield a
c = a + b
a = b
b = c
count += 1
fib = list(i for i in genFibonacci(20))
print(fib)
▶ 本地執行結果(Python 3.12 / matplotlib 3.11)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181]
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597, 2584, 4181]
挑戰:你能編寫一個質數產生器嗎?
迷你專案 - 媒體情緒分析
-
如何分析新聞、評論、社交媒體的情緒?如何簡單地知道它是積極的還是消極的?
-
內容的可讀性如何?
-
如何按數位縮放以上內容?
Sentiment Analysis
專案要求:
- 新聞情緒分析
目標輸出:
-
句子和字數計數
-
可讀性比(0-100)
-
情緒比率(0-100)
分析方法 - 可讀性
牛津簡明英語指南,GOV.UK 和語言學家一致認為:
• 15 個單詞的句子更容易理解
• 25 個字是一個很好的最大句子長度限制
• 40 字以上的句子很難理解
- https://readabilityguidelines.co.uk/
分析方法 - 情緒
-
計算內容中的正面詞語和負面詞語。
-
計算閱讀時間(每分鐘 250 個單詞)
-
制定一個總體比率來表示內容的情緒
程式思維導圖 / 流程
-
載入內容
-
計算句子和單詞
-
計算句子中的平均單詞數和閱讀時間
-
載入積極詞數據集
-
載入否定詞數據集
-
計算內容中的正面和負面單詞總數
-
計算所有比率
-
輸出分析摘要
導入庫
-
自然語言處理(NLP)是一個專注於使自然人類語言可供計算機程式使用的領域。NLTK,即自然語言工具包,是一個可用於 NLP 的 Python 包。
-
自然語言工具包
安裝 nltk
pip install nltk
文件:https://www.nltk.org/
通過載入新聞文本啟動程式。
計算基本統計,總句子、總單詞,句子中的平均單詞。
import nltk
from nltk.tokenize import sent_tokenize, word_tokenize
import math
<h3 id="h-186-Load-the-text-file">Load the text file</h3>
filename = "news.txt"
try:
with open(filename, encoding='utf-8') as f:
contents = f.read()
except FileNotFoundException:
print(f"Sorry, the file {filename} does not exist.")
except Exception as e:
print(f"Error: {e}")
<h3 id="h-186-Sentences-and-words-analysis">Sentences and words analysis</h3>
sentences = nltk.sent_tokenize(contents)
words = nltk.word_tokenize(contents)
num_words = len(words)
num_sentences = len(sentences)
word_per_sen = round((num_words / num_sentences), 2)
read_minute = math.ceil(num_words/250)
⚠️ 本頁有 1 段未能本地執行(#1: **********************************************************************),原因見 OCR_run_report.md
載入正面和負面詞數據集。掃描所有單詞並記錄 pos 或 neg 單詞。
<h2 id="h-187-Sentiment-analysis">Sentiment analysis</h2>
<h3 id="h-187-Load-positive-words-bank">Load positive words bank</h3>
pos_words = open("positive-words.txt", 'r', encoding="ISO-8859-1").read().split()
<h3 id="h-187-Load-negative-words-bank">Load negative words bank</h3>
neg_words = open("negative-words.txt", 'r', encoding="ISO-8859-1").read().split()
num_pos, num_neg = 0, 0
pos_list, neg_list = [], []
for w in words:
if w in pos_words:
pos_list.append(w)
num_pos += 1
if w in neg_words:
neg_list.append(w)
num_neg += 1
計算正負的總數和總比,定義內容。基於可讀性指南,定義內容可讀性。
<h3 id="h-187-sentiment-ratio-round-num-pos-num-pos-nu">sentiment_ratio = round((num_pos / (num_pos + num_neg)), 2)</h3>
<h3 id="h-187-if-sentiment-ratio-0-5">if sentiment_ratio > 0.5:</h3>
sentiment = 'positive'
else:
sentiment = 'negative'
<h3 id="h-187-readability">readability</h3>
if num_sentences<15:
readability = 'very comprehensible'
elif num_sentences>40:
readability = 'hard to comprehend'
else:
readability = 'comprehensible'
輸出分析摘要
<h1 id="h-187-Output-Analysis">Output Analysis</h1>
print(f"The content is {readability}. The content is likely to be {sentiment} with ratio {sentiment_ratio} in posit
print(f"Reading time is approximately {read_minute} mins.")
print(f"The file {filename} has about {num_sentences} sentences, {num_words} words, average words per sentence is {
print(f"Total positive words {num_pos} : {pos_list}")
print(f"Total negative words {num_neg} : {neg_list}")
61
The content is comprehensible. The content is likely to be negative with ratio 0.2 in positive words.
Reading time is approximately 3 mins.
The file news.txt has about 20 sentences, 574 words, average words per sentence is 28.7.
Total positive words 4 : ['proving', 'reasonable', 'clear', 'flexibility']
Total negative words 16 : ['warned', 'stubborn', 'slow', 'debt', 'revenge', 'warned', 'hawkish', 'sharply', 'impending', 'recession', 'complicated', 'fear', 'revenge', 'recession', 'debt', 'struggle']
情感和自然語言分析的用法示例
搜尋引擎優化
客戶行為研究(產品評論中的評論)
社交媒體分析(選舉、社會證券、垃圾過濾)
金融市場參與者分析師(2021年GameStop危機)
⚠️ 本頁有 3 段未能本地執行(#1: NameError: name 'words' is not defined; #2: IndentationError: unexpected indent (
, line 3); #3: SyntaxError: f-string: expecting '}' ( , line 3)),原因見 OCR_run_report.md
郵件伺服器過濾(廣告推送)
在您的社交媒體應用程式中輸入內容,某些廣告可能很快就會顯示!
Why Grammarly
For Work
For Education
Compare Plans
Tools & Guides
Elevate Your Writing
Go beyond grammar. Choose a plan to ensure everything you write is clear, engaging, and polished.
Free
Basic writing suggestions and tone detection
Create Account
✓ Grammar
✓ Spelling
✓ Punctuation
✓ Conciseness
✓ Tone detection
FOR APPROVAL
Premium
Clarity, vocabulary, and tone improvements
Get Started
✓ Everything in Free
✓ Full-sentence rewrites
✓ Word choice
✓ Tone suggestions
✓ Citations
Business
Features for teams, organizations, and enterprises
✓ Everything in Premium
✓ Style guide
✓ Snippets
✓ Brand tones
✓ Analytics dashboard
✓ Account roles and permissions
✓ SAML single sign-on
R readable
How It Works
Pricing
Learn
Contact
時間序列分析 Time series analysis
時間序列分析是分析在一段時間間隔內收集的一系列數據點的特定方法。在時間序列分析中,分析師在設定的時間段內以一致的時間間隔記錄數據點,而不僅僅是間歇性或隨機地記錄數據點。
時間變數/特徵是自變數,支持目標變數來預測結果。
時間序列分析(TSA)用於基於時間的預測的不同領域,如天氣預報、金融、信號處理、工程領域、控制系統、通信系統。
時間序列是在不同時間戳處收集的數據點序列。這些基本上是在同一時間間隔內從同一數據源收集的連續測量值。此外,我們可以使用這些按時間順序收集的讀數來監測趨勢和隨時間的變化。時間序列模型可以是單變數模型,也可以是多變數模型。
穩態和非穩態時間序列 Stationary and Non-Stationary Time Series
平穩性是時間序列的一個屬性。穩態序列是指序列值不是時間函數的序列。也就是說,序列的統計屬性(如均值、方差和自相關)隨時間變化是恆定的。
序列的自相關只不過是序列與其先前值的相關性,稍後會詳細介紹。靜止的時間序列也沒有季節性影響。
例:
在特定位置進行的一系列每日溫度測量,其中平均溫度隨時間保持不變。
穩定公司的股價波動性小,沒有長期趨勢。
穩定產品的每日銷售額,隨時間推移保持相對穩定。
在平均潮位保持不變的固定位置記錄的海洋潮汐高度。
非平穩行為可以是趨勢、週期、隨機遊走或三者的組合。數據點通常是非平穩的,或者具有隨時間變化的均值、方差和協方差。
例:
成長型公司的股價隨著時間的推移呈上升趨勢。
季節性產品(如霜淇淋)的月銷售額,具有週期性模式。
隨著個體數量的增加,人口隨時間增長。
受氣候變化影響地區的每日溫度測量值,那裡有明顯的長期溫度上升趨勢。
趨勢
該趨勢顯示了時間序列數據在很長一段時間內的大致方向。趨勢可以是增加(向上)、減少(向下)或水準(靜止)。
季節性 Seasonality
季節性成分表現出在時間、方向和幅度方面重複的趨勢。一些例子包括由於炎熱的天氣條件導致夏季用水量增加。
週期性成分 Cyclical Component
這些趨勢在特定時間段內沒有固定的重複。週期是指時間序列的起伏、繁榮和貧民窟的時期,主要在商業週期中觀察到。這些周期沒有表現出季節性變化,但通常發生在3到12年的時間段內,具體取決於時間序列的性質。
不規則變化 Irregular Variation
這些是時間序列數據的波動,當去除趨勢和周期變化時,這些波動變得明顯。這些變化是不可預測的、不穩定的,可能是隨機的,也可能不是隨機的。
ETS分解 ETS Decomposition
ETS 代表 Error-Trend-Seasonality,是用於時間序列分解的模型。ETS 分解用於分離時間序列的不同元件。ETS 一詞代表誤差、趨勢和季節性。
依存 Dependence
它是指同一變數的兩個觀測值在先前時間段的關聯。
差分 Differencing
差分用於使序列平穩並控制自相關。在時間序列分析中,在某些情況下,我們不需要差分,過度差分的序列可能會產生錯誤的估計。
規範 Specification
它可能涉及使用時間序列模型(如 ARIMA 模型)測試因變數的線性或非線性關係。
ARIMA
代表自回歸綜合移動平均線。如果統計模型基於過去的值預測未來值,則該模型是自回歸的。
模式識別-趨勢 Patterns Recognition – Trend
當在時間序列中觀察到斜率增加或減少時,將觀察到趨勢。
線性趨勢:保持直線。
多項式趨勢:顯示多項式曲線。
指數趨勢:顯示指數增長或下降。
對數趨勢:顯示對數增長或下降。
對時間序列進行去趨勢化 Detrend a time series
對時間序列進行去趨勢化是從時間序列中刪除趨勢分量。
從時間序列中減去最佳擬合線。最佳擬合線可以從以時間步長為預測變數的線性回歸模型中獲得。對於更複雜的趨勢,您可能希望在模型中使用二次項(x^2)。
減去從我們之前看到的時間序列分解中獲得的趨勢分量。
· 减去平均值
應用Baxter-King過濾器(statsmodels.tsa.filters.bkfilter)或Hodrick-Prescott過濾器(statsmodels.tsa.filters.hpfilter)等過濾器來刪除移動平均趨勢線或週期分量。
模式識別 - 季節性 Patterns Recognition - Seasonality
當由於季節性因素在常規間隔之間觀察到明顯的重複模式時,就會觀察到季節性。這可能是因為一年中的月份、月份的某一天、工作日甚至一天中的時間。
• 年度:示例 - 黑色星期五和耶誕節促銷
每月:示例-我們可能會在每月的第一周發現大筆銷售,因為當時支付了工資。
對時間序列進行反季節化的方法:
以長度為季節性視窗的移動平均線。這將在此過程中串聯平滑。
季節差異系列(從當前值中減去上一季的值)
將序列除以季節性指數(STL)分解的季節性趨勢分解獲得的季節性指數
〔Tesseract 另讀到 162 字,經詞彙驗證判定為圖內文字/程式碼雜訊,未收錄;需要時見 OCR_uncertain.md〕
測試時間序列的季節性 Test for seasonality of a time series
常見的方法是繪製序列並在固定的時間間隔內檢查可重複的模式。因此,季節性的類型由時鐘或日曆決定:
一天中的小時
月份中的某一天
週刊
· 每月
· 每年
加法和乘法時間序列 Additive and Multiplicative Time Series
我們可能有不同的趨勢和季節性組合。根據趨勢的性質和季節性,可以將時間序列建模為加法或乘法時間序列。序列中的每個觀測值都可以表示為元件的總和或乘積。
加法時間序列:
值 = 基数 + 趨勢 + 季節性 + 誤差
乘法時間序列:
值 = 基数水準 x 趨勢 x 季節性 x 誤差
平穩性 Stationarity
穩態時間序列具有不隨時間變化的統計屬性或時刻(例如,均值和方差)。因此,平穩性是平穩時間序列的狀態。相反,非平穩是時間序列的狀態,其統計屬性隨時間變化。
數據點通常是非平穩性的,或者具有隨時間變化的均值、方差和協方差。
非平穩性行為可以是趨勢、週期、隨機遊走或三者的組合。通常,非平穩數據是不可預測的,無法建模或預測。
使時間序列靜止 Make a time series stationary
我們可以應用某種變換來使時間序列平穩。這些轉變可能包括:
區分系列(一次或多次)
獲取該系列的日誌
取級數的第 n 次根
以上组合
在預測之前使非平穩序列靜止
預測平穩序列相對容易,預測更可靠。一個重要的原因是,
自回歸預測模型本質上是線性回歸模型,它利用序列本身的滯後
作為預測變數。我們知道,如果預測變數(X
變數)彼此不相關,線性回歸效果最好。因此,將序列穩態化可以解決這個問題,因為它消除了任何持久的自相關,從而使預測模型中的預測變數(序列的滯後)幾乎獨立。
平穩性測試
單元根測試有多種實現,例如:
-
增強型 Dickey Fuller 測試(ADH 測試)
-
Kwiatkowski-Phillips-Schmidt-Shin - KPSS 測試(趨勢平穩)
-
飛利浦 Perron 測試(PP 測試)Philips Perron test
處理時間序列中的缺失值Treat missing values in a time series
歸因的一些有效替代方案是:
-
向後/向前填充 Backward/Forward Fill
-
線性插值 Linear Interpolation
• 二次插值 Quadratic interpolation
- 最近鄰的平均值 Mean of nearest neighbours
• 季節性對應物的平均值 Mean of seasonal counterparts
Autocorrelation and Partial Autocorrelation
Autocorrelation是時間序列中不同點的兩個觀測值之間的相關性。例如,由區間分隔的值可能具有很強的正相關或負相關。當存在這些相關性時,它們表明過去的值會影響當前值。
Partial autocorrelation 函數與上面的 ACF
類似,只不過它只顯示兩個觀測值之間的相關性,而這些觀測值之間的較短滯後無法解釋。
可預測性 Forecastability
時間序列的規律性和可重複性越強,就越容易預測。
近似熵可用於量化時間序列中波動的規律性和不可預測性。近似熵越高,預測它就越困難。
平滑 Smoothening
時間序列的平滑:
-
取移動平均線
-
進行 LOESS滑(局部回歸)
-
執行 LOWESS 平滑(局部加權回歸)
-
移動平均線只不過是定義寬度的滾動視窗的平均值。
📁 Image_20261118_0005.pdf(p.201–250)
How to Smoothen a Time Series
Original Series
ARIMA 模型
ARIMA
模型代表自動回歸綜合移動平均線。它用於使用時間序列的過去值和預測誤差來預測時間序列的未來值。下圖顯示了 ARIMA 模型的元件:
自動回歸模型 Auto-Regressive models
自動回歸模型使用過去的行為來預測未來的行為,其中過去和未來的數據之間存在一定的相關性。下面的公式表示自回歸模型。它是斜率公式的修改版本,目標值表示為截距之和、係數和先前輸出的乘積以及誤差校正項。
滾動分析 Rolling Analysis
時間序列模型的滾動分析通常用於評估模型隨時間推移的穩定性。使用統計模型分析金融時間序列數據時,一個關鍵假設是模型的參數隨時間推移是恆定的。
滾動平均線是可視化數據集趨勢的好方法。由於數據集按月提供計數,因此視窗大小為12將為我們提供年度滾動平均值。
時序數據分析摘要
在數學中,時間序列是按時間順序索引的一系列數據點。最常見的是,時間序列是在連續等距的時間點上拍攝的序列。因此,它是離散時間數據的序列。
參考及引用
教科書
- 初學者
Python Crash Course a Hands-on Project-based Introduction to Programming, 2nd E, Eric Matthes, NoStarch
- 中級
Dive Into Python3, Mark Pilgrim, APRESS
- 進階
Effective Python, 90 Specific Ways to Write Better Python, E, Brett Slatkin, ADDISON-WESLEY
網站
• Object-Oriented Programming
https://realpython.com/python3-object-oriented-programming/
• Forecasting: Principles and Practice (2nd ed)
https://otexts.com/fpp2/
- Draw.io = UML 繪圖應用程式
https://drawio-app.com/blog/uml-class-diagrams-in-draw-io/