p.92

4. 矩陣代數基礎

章節內容

p.93

代數 - 簡介

  1. 資料預處理

  2. 資料轉換

  3. 數據分析和預測

  4. 模型評估。

p.93 原掃描圖
p.93 原掃描圖

p.94

如何根據歷史資料進行預測?

p.94 原掃描圖
p.94 原掃描圖

OLS/線性迴歸模型

普通最小平方法 (OLS) 迴歸的性質

金融和經濟研究中的變數可以用兩種方式分類:

函數關係:

Y=f(x1,x2,…,xp) ,in which Y 僅由以下因素 xi(i=1,2,…,p) . 決定

相關關係:

Y=f(x1,x2,…,xp) ,in which Y 僅部分取決於 xi(i=1,2,…,p) .

Y=α+βx

p.95

α=+ve

β=−ve

我們用來 μ 表示誤差項

Y=α+βx+μ

t(=1,2,3,…,T) 表示觀測單位

Yt=α+βxt+μt

Yt 稱為因變數

xt 稱為自變數

  1. 有些因素無法衡量,或影響因素太多 Yt

  2. 迴歸模型無法考慮的統計誤差 Yt

  3. 一些外部因素會影響迴歸模型,無法建模。即恐怖攻擊、自然災害、設施故障

Example : U.S. Unemployment Rate and GDP

p.96

失業率與實質 GDP(1949-2023)

https://fred.stlouisfed.org/graph/?g=luy4

p.96 原掃描圖
p.96 原掃描圖

OLS(Ordinary Least Square)線性迴歸參數估計

根據 OLS 原理,最佳擬合線應最小化

估計值與實際值之間的差異。換句話說,殘差平方和應該最小化。

RSS=∑t=1T(yt−y^t)2=∑t=1T(yt−α^−β^xt)2

假設我們對 RSS 進行一階導數並將其設為零,我們可以得到以下結果:

β^=∑xtyt−Txy―∑xt2−Tx―2

α^=y―−β^x―

p.97

OLS 迴歸的基本假設

(1) E(ut)=0

(2) var(ut)=σ2<∞;

(3) cov(ui,uj)=0 ;

(4) cov(ut,xt)=0 ;

(5) ut~N(0,σ2)

估計參數的標準誤差

SE(α^)=s∑xt2T∑(xt−x¯)2=s∑xt2T((∑xt2)−Tx¯2)

SE(β^)=s1∑(xt−x¯)2=s1∑xt2−Tx¯2

in which, s=∑ut2T−2 is the standard error of residual values

  1. 標準誤差隨著樣本量 T 的增加而減少;

  2. SE(α^) 和由 SE(β^)S2 確定。

p.98

擬合優度統計

∑(yt−y¯)2

∑(yt−y¯)2=∑(y^t−y¯)2+∑u^t2

∑(y^−y¯)2 is the explained portion from OLS regression, and thus named the explained sum of squares (ESS);

∑u^t2 is the unexplained portion from OLS regression, and thus named the residual sum of squares (RSS).

∑u^t2=∑(yt−y^t)2

TSS、ESS 和 RSS

p.98 原掃描圖
p.98 原掃描圖

TSS=∑(yt−y¯)2

ESS=∑(y^−y¯)2

RSS=∑(yt−y^t)2

p.99

Fitness R2=ESSTSS

Because TSS = ESS + RSS

Therefore R2=ESSTSS=TSS−RSSTSS=1−RSSTSS

R2∈[0,1]

如果 R2 很大,這表示迴歸方程式適合大部分數據;如果 R2 很小,這表示迴歸方程式不太適合數據。

2 的讀數來確定迴歸的適合度。

矩阵

矩陣在線性代數中扮演核心角色。

對於 m,n∈ℕ, 實值 (m,n) 矩陣 A 是元素 aij 的 m×n 元組; 我 = 1, . 。 , 米; j=1,…,n; 根據 m 行和 n 列組成的矩形方案排序:

A=[a11a12…a1na21a22…a2n⋮⋮⋮am1am2…amn],aij∈R.

p.100

位置的數字相加

[3846]+[401−9]=[785−3]

位置的數字

[3846]−[401−9]=[−18315]

僅當「相鄰」維度匹配時,矩陣才能相乘。

A Bn×kk×m=Cn×m

Example

For A=[123321]∈ℝ2×3, B=[021−101]∈ℝ3×2, we obtain

AB=[123321][021−101]=[2325]∈R2×2,

BA=[021−101][123321]=[642−202321]∈R3×3.

📁 Image_20261118_0003.pdf(p.101–150)

p.101

線性方程組的緊緻表示

If we consider the system of linear equations

2x1+3x2+5x3=14x1−2x2−7x3=89x1+5x2−3x3=2

and use the rules for matrix multiplication, we can write this equation system in a more compact form as

[2354−2−795−3][x1x2x3]=[182].

矩阵除法:

A/B=A×(1/B)=A×B−1

其中 B−1 表示 B 的「逆」。

[abcd]−1=1ad−bc[d−b−ca]

矩陣轉置:

交换行和列。

我們在右上角放一個「T」表示轉置

[64241−98]T=[614−9248]

目前,您只需要了解基本想法。我們藉助 Python、R 及其函式庫深入研究複雜計算。

p.102

實際應用

有一家 iBank 發起了一項

12 月 6 日投資報告(左摘要)。另外大家集思廣益紫金礦業(2899.HK)作為參考。

您的秘書已將 csv 文件中的資料準備好。現在

(1) 您決定計算 R2 以及兩隻股票與黃金現貨的相關性。

(2)此外,您計劃使用 OSL 來預測未來的趨勢。

以下段落摘自 iBank 報告:

不要錯過這個黃金機會:首次給予中國黃金產業增持評級。我們認為,在曠日持久的歐洲主權債務危機、美國經濟困境、結構性通膨壓力以及新興市場對黃金的需求的支撐下,黃金前景樂觀。我們看好招金礦業(1818HK,跑贏大盤),因其對金價敏感。

p.103

R2-Gold-Zijin

0.048814032

R2-Gold-Zhaojin

0.621047582

CORR-Gold-Zijin

0.220938978

CORR-Gold-Zhaojin

0.788065722

=RSQ([資料集 1],[資料集 2])

=CORREL([資料集 1],[資料集 2])

更多分析數據

  1. 從工具列中選擇"資料"。將顯示"數據"選單。

  2. 選擇"數據分析"。將顯示資料分析 - 分析工具對話框。

  3. 從選單中選擇"回歸"並點擊"確定"。

  4. 在「迴歸」對話方塊中,按一下「輸入Y範圍」方塊並選擇因變數資料(紫金或招金)。

  5. 按一下「輸入 X 範圍」方塊並選擇自變數資料(GoldSpot)。

  6. 按一下"確定"運行結果。

GoldSpotZijinZhaojin
1/1/20131,675.923.0512.1
2/1/20131,686.893.1312.66
3/1/20131,663.993.1612.86
4/1/20131,656.103.0812.22
5/1/20131,656.103.0812.22
6/1/20131,656.103.0812.22
7/1/20131,646.923.0811.98
8/1/20131,659.133.0612.02
9/1/20131,657.633.0811.84
10/1/20131,675.363.0811.62
11/1/20131,662.983.0911.78
12/1/20131,662.983.0911.78
13/1/20131,662.983.0911.78
14/1/20131,667.803.0911.6
15/1/20131,679.623.0911.68
16/1/20131,679.933.1612.16
17/1/20131,687.643.1411.94
18/1/20131,684.253.1812.1
19/1/20131,684.253.1812.1
20/1/20131,684.253.1812.1
21/1/20131,690.053.1612.06
22/1/20131,692.753.1812.14
23/1/20131,685.843.1512.3
24/1/20131,667.973.0912.04
25/1/20131,658.653.0111.64
26/1/20131,658.653.0111.64
27/1/20131,658.653.0111.64
28/1/20131,655.613.0111.56
29/1/20131,663.40311.7
30/1/20131,677.002.9911.6
31/1/20131,663.702.9911.68
1/2/20131,667.402.9911.5
2/2/20131,667.402.9911.5
3/2/20131,667.402.9911.5
4/2/20131,674.302.9611.5
5/2/20131,672.952.9311.36
6/2/20131,677.572.9111.38
7/2/20131,671.402.8611.26
8/2/20131,667.252.8211.22
9/2/20131,667.252.8211.22
10/2/20131,667.252.8211.22
11/2/20131,648.072.8211.22
12/2/20131,651.332.8211.22
13/2/20131,642.502.8211.22
14/2/20131,634.852.8411.14
1-2-3-4-5-6-7-8-9-10-11-12-13-14-15-16-17-18-19-20-21-22-23-24-25-26-27-28-29-30-31-32-33-34-35-36-37-38-39-40-41-42-43-44-45-46-47-48-49-50-51-52-53-54-55-56-57-58-59-60-61-62-63-64-65-66-67-68-69-70-71-72-73-74-75-76-77-78-79-80-81-82-83-84-85-86-87-88-89-90-91-92-93-94-95-96-97-98-99-100-101-102-103-104-105-106-107-108-109-110-111-112-113-114-115-116-117-118-119-120-121-122-123-124-125-126-127-128-129-130-131-132-133-134-135-136-137-138-139-140-141-142-143-144-145-146-147-148-149-150-151-152-153-154-155-156-157-158-159-160-161-162-163-164-165-166-167-168-169-170-171-172-173-174-175-176-177-178-179-180-181-182-183-184-185-186-187-188-189-190-191-192-193-194-195-196-197-198-199-200-201-202-203-204-205-206-207-208-209-210-211-212-213-214-215-216-217-218-219-220-221-222-223-224-225-226-227-228-229-230-231-232-233-234-235-236-237-238-239-240-241-242-243-244-245-246-247-248-249-250-251-252-253-254-255-256-257-258-259-260-261-262-263-264-265-266-267-268-269-270-271-272-273-274-275-276-277-278-279-280-281-282-283-284-285-286-287-288-289-290-291-292-293-294-295-296-297-298-299-300-301-302-303-304-305-306-307-308-309-310-311-312-313-314-315-316-317-318-319-320-321-322-323-324-325-326-327-328-329-330-331-332-333-334-335-336-337-338-339-340-341-342-343-344-345-346-347-348-349-350-351-352-353-354-355-356-357-358-359-360-361-362-363-364-365-366-367-368-369-370-371-372-373-374-375-376-377-378-379-380-381-382-383-384-385-386-387-388-389-390-391-392-393-394-395-396-397-398-399-400-401-402-403-404-405-406-407-408-409-410-411-412-413-414-415-416-417-418-419-420-421-422-423-424-425-426-427-428-429-430-431-432-433-434-435-436-437-438-439-440-441-442-443-444-445-446-447-448-449-450-451-452-453-454-455-456-457-458-459-460-461-462-463-464-465-466-467-468-469-470-471-472-473-474-475-476-477-478-479-480-481-482-483-484-485-486-487-488-489-490-491-492-493-494-495-496-497-498-499-500-501-502-503-504-505-506-507-508-509-510-511-512-513-514-515-516-517-518-519-520-521-522-523-524-525-526-527-528-529-530-531-532-533-534-535-536-537-538-539-540-541-542-543-544-545-546-547-548-549-550-551-552-553-554-555-556-557-558-559-560-561-562-563-564-565-566-567-568-569-570-571-572-573-574-575-576-577-578-579-580-581-582-583-584-585-586-587-588-589-590-591-592-593-594-595-596-597-598-599-600-601-602-603-604-605-606-607-608-609-610-611-612-613-614-615-616-617-618-619-620-621-622-623-624-625-626-627-628-629-630-631-632-633-634-635-636-637-638-639-640-641-642-643-644-645-646-647-648-649-650-651-652-653-654-655-656-657-658-659-660-661-662-663-664-665-666-667-668-669-670-671-672-673-674-675-676-677-678-679-680-681-682-683-684-685-686-687-688-689-690-691-692-693-694-695-696-697-698-699-700-701-702-703-704-705-706-707-708-709-710-711-712-713-714-715-716-717-718-719-720-721-722-723-724-725-726-727-728-729-730-731-732-733-734-735-736-737-738-739-740-741-742-743-744-745-746-747-748-749-750-751-752-753-754-755-756-757-758-759-760-761-762-763-764-765-766-767-768-769-770-771-772-773-774-775-776-777-778-779-780-781-782-783-784-785-786-787-788-789-790-791-792-793-794-795-796-797-798-799-800-801-802-803-804-805-806-807-808-809-810-811-812-813-814-815-816-817-818-819-820-821-822-823-824-825-826-827-828-829-830-831-832-833-834-835-836-837-838-839-840-841-842-843-844-845-846-847-848-849-850-851-852-853-854-855-856-857-858-859-860-861-862-863-864-865-866-867-868-869-870-871-872-873-874-875-876-877-878-879-880-881-882-883-884-885-886-887-888-889-890-891-892-893-894-895-896-897-898-899-900-901-902-903-904-905-906-907-908-909-910-911-912-913-914-915-916-917-918-919-920-921-922-923-924-925-926-927-928-929-930-931-932-933-934-935-936-937-938-939-940-941-942-943-944-945-946-947-948-949-950-951-952-953-954-955-956-957-958-959-960-961-962-963-964-965-966-967-968-969-970-971-972-973-974-975-976-977-978-979-980-981-982-983-984-985-986-987-988-989-990-991-992-993-994-995-996-997-998-999-1000-1001-1002-1003-1004-1005-1006-1007-1008-1009-1010-1011-1012-1013-1014-1015-1016-1017-1018-1019-1020-1021-1022-1023-1024-1025-1026-1027-1028-1029-1030-1031-1032-1033-1034-1035-1036-1037-1038-1039-1040-1041-1042-1043-1044-1045-1046-1047-1048-1049-1050-1051-1052-1053-1054-1055-1056-1057-1058-1059-1060-1061-1062-1063-1064-1065-1066-1067-1068-1069-1070-1071-1072-1073-1074-1075-1076-1077-1078-1079-108
p.104

In [1]: #pip install statsmodels

Mini Project - Gold & Gold Stock

In [2]: import pandas as pd
import statsmodels.api as sm
import seaborn as sns

df = pd.read_csv("gold_goldstock.csv")
df["Date"] = pd.to_datetime(df['Date'], dayfirst=True)
df = df.set_index('Date')
df

Out[2]:

GoldSpotZijinZhaojin
Date
2013-01-011675.923.0512.10
2013-01-021686.893.1312.66
2013-01-031663.993.1612.86
2013-01-041656.103.0812.22
2013-01-051656.103.0812.22
............
2017-04-151285.693.067.34
2017-04-161285.693.067.34
2017-04-171284.713.067.34
2017-04-181289.762.937.24
2017-04-191280.212.877.19

1570 rows × 3 columns

⚠️ 本頁有 1 段未能本地執行(#1: ValueError: unconverted data remains when parsing with format "%Y-%d-%),原因見 OCR_run_report.md

p.105

In [3]: print('Correlation between GoldSpot and Zijin: ', df['GoldSpot'].corr(df['Zijin'])) print('Correlation between GoldSpot and Zhaojin: ', df['GoldSpot'].corr(df['Zhaojin'])) )

Correlation between GoldSpot and Zijin: 0.22093897772281507 Correlation between GoldSpot and Zhaojin: 0.7880657221651316

In [4]: #add constant to predictor variables
X = sm.add_constant(df['GoldSpot'])
#fit linear regression model
model = sm.OLS(df['Zijin'], X).fit()
#view model summary
summary = model.summary()
print(summary)

▶ 本地執行結果(Python 3.12 / matplotlib 3.11)

0
Time:                        01:35:17   Log-Likelihood:                -6195.7
No. Observations:                2852   AIC:                         1.240e+04
Df Residuals:                    2850   BIC:                         1.241e+04
Df Model:                           1                                         
Covariance Type:            nonrobust                                         
==============================================================================
                 coef    std err          t      P>|t|      [0.025      0.975]
---------------------------------------------
…(已截斷)

OLS Regression Results

Dep. Variable: Zijin R-squared: 0.049
Model:OLSAdj. R-squared:0.048
Method:Least SquaresF-statistic:80.47
Date:Sat, 04 Mar 2023Prob (F-statistic):8.22e-19
Time:04:48:16Log-Likelihood:-888.30
No. Observations:1570AIC:1781.
Df Residuals:1568BIC:1791.
Df Model:1
Covariance Type:nonrobust
coefstd errtP>|t|[0.0250.975]
const1.26120.11111.3980.0001.0441.478
GoldSpot0.00088.68e-058.9700.0000.0010.001
Omnibus: 86.123 Durbin-Watson: 0.012
Prob(Omnibus): 0.000Jarque-Bera (JB):54.679
Skew: 0.329Prob(JB):1.34e-12
Kurtosis: 2.365Cond. No.1.31e+04
p.106

In [5]: #add constant to predictor variables X = sm.add_constant(df['GoldSpot'])

fit linear regression model

model = sm.OLS(df['Zhaojin'], X).fit()

view model summary

summary = model.summary() print(summary)

OLS Regression Results

Dep. Variable: Zhaojin R-squared: 0.621 Model: OLS Adj. R-squared: 0.621 Method: Least Squares F-statistic: 2570. Date: Sat, 04 Mar 2023 Prob (F-statistic): 0.00 Time: 04:48:16 Log-Likelihood: -2512.7 No. Observations: 1570 AIC: 5029. Df Residuals: 1568 BIC: 5040. Df Model: Covariance Type: nonrobust

coef std err t p>|t| [0.025 0.975]

const -9.6994 0.311 -31.150 0.000 -10.310 -9.089 GoldSpot 0.0124 0.000 50.692 0.000 0.012 0.013

Omnibus: 305.785 Durbin-Watson: 0.023 Prob(Omnibus): 0.000 Jacque-Bera (JB): 72.126 Skew: 0.200 Probo(JB): 2.18e-16 Kurtosis: 2.030 Cond. No. 1.31e+04

Notes: [1] Standard Errors assume that the covariance matrix of the errors is correctly specified. [2] The condition number is large, 1.31e+04. This might indicate that there are strong multicollinearity or other numerical problems.

In [6]: sns.pairplot(df, x_vars=["Zijin", "Zhaojin"], y_vars=["GoldSpot"]), height=10, aspect=.8, kind="reg");

p.106 原掃描圖
p.106 原掃描圖

以上是初試數據分析應用。接下來的章節我們將討論用於資料分析的強大 Python 函式庫 NumPy 和 Pandas。

p.107

單變量迴歸 Single variable regression

在本章前面,我們了解到簡單迴歸函數表示為:

Y=α+βx

x是Y的唯一一個變量,但在實際情況中,可能不存在單一變量,也沒有我們的GDP與失業情況。影響GDP的變數有很多。

迴歸量是迴歸分析中的統計術語。它指的是迴歸模型中用於預測反應變數的任何變數。

p.108

多重回歸

Multiple Regression

參考聯合國數據,對於響應 lifeExpF 和回歸量 log(ppgdp) 的回歸,我們考慮添加生育率,即每位婦女的平均孩子數。因此,興趣集中在 log(lifeExpF) 的分佈上,因為 log(ppgdp) 和生育率都不同。

a) lifeExpF 對 log(ppgdp) 的簡單迴歸的總和圖。此圖也可以稱為邊際圖,因為它忽略了所有其他迴歸量。使用 OLS 對邊際圖擬合的平均值函數為:

lifeExpF^=29.815+5.019log(ppgdp)

其中 R2=0.596,因此 lifeExpF

中約 60% 的變異性由

log(ppgdp)解釋。預期

lifeExpF 隨著 log(ppgdp) 的增加而增加。

p.108 原掃描圖
p.108 原掃描圖

p.109

b) lifeExpF 對生育率回歸的邊際圖。這個簡單的迴歸擬合了均值函數

lifeExpF^=89.481−6.224fertility

R2=0.678,因此生育率解釋了lifeExpF 中約 68% 的變異性。預期壽命 ExpF 隨著生育率的增加而減少。

p.109 原掃描圖
p.109 原掃描圖

c) 生育率 GDP 的邊際圖。log(ppgdp) 較大的國家的生育率也往往較低,因此這些變數呈現負相關。

p.109 原掃描圖
p.109 原掃描圖

p.110

從數據中我們了解到:

多元線性迴歸透過在均值函數中允許多個迴歸量來概括簡單線性迴歸模型。然而,因變數可能相互依賴,並使預測模型更加複雜。

對於 2 變數迴歸圖,它是一個 3 維回歸圖。對於 3 個或更多維度,無法使用變數進行繪製或視覺化。

作為兩個自變數的函數的 Y 觀測值和期望值的比較

  • 一個變數可能依賴其他變數。

  • 太多的變數會導致更大的誤差/變異數。(過度擬合)

• 變數太少會導致預測偏差。

  • 假設多元迴歸公式中的誤差項為零。但保留模型選擇的誤差項(如果有)。
p.111

Standard Multiple Regression Assumptions

The population multiple regression model is

yi=β0+β1x1i+β2x2i+…+βKxKi+εi

and we assume that n sets of observations are available. The following standard assumptions are made for the model:

  1. The xji terms are fixed numbers, or they are realizations of random variables, Xj, that are independent of the error terms, εi. In the latter case, inference is carried out conditionally on the observed values of the xjis.

  2. The expected value of the random variable Y is a linear function of the independent Xi variables.

  3. The error terms are normally distributed random variables with a mean of 0 and the same variance, σ2 . The latter is called homoscedasticity, or uniform variance.

E[εi]=0 and E[εi2]=σ2 for (i=1,…,n)

  1. The random error terms, εi , are not correlated with one another, so that

E[εiεl]=0 for   all i≠l

  1. It is not possible to find a set of nonzero numbers, c1,…,cK , such that

c1x1i+c2x2i+…+cKxKi=0

This is the property of no direct linear relationship between the Xj variables.

p.112

示範項目

公司需要廣告來提高銷售額。為了分析每個媒體的效果,行銷部門有過去 200 個月的統計數據。

你的任務:

1) 找出最有效的媒體

2) 預算 300 的預測銷售額

TVRadioNewspaperSales
1230.137.869.222.1
244.539.345.110.4
317.245.969.39.3
4151.541.358.518.5
5180.810.858.412.9
68.748.975.07.2
757.532.823.511.8
8120.219.611.613.2
98.62.11.04.8
10199.82.621.210.6
p.113

使用所需的庫啟動我們的項目

import pandas as pd
import numpy as np
from sklearn import linear_model
from sklearn.metrics import mean_squared_error, r2_score
import matplotlib.pyplot as plt
import seaborn as sns
df_adv = pd.read_csv('Advertising.csv', index_col=0)
df_adv.head()

▶ 本地執行結果(Python 3.12 / matplotlib 3.11)

TV  radio  newspaper  sales
1  230.1   37.8       69.2   22.1
2   44.5   39.3       45.1   10.4
3   17.2   45.9       69.3    9.3
4  151.5   41.3       58.5   18.5
5  180.8   10.8       58.4   12.9

首次使用前您可能需要安装一些 dependencies。

  • pip install panda

  • pip install numpy

  • pip install matplotlib

  • pip install seaborn

  • pip install sklearn

開啟 Advertising.csv 後,我們檢查裡面的資料框 data frame 和資料類型。確保一切正常。(都是數字,沒有缺失資料)

1 df_adv.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 200 entries, 1 to 200
Data columns (total 4 columns):
<h3 id="h-113-Column-Non-Null-Count-Dtype">Column Non-Null Count Dtype</h3>
---    ---    ---
0 TV 200 non-null float64
1 Radio 200 non-null float64
2 Newspaper 200 non-null float64
3 Sales 200 non-null float64
dtypes: float64(4)
memory usage: 7.8 KB

9 df_adv.head()

TVRadioNewspaperSales
1230.137.869.222.1
244.539.345.110.4
317.245.969.39.3
4151.541.358.518.5
5180.810.858.412.9

⚠️ 本頁有 1 段未能本地執行(#2: SyntaxError: invalid syntax (, line 2)),原因見 OCR_run_report.md

p.114

現在研究資料視覺化。

你能察覺電視、廣播和報紙這三種廣告媒體有什麼特色嗎?

sns.pairplot(df_adv, hue="Sales", height=4)

p.114 原掃描圖
p.114 原掃描圖

p.114 原掃描圖
p.114 原掃描圖

p.115

繪製電視與銷售的關係圖

1 sns.jointplot(x="TV", y="Sales", data=df_adv, kind="reg", truncate=False, color="m", height=7)

p.115 原掃描圖
p.115 原掃描圖

p.116

繪製廣播與銷售的關係圖

1 sns.jointplot(x="Radio", y="Sales", data=df_adv,

2 kind="reg", truncate=False,

3 color="b", height=7)

p.116 原掃描圖
p.116 原掃描圖

p.117

繪製報紙與銷售量的關係圖

1 sns.jointplot(x="Newspaper", y="Sales", data=df_adv,

2 kind="reg", truncate=False,

3 color="g", height=7)

p.117 原掃描圖
p.117 原掃描圖

p.118

scikit-learn

Machine Learning in Python

Scikit-learn(sk-learn)是 Python 中的機器學習函式庫。用於資料建模和預測的強大計算工具之一。在典型的建模過程中,有 3 個短語:訓練、測試、預測。

一般我們可能會用 75% 的資料來訓練我們的模型,25% 的資料來測試,如果模型測試結果良好,我們就可以用模型來預測。

機器學習超出了我們的範圍,但它的一些功能(方法)可以幫助數據分析。

現在我們分配 df 進行訓練(150 行資料),分配 df 進行測試(50 行資料)。

1 df_train, df_test = df_adv.iloc[0:150], df_adv.iloc[150:200]

1 df_train.info()

<class 'pandas.core.frame.DataFrame'> Int64Index: 150 entries, 1 to 150 Data columns (total 4 columns):

Column Non-Null Count Dtype


p.119
<h2 id="h-119-Create-linear-regression-object">Create linear regression object</h2>
regr = linear_model.LinearRegression()

<h3 id="h-119-Train-the-model-using-the-training-sets">Train the model using the training sets</h3>
regr.fit(X_train, y_train)

<h3 id="h-119-Use-the-above-trained-model-to-predict-t">Use the above trained model to predict the Sales in test df</h3>
y_pred = regr.predict(df_test[["TV", "Radio", "Newspaper"]])

使用測試 x(50 行資料)測試上述訓練模型。儲存到模型預測 y。

預測的準確性

r2_score(df_test["Sales"], y_pred)

0.8963519785440216

print("Mean Square Error:", mean_squared_error(df_test["Sales"], y_pred))

Mean Square Error: 2.66702486838371

print("Root Mean Square Error:", mean_squared_error(df_test["Sales"], y_pred, squared=False))

Root Mean Square Error: 1.6331028346015783

這兩個函數是從我們程式碼標題中的 sklearn 函式庫導入的。

R²範圍從0到1,越大相關性越強。均方誤差和均方根誤差是簡單的概念。我們可以透過這3個數字來區分其他型號。

1、X2、X3的截距和係數並形成多元迴歸公式。誤差項是隨機變數±1.6331

regr.intercept_
3.029766796293691
regr.coef_
array([0.04700012, 0.17993257, -0.001402731])
Expected_Sales = 3.0298 + 0.047TV + 0.18Radio - 0.0014Newspaper
Expected_Sales = 3.0298 + 0.047TV + 0.18Radio - 0.0014Newspaper +/- 1.6331

⚠️ 本頁有 5 段未能本地執行(#1: NameError: name 'linear_model' is not defined; #2: NameError: name 'df_test' is not defined; #3: NameError: name 'regr' is not defined. Did you mean: 'repr'?; #4: SyntaxError: invalid decimal literal (, line 1) 等 5 段),原因見 OCR_run_report.md

p.120

現在我們有了資訊和模型:

預期銷售額 = 3.0298 + 0.047TV + 0.18Radio - 0.0014Newspaper

1)找出最有效的媒體

2)預算$300的預測銷售額

這三個係數是什麼意思?您會選擇什麼投放廣告?

廣播是最有效的廣告媒體,其次是電視,報紙的影響或負面影響幾乎為零。然而,行銷活動在大眾推廣力量中所佔的比重仍然很小。

某些產品可能在某些媒體上通常受到青睞,係數可能會有所不同。這取決於人口統計和客戶的需求。

為了投入 300 美元的廣告費,我們可能會進行以下預算。

#Place $300 into ads, we might follow this method
print("TV: ", (300-3.0298) * 0.0477 / (0.047+0.18))
print("Radio: ", (300-3.0298) * 0.18 / (0.047+0.18))

TV: 61.48722202643172
Radio: 235.48297797356827

▶ 本地執行結果(Python 3.12 / matplotlib 3.11)

TV:  62.402989162995596
Radio:  235.48297797356827

預期銷售額為48.29

1 new_ads = pd.DataFrame(np.array([[61.48722202643172, 235.48297797356827, 0]])), columns=['TV', 'Radio', 'Newspaper'])
1 # Predict with data
2 regr.predict(new_ads)
array([48.29073127])

如果您不想看到警告訊息(不是錯誤),您可以使用資料框架來擬合模型(也許還有3個具有其他預算組合的廣告計劃)。

<h3 id="h-120-Predict-with-data">Predict with data</h3>
regr.predict(df_test(["TV", "Radio", "Newspaper"])].iloc[1])
array([18.67186188])

<h3 id="h-120-If-you-don-t-want-to-see-the-warning-you">If you don&#x27;t want to see the warning, you can create a dataframe</h3>
df_test1["TV", "Radio", "Newspaper"]].iloc[0:1]
TV Radio Newspaper
191 280.7 13.9 37.0

⚠️ 本頁有 3 段未能本地執行(#1: SyntaxError: invalid decimal literal (, line 1); #3: SyntaxError: unmatched ')' (, line 1); #4: SyntaxError: closing parenthesis ']' does not match opening parenthesi),原因見 OCR_run_report.md

p.121

壞消息

  • 有些問題不是線性的,甚至不是非線性的

  • 有超過 10 種流行的機器學習工具

好消息

  • 您學習了基本的多元線性迴歸模型和預測

  • 線性迴歸可以解決很多問題

  • 機器學習庫並不難使用

我們將在後面的章節中更多地討論 Pandas 和機器學習案例。如果您有興趣立即發現,請隨時前往:

https://pandas.pydata.org/

https://scikit-learn.org/

p.122

參考和數據

教科書

• Mathematics for Machine Learning, Marc Peter, Cambridge University Press, 2020

• Statistics for Business and Economics, 9th E, Paul Newbold, Pearson

網路資料資源

• 香港政府統計處 https://www.censtatd.gov.hk/

• 美國經濟數據 https://fred.stlouisfed.org/

• 世界經濟數據 https://tradingeconomics.com/

• 世界銀行 https://www.worldbank.org/