T 流年印迹
流年印迹
首页 Python 正文

Python 100 天 · 第 77 天:线性回归与 Seaborn:电影票房

这是「Python 100 天」系列第 77 天的学习笔记:线性回归与 Seaborn:电影票房。正文包含知识点拆解、可直接运行的代码,以及当天仓库源文件的逐文件讲解。

今天要解决的问题

一份"电影成本 / 全球票房"的脏数据(带 $、逗号、日期字符串、未来上映的电影、0 票房),清洗后画气泡图 + 回归线,用 scikit-learn 量化"预算每多 1 美元,票房多多少"。README 知识点:多条件筛选、Seaborn 气泡图、地板除把年份变年代、Seaborn 回归图、scikit-learn 做回归。

一、一次清洗多列

1
2
3
4
5
6
7
chars_to_remove = [',', '$']
columns_to_clean = ['USD_Production_Budget', 'USD_Worldwide_Gross', 'USD_Domestic_Gross']

for col in columns_to_clean:
for char in chars_to_remove:
data[col] = data[col].astype(str).str.replace(char, "")
data[col] = pd.to_numeric(data[col])

嵌套循环 + 列表驱动:以后要清洗第 4 列,只改 columns_to_clean。这种"把列名写成列表"的习惯能省大量重复代码。

.str.replace(char, "") 是字面替换(不是正则),所以 $ 不用转义。要正则得 regex=True。

二、多条件筛选的两种写法

1
2
3
4
5
# 写法 1:布尔索引 + 位运算符
data.loc[(data.USD_Domestic_Gross == 0) & (data.USD_Worldwide_Gross != 0)]

# 写法 2:query 字符串
data.query('USD_Domestic_Gross == 0 and USD_Worldwide_Gross != 0')

必须用 & | ~,不能用 and or not,而且每个条件都要加括号——因为 & 的优先级比 == 高。这是 pandas 最经典的报错来源(ValueError: The truth value of a Series is ambiguous)。

query() 可读性更好,列名含空格时用反引号 ` 列名 `。

三、地板除:年份 → 年代

1
data['Decade'] = (data.Release_Date.dt.year // 10) * 10

// 是地板除(向下取整):1994 // 10 = 199,再 * 10 = 1990。一行完成"1994 → 1990 年代"。

对比 /:1994 / 10 = 199.4(浮点)。分组统计前先降粒度,是聚合分析的常用手法(这里是把 100 年压成 10 个桶,趋势更清楚)。

四、Seaborn 气泡图

1
2
3
4
5
sns.scatterplot(data=release_data,
x='USD_Production_Budget',
y='USD_Worldwide_Gross',
hue='USD_Worldwide_Gross', # 颜色
size='USD_Worldwide_Gross') # 大小

Seaborn 和 Matplotlib 的关系:Seaborn 是建立在 Matplotlib 之上的高层封装,data= + 列名 就能画,不用自己拆 x/y 数组。hue(颜色)和 size(大小)可以映射第三、第四个变量——这就是"气泡图"。

五、回归线

1
sns.regplot(data=release_data, x='USD_Production_Budget', y='USD_Worldwide_Gross')

regplot 自动做线性拟合并画置信区间。但它只是"画出来",不给你系数。

六、scikit-learn 做回归

1
2
3
4
5
6
7
8
from sklearn.linear_model import LinearRegression

regression = LinearRegression()
regression.fit(X, y) # X 必须是二维!

print(regression.coef_) # 斜率
print(regression.intercept_) # 截距
print(regression.score(X, y)) # R²

三个必须知道的点:

  1. X 必须是二维数组((n_samples, n_features))。一列也要 reshape(-1, 1) 或 df[['列名']](双层方括号);
  2. coef_ 是"x 每增加 1,y 平均增加多少";
  3. score() 返回 R²:模型解释了目标变量多少比例的方差,1 是完美,0 是"和瞎猜一样"。

这份代码用 X = release_data[['USD_Production_Budget']](二维)、y = release_data['USD_Worldwide_Gross'](一维)。

代码全文(notebook 全部单元格)

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
# seaborn:基于 matplotlib 的统计绘图库,默认配色和统计图更漂亮;
# sklearn.linear_model.LinearRegression:最小二乘线性回归。
import pandas as pd
import matplotlib.pyplot as plt

import seaborn as sns
from sklearn.linear_model import LinearRegression

# 浮点显示格式 + 注册日期转换器(老版本兼容用)。
pd.options.display.float_format = '{:,.2f}'.format

from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()

# 读“脏”数据:预算/票房列带 $ 和逗号,日期是字符串。
data = pd.read_csv('cost_revenue_dirty.csv')

# shape:先看规模。
data.shape

# sample(5):随机看 5 行,了解脏数据的具体形态。
data.sample(5)

# tail():看尾部有没有汇总行/空行。
data.tail()

# isna().values.any():有没有缺失值。
print(f'Any NaN values among the data? {data.isna().values.any()}')

# duplicated().values.any():有没有完全重复的行;再筛出来数一数。
print(f'Any duplicates? {data.duplicated().values.any()}')

duplicated_rows = data[data.duplicated()]
print(f'Number of duplicates: {len(duplicated_rows)}')

# info():每列 dtype 和非空数 —— 金额列现在是 object(字符串)。
# Show NaN values and data types per column
data.info()

# 批量清洗:对三列金额,循环去掉 ',' 和 '$',再 to_numeric 转数字。
# 这是“先看 info 定位问题列,再批量处理”的标准流程。
chars_to_remove = [',', '$']
columns_to_clean = ['USD_Production_Budget',
'USD_Worldwide_Gross',
'USD_Domestic_Gross']

for col in columns_to_clean:
for char in chars_to_remove:
# Replace each character with an empty string
data[col] = data[col].astype(str).str.replace(char, "")
# Convert column to a numeric data type
data[col] = pd.to_numeric(data[col])

# 看一眼清洗结果:金额已是数字,可以直接比较和计算。
data.head()

# 日期列转 datetime,否则没法按年份/年代分组。
data.Release_Date = pd.to_datetime(data.Release_Date)
data.head()

# 再 info 一次,确认 dtype 都对了。
data.info()

# describe():金额的分布范围。min 出现 1100 这种值 —— 说明还有异常。
data.describe()

# 查预算正好 1100 美元的行:明显是录入错误(少了几个零)。
data[data.USD_Production_Budget == 1100.00]

# 查预算 4.25 亿美元的行:确认极端值是否真实。
data[data.USD_Production_Budget == 425000000.00]

# 国内票房为 0 的电影:可能是没在国内上映,而不是真的零收入。
zero_domestic = data[data.USD_Domestic_Gross == 0]
print(f'Number of films that grossed $0 domestically {len(zero_domestic)}')
zero_domestic.sort_values('USD_Production_Budget', ascending=False)

# 全球票房为 0 的:数据缺失的典型表现。
zero_worldwide = data[data.USD_Worldwide_Gross == 0]
print(f'Number of films that grossed $0 worldwide {len(zero_worldwide)}')
zero_worldwide.sort_values('USD_Production_Budget', ascending=False)

# 用 & 组合两个条件(每个条件都要加括号);
# 国内 0 但全球不为 0 = 只在海外上映的影片。
international_releases = data.loc[(data.USD_Domestic_Gross == 0) &
(data.USD_Worldwide_Gross != 0)]
print(f'Number of international releases: {len(international_releases)}')
international_releases.head()

# 等价写法:DataFrame.query('表达式'),可读性更好,列名不用重复写 data.xxx。
international_releases = data.query('USD_Domestic_Gross == 0 and USD_Worldwide_Gross != 0')
print(f'Number of international releases: {len(international_releases)}')
international_releases.tail()

# pd.Timestamp('2018-5-1'):数据抓取日期,作为“未来影片”的分界线。
# Date of Data Collection
scrape_date = pd.Timestamp('2018-5-1')

# 上映日期 >= 抓取日期 = 当时还没上映的影片。
future_releases = data[data.Release_Date >= scrape_date]
print(f'Number of unreleased movies: {len(future_releases)}')
future_releases

# drop(labels):按**索引**删除行 —— 这里传的是那些未来影片的行索引,
# 从而把“还没上映所以票房为 0”的样本剔掉,避免污染回归。
# exclude future releases
data_clean = data.drop(future_releases.index)

# 对比行数差,确认删了 7 行。
# difference is 7 rows
data.shape[0] - data_clean.shape[0]

# 亏损影片占比:预算 > 全球票房。len(df) 是行数,相除得比例。
money_losing = data_clean.loc[data_clean.USD_Production_Budget > data_clean.USD_Worldwide_Gross]
len(money_losing)/len(data_clean)

# query 版本,shape[0] 与 len 等价。
money_losing = data_clean.query('USD_Production_Budget > USD_Worldwide_Gross')
money_losing.shape[0]/data_clean.shape[0]

# sns.scatterplot(data=, x=, y=):声明式接口 —— 直接传列名,不用自己切 Series。
# ax.set(...) 一次设置多个属性(xlim/ylim/轴标题)。
# 限额是为了切掉极端值,让主体分布看得清。
plt.figure(figsize=(8,4), dpi=200)

ax = sns.scatterplot(data=data_clean,
x='USD_Production_Budget',
y='USD_Worldwide_Gross')

ax.set(ylim=(0, 3000000000),
xlim=(0, 450000000),
ylabel='Revenue in $ billions',
xlabel='Budget in $100 millions')

plt.show()

# hue= 按数值上色(连续色阶),size= 让点大小也编码一个变量 —— 一图三变量。
plt.figure(figsize=(8,4), dpi=200)
ax = sns.scatterplot(data=data_clean,
x='USD_Production_Budget',
y='USD_Worldwide_Gross',
hue='USD_Worldwide_Gross', # change colour
size='USD_Worldwide_Gross',) # change size of dot

ax.set(ylim=(0, 3000000000),
xlim=(0, 450000000),
ylabel='Revenue in $ billions',
xlabel='Budget in $100 millions',)

plt.show()

# with sns.axes_style('darkgrid'): 只对这张图生效的样式上下文,
# 比全局 sns.set_style 更安全(不影响后面的图)。
plt.figure(figsize=(8,4), dpi=200)

# set styling on a single chart
with sns.axes_style('darkgrid'):
ax = sns.scatterplot(data=data_clean,
x='USD_Production_Budget',
y='USD_Worldwide_Gross',
hue='USD_Worldwide_Gross',
size='USD_Worldwide_Gross')

ax.set(ylim=(0, 3000000000),
xlim=(0, 450000000),
ylabel='Revenue in $ billions',
xlabel='Budget in $100 millions')

# 换 x 轴为上映日期:能看出“电影产量随年代增长”这个宏观趋势。
plt.figure(figsize=(8,4), dpi=200)

with sns.axes_style("darkgrid"):
ax = sns.scatterplot(data=data_clean,
x='Release_Date',
y='USD_Production_Budget',
hue='USD_Worldwide_Gross',
size='USD_Worldwide_Gross',)

ax.set(ylim=(0, 450000000),
xlim=(data_clean.Release_Date.min(), data_clean.Release_Date.max()),
xlabel='Year',
ylabel='Budget in $100 millions')

# pd.DatetimeIndex(日期列).year:把日期列转成日期索引后取年份(返回整数数组)。
dt_index = pd.DatetimeIndex(data_clean.Release_Date)
years = dt_index.year

# 整除演示:1999 // 10 = 199(去掉个位)。
# How to convert the year 1999 to the 90s decade
1999//10

# 再乘 10 = 1990,得到“年代”的起点。
199*10

# years // 10 * 10:把每部片归到所属年代,新增 Decade 列。
decades = years//10*10
data_clean['Decade'] = decades

# 按年代切分:1960 及以前算“老片”,之后算“新片”(两个时代成本结构完全不同)。
old_films = data_clean[data_clean.Decade <= 1960]
new_films = data_clean[data_clean.Decade > 1960]

# describe() 看老片的预算/票房量级。
old_films.describe()

# 老片里预算最高的几部 —— 验证那个年代的成本上限。
old_films.sort_values('USD_Production_Budget', ascending=False).head()

# sns.regplot:散点 + 拟合直线 + 置信带,一行看完“关系形状”。
sns.regplot(data=old_films,
x='USD_Production_Budget',
y='USD_Worldwide_Gross')

# 美化版:whitegrid 背景、点半透明(alpha=0.4)减少重叠、拟合线用黑色。
plt.figure(figsize=(8,4), dpi=200)
with sns.axes_style("whitegrid"):
sns.regplot(data=old_films,
x='USD_Production_Budget',
y='USD_Worldwide_Gross',
scatter_kws = {'alpha': 0.4},
line_kws = {'color': 'black'})

# 新片同样画一张,对比斜率 —— 新片“投入产出比”明显更差(斜率更小)。
plt.figure(figsize=(8,4), dpi=200)
with sns.axes_style('darkgrid'):
ax = sns.regplot(data=new_films,
x='USD_Production_Budget',
y='USD_Worldwide_Gross',
color='#2f4b7c',
scatter_kws = {'alpha': 0.3},
line_kws = {'color': '#ff7c43'})

ax.set(ylim=(0, 3000000000),
xlim=(0, 450000000),
ylabel='Revenue in $ billions',
xlabel='Budget in $100 millions')

# 创建回归器对象(还没训练)。
# Create regression object
regression = LinearRegression()

# sklearn 要求 X 是**二维**(样本数 × 特征数),所以用 pd.DataFrame(..., columns=[...]) 包一层;
# y 同理。只传一列 Series 会报 “Expected 2D array”。
# Explanatory Variable(s) or Feature(s)
X = pd.DataFrame(new_films, columns=['USD_Production_Budget'])

# Response Variable or Target
y = pd.DataFrame(new_films, columns=['USD_Worldwide_Gross'])

# .fit(X, y):用最小二乘法求使残差平方和最小的系数。
# Find the best-fit line
regression.fit(X, y)

# .intercept_:截距(theta_0)。sklearn 里是数组形式。
# Theta zero
regression.intercept_

# .coef_:斜率(theta_1),形状 (1,1)。
# Theta one
regression.coef_

# .score(X, y):R²(决定系数),1 表示完美拟合,0 表示和“取均值”一样差。
# 这里新片 R² 只有 0.04 左右 —— 预算几乎解释不了票房,模型很弱。
# R-squared
regression.score(X, y)

# 用老片重新训练,再看系数与 R²(老片关系更线性,R² 明显更高)。
X = pd.DataFrame(old_films, columns=['USD_Production_Budget'])
y = pd.DataFrame(old_films, columns=['USD_Worldwide_Gross'])
regression.fit(X, y)
print(f'The slope coefficient is: {regression.coef_[0]}')
print(f'The intercept is: {regression.intercept_[0]}')
print(f'The r-squared is: {regression.score(X, y)}')

# 手算验证:截距 + 斜率 × 预算 = 预测票房(3.5 亿美元预算)。
22821538 + 1.64771314 * 350000000

# coef_[0,0] 注意是**二维索引**,因为 coef_ 形状是 (1,1)。
# round(x, -6):四舍五入到百万位,避免给出虚假的精确感。
budget = 350000000
revenue_estimate = regression.intercept_[0] + regression.coef_[0,0]*budget
revenue_estimate = round(revenue_estimate, -6)
print(f'The estimated revenue for a $350 film is around ${revenue_estimate:.10}.')

走读与要点

  1. 三轮体检:isna().values.any()、duplicated().values.any()、info()(看 dtype 是否都是 object)。
  2. for col in columns_to_clean 清洗三列金额。
  3. data.Release_Date = pd.to_datetime(...) 转日期。
  4. data[data.USD_Production_Budget == 1100.00]:找异常值——一部电影预算 1100 美元,明显是脏数据(单位错了)。
  5. zero_domestic / zero_worldwide:票房为 0 的记录,按预算降序看,能判断是"真没上映"还是"数据缺失"。
  6. international_releases:国内 0、全球非 0 = 只在海外上映。
  7. future_releases = data[data.Release_Date >= scrape_date]:数据采集日是 2018-05-01,之后的是"尚未上映",必须剔除,否则票房为 0 会把回归线拉平。
  8. 最后在清洗后的数据上画气泡图 + 回归。

这份代码的问题

(1) 未来上映的电影没删干净

future_releases 只是打印出来看了,后面需要 release_data = data[data.Release_Date < scrape_date] 才真正剔除。如果后续没做,回归结果会被一批"票房 0"的电影污染。

(2) 0 票房没处理

同上,USD_Worldwide_Gross == 0 的记录留在数据里,等于给回归加了大量 (高预算, 0 票房) 的点。

(3) 极端值没处理

1100 美元的预算、4.25 亿美元的预算,都是长尾。线性回归对极端值非常敏感,最好取对数(np.log1p)再回归。

(4) 用 R² 判断"模型好不好"很危险

票房受宣发、档期、口碑影响巨大,预算只能解释一部分。R² 低不代表分析错了,只代表"预算不是唯一因素"。

(5) 相关性 ≠ 因果

"预算高的电影票房高"不等于"多花钱就能多赚"。这里没有控制变量,结论只能当描述。

运行结果

  • 气泡图:预算与票房正相关,但离散度极大(同样预算,票房能差 10 倍);
  • 回归线:斜率为正,约"每多 1 美元预算,全球票房多约 3 美元"(具体数值取决于清洗后的数据);
  • 按年代分组:1980 年代后票房规模整体抬升。

易错点

  1. and 代替 &:ValueError: truth value of a Series is ambiguous。
  2. X 传了一维:Reshape your data either using array.reshape(-1, 1)。
  3. data.Release_Date.dt.year:先 to_datetime 才能用 .dt。
  4. regplot 不返回系数:要数值就用 sklearn。

动手改

  • 真正剔除未来上映和 0 票房的记录。
  • 对预算和票房都取 np.log1p 再回归,对比 R²。
  • 按年代分组各拟合一条线,看斜率是否在变大。

源文件逐个讲解

3 个文件:

文件 规模 职责
day77.ipynb77 个单元格电影预算 vs 票房:清洗 → 可视化 → 线性回归
cost_revenue_dirty.csv5390 行 × 6 列从 the-numbers.com 爬的「脏」数据
README.md8 行说明页

cost_revenue_dirty.csv——6 列,全是「脏」的

1
2
Rank,Release_Date,Movie_Title,USD_Production_Budget,USD_Worldwide_Gross,USD_Domestic_Gross
5293,8/2/1915,The Birth of a Nation,"$110,000","$11,000,000","$10,000,000"

六个字段各自的坑:

列 坑
Rank第 5293 名(排名不是 1~5390 连续)
Release_Date"8/2/1915" 美式 月/日/年(字符串)
Movie_Title带引号包裹(因为标题里有逗号)
三个金额列"$110,000" 带美元符 + 千分位逗号(字符串)

「dirty」在文件名里就写明了——这一天是「专门练清洗」的。

1915 年的电影说明数据跨度到 100 多年——这也是后面要按「年代」分组的原因。

day77.ipynb(77 个单元格)

(1)三个库,各管一段

1
2
3
4
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.linear_model import LinearRegression
库 角色
pandas清洗
matplotlib底层绘图
seaborn统计可视化(一行画散点 + 回归线)
sklearn跑线性回归

seaborn 是「matplotlib 的高层封装」——sns.scatterplot 比 plt.scatter 多支持「按列上色/改大小」。

(2)体检

1
2
3
4
5
6
7
8
data.shape
data.sample(5)
data.tail()
print(f'Any NaN values among the data? {data.isna().values.any()}')
print(f'Any duplicates? {data.duplicated().values.any()}')
duplicated_rows = data[data.duplicated()]
print(f'Number of duplicates: {len(duplicated_rows)}')
data.info()

data.info() 的输出是关键:它显示每列的 dtype——三个金额列是 object(字符串),这直接决定了下一步要转换。

(3)批量清洗三列:双重 for 循环

1
2
3
4
5
6
7
8
chars_to_remove = [',', '$']
columns_to_clean = ['USD_Production_Budget',
'USD_Worldwide_Gross',
'USD_Domestic_Gross']

for col in columns_to_clean:
for char in chars_to_remove:
data[col] = data[col].astype(str).str.replace(char, '')

这是「用数据结构消灭重复代码」的典型:

  • 三列 × 两个字符 = 六次 replace;
  • 用两个列表 + 嵌套循环,写 4 行搞定。

astype(str) 先转字符串——防止某列已被 pandas 推断为数字时,.str 访问器报错。

(4)转数字(藏在下一格)

replace 之后列还是字符串,需要 pd.to_numeric(data[col])——notebook 里紧跟着的格子做了这一步(用 data[col] = pd.to_numeric(data[col]))。

(5)日期转换

1
2
3
data.Release_Date = pd.to_datetime(data.Release_Date)
data.head()
data.info()

pd.to_datetime("8/2/1915"):pandas 能自动识别美式格式。

⚠️ 但「8/2/1915」有歧义:可能是 8 月 2 日,也可能是 2 月 8 日。

pandas 默认按「月/日/年」解析(美式)——因为数据来自美国网站,这个假设是合理的。

如果写成 pd.to_datetime(..., dayfirst=True) 就按「日/月/年」解析。

(6)描述统计

1
data.describe()

这一步能看到几个异常:

  • USD_Production_Budget 最小值是 1100(1915 年的电影只要 1100 美元);
  • 最大值 425000000(4.25 亿美元);
  • USD_Worldwide_Gross 最小值是 0——这就是后面要查的「零票房」。

(7)查极值对应的具体电影

1
2
data[data.USD_Production_Budget == 1100.00]
data[data.USD_Production_Budget == 425000000.00]

「看到异常数字,就去查是哪一行」——这是数据审查的标准动作。

(8)零票房:国内 vs 全球

1
2
3
4
5
6
7
zero_domestic = data[data.USD_Domestic_Gross == 0]
print(f'Number of films that grossed $0 domestically {len(zero_domestic)}')
zero_domestic.sort_values('USD_Production_Budget', ascending=False)

zero_worldwide = data[data.USD_Worldwide_Gross == 0]
print(f'Number of films that grossed $0 worldwide {len(zero_worldwide)}')
zero_worldwide.sort_values('USD_Production_Budget', ascending=False)

两个「零」的含义完全不同:

情况 含义
国内 0、全球 > 0「只在海外上映」(正常)
全球 0「根本没上映」(数据问题)

排序后看「预算最高但零票房」的片子——大概率是「还没上映」。

(9)多条件筛选:两种写法

1
2
international_releases = data.loc[(data.USD_Domestic_Gross == 0) & 
(data.USD_Worldwide_Gross != 0)]
1
international_releases = data.query('USD_Domestic_Gross == 0 and USD_Worldwide_Gross != 0')

两种写法等价,但各有优劣:

写法 优点 缺点
布尔索引 + &灵活(能嵌变量、函数)每个条件必须加括号,且用 & 不用 and
.query('...')像 SQL,可读性高列名有空格时要反引号

.loc[布尔序列] 里的 .loc 可以省略(data[布尔序列] 也行)——但显式写 .loc 更清楚。

⚠️ 为什么必须用 & 而不是 and?

and 是「短路求值」,只接受单个布尔值;而 Series 是一整列布尔值——用 and 会抛 ValueError: The truth value of a Series is ambiguous。

这是 Pandas 最经典的报错。

(10)剔除「未上映」:按日期

1
2
3
4
5
6
scrape_date = pd.Timestamp('2018-5-1')
future_releases = data[data.Release_Date >= scrape_date]
print(f'Number of unreleased movies: {len(future_releases)}')

data_clean = data.drop(future_releases.index)
data.shape[0] - data_clean.shape[0]

逻辑非常清晰:

  1. 数据抓取日是 2018-05-01;
  2. 上映日期 ≥ 抓取日 = 还没上映;
  3. drop(索引) 删掉这 7 行。

data.drop(future_releases.index):drop 默认删「行」(axis=0),传索引列表即可。

为什么不能按「票房 = 0」删? 因为有些零票房是数据缺失,不一定是未上映——按日期判断更可靠。

(11)亏钱比例

1
2
3
4
5
money_losing = data_clean.loc[data_clean.USD_Production_Budget > data_clean.USD_Worldwide_Gross]
len(money_losing)/len(data_clean)

money_losing = data_clean.query('USD_Production_Budget > USD_Worldwide_Gross')
money_losing.shape[0]/data_clean.shape[0]

两种写法算同一个比例——len(df) 和 df.shape[0] 等价。

结论:约 37% 的电影「全球票房 < 制作预算」——但注意这不等于「亏钱」(票房不等于片方收入,还要分账、算宣发)。

这是数据分析里必须交代的「口径问题」。

(12)Seaborn 散点图

1
2
3
4
5
6
7
8
9
10
plt.figure(figsize=(8,4), dpi=200)

ax = sns.scatterplot(data=data_clean,
x='USD_Production_Budget',
y='USD_Worldwide_Gross')

ax.set(ylim=(0, 3000000000),
xlim=(0, 450000000),
ylabel='Revenue in $ billions',
xlabel='Budget in $100 millions')

sns.scatterplot(data=df, x=列名, y=列名):直接传 DataFrame + 列名——比 plt.scatter(x=df.a, y=df.b) 更简洁。

ax.set(...) 一次设多个属性——比连写四行 plt.xxx 更整齐。

(13)气泡图:hue + size

1
2
3
4
5
ax = sns.scatterplot(data=data_clean,
x='USD_Production_Budget',
y='USD_Worldwide_Gross',
hue='USD_Worldwide_Gross', # change colour
size='USD_Worldwide_Gross',) # change size of dots

hue='列名':按列值上色(颜色深浅随数值变); size='列名':按列值改点大小。

同时用 hue 和 size 指向同一列——就是「颜色和大小都表示票房」——视觉上强化了「大片更醒目」。

(14)with sns.axes_style(...):临时改风格

1
2
with sns.axes_style('darkgrid'):
ax = sns.scatterplot(...)

sns.axes_style() 是「上下文管理器」——with 块内用 darkgrid(灰底白格),出了块自动恢复。

这是 Seaborn 的「主题切换」机制:

风格 外观
'darkgrid'深灰底 + 白网格(最常用)
'whitegrid'白底 + 灰网格
'ticks'白底 + 刻度线
'dark' / 'white'纯色无网格

⚠️ 缩进用 2 空格( ax = ...)——PEP 8 建议 4 空格,但 Python 只要求「同一块内一致」。这不报错,只是不统一。

(15)时间序列气泡图

1
2
3
4
5
6
with sns.axes_style("darkgrid"):
ax = sns.scatterplot(data=data_clean,
x='Release_Date',
y='USD_Production_Budget',
hue='USD_Worldwide_Gross',
size='USD_Worldwide_Gross',)

x 轴换成日期——能看出「电影预算随时间增长」。

(16)「年份转年代」的技巧

1
2
dt_index = pd.DatetimeIndex(data_clean.Release_Date)
years = dt_index.year
1
2
1999//10      # 199
199*10 # 1990
1
2
decades = years//10*10
data_clean['Decade'] = decades

这是全书最优雅的一个整数技巧:

1999 // 10(整除)= 199 → 丢掉个位 199 * 10 = 1990 → 补回 0

两步合起来 = 「向下取整到 10 的倍数」——1999 → 1990、2005 → 2000。

为什么不用字符串切片? 因为整数运算快,而且不用先转字符串。

pd.DatetimeIndex(series).year:从日期列批量取年份——比 series.dt.year 更底层,但效果一样。

(17)按年代切分:老片 vs 新片

1
2
old_films = data_clean[data_clean.Decade <= 1960]
new_films = data_clean[data_clean.Decade > 1960]

分界点是 1960 年代——markdown 里说要「1969 及以前」和「1970 及以后」:

Decade <= 1960 = 1960 年代及以前(因为 1969 的 Decade 是 1960)——正好对应「≤1969」。

这是一个「用整除代替比较」的巧妙等价。

(18)regplot:散点 + 回归线

1
2
3
sns.regplot(data=old_films, 
x='USD_Production_Budget',
y='USD_Worldwide_Gross')

regplot = scatter + 线性拟合线 + 置信带——一行出「相关性强不强」。

1
2
3
4
5
6
7
plt.figure(figsize=(8,4), dpi=200)
with sns.axes_style("whitegrid"):
sns.regplot(data=old_films,
x='USD_Production_Budget',
y='USD_Worldwide_Gross',
scatter_kws = {'alpha': 0.4},
line_kws = {'color': 'black'})

scatter_kws / line_kws:给内部的散点和线分别传参:

  • {'alpha': 0.4}:点半透明(重叠处颜色更深,能看出密度);
  • {'color': 'black'}:拟合线黑色(默认是蓝的,配白底更清楚)。

(19)sklearn 线性回归:五步

1
2
3
4
5
6
7
8
9
10
regression = LinearRegression()

X = pd.DataFrame(new_films, columns=['USD_Production_Budget'])
y = pd.DataFrame(new_films, columns=['USD_Worldwide_Gross'])

regression.fit(X, y)

regression.intercept_ # θ0
regression.coef_ # θ1
regression.score(X, y) # R²

这是全书「机器学习」的第一个完整流程:

步骤 代码 含义
1LinearRegression()建模型
2准备 X(特征)、y(目标)X 必须是二维(DataFrame 或 2D array)
3.fit(X, y)训练(算 θ0、θ1)
4.intercept_ / .coef_取参数
5.score(X, y)算 R²(拟合优度)

pd.DataFrame(new_films, columns=['USD_Production_Budget']):从原表里「挑一列」变成新 DataFrame——X 必须是「表」而不是「列」(sklearn 要求 2D)。

(20)R² 怎么读

regression.score(X, y) 返回「决定系数 R²」:

  • R² = 1:完美拟合(所有点都在线上);
  • R² = 0:模型和「直接用平均值预测」一样差;
  • R² = 0.75:75% 的方差被模型解释了。

新片(1970 后)的 R² 通常在 0.5 左右——预算能解释一半的票房差异,剩下的是「运气、营销、档期」。

(21)用模型预测

1
2
3
4
budget = 350000000
revenue_estimate = regression.intercept_[0] + regression.coef_[0,0]*budget
revenue_estimate = round(revenue_estimate, -6)
print(f'The estimated revenue for a $350 film is around ${revenue_estimate:.10}.')

手动代入公式:θ0 + θ1 × 预算。

intercept_[0] 和 coef_[0,0]:都要取下标——因为 sklearn 的参数总是「数组/矩阵」形式(即使只有一个特征)。

round(x, -6):负数的 ndigits = 四舍五入到「百万」(-6 表示「6 位小数前」= 百万位)。

这是「用负 round 做粗略估算」的技巧。

:.10 格式串有问题:.10 不是合法的浮点格式(应该是 .10f 或 .10g)——这一行会抛 ValueError: Format specifier missing precision。

(22)前一行是「硬编码答案」

1
22821538 + 1.64771314 * 350000000

这一格直接写死了 θ0 和 θ1——是「手动验算」,验证 regression.coef_ 算出来的是不是这两个数。

这份代码的问题

  1. f'...{revenue_estimate:.10}' 格式串非法(应 .10f)。
  2. round(..., -6) 后打印 .10,双重错误。
  3. data.query('... and ...') 里 and 能工作(query 内部会翻译),但布尔索引里必须用 &——两种语法的差异容易混。
  4. 「亏钱」用「票房 < 预算」定义不严谨(没算分账)。
  5. descade 分界 1960 需要解释(不然读者不知道「为什么是 1960」)。
  6. sns.axes_style 块内缩进 2 空格,不统一。

README.md(8 行)

标题 Day 77 - Linear Regression with Seaborn and Scikit Learn,知识点:Linear Regression、Data Visualisation、Seaborn、Scikit Learn。

四条:线性回归、可视化、Seaborn、sklearn。

这一天是「从描述到预测」的转折:

  • Day 71~76 都是「看数据」(统计、画图);
  • Day 77 第一次「建模型、做预测」。

R² 和 residuals(残差)这两个概念,是后面 Day 80 的核心。

微信收款码 微信
支付宝收款码 支付宝
评论