快速答案
本答案頁包含 Python 線性回歸:從直線到誤差 的 4 道選擇題、4 道填空題和 4 道輸出預測題,每題都給出準確答案和簡短解釋。
答案已完整展示,建議先嘗試作答,再用本頁核對。第一次練習最好從互動練習頁開始。
在直線 y = 3x + 2 中,3 表示什麼?
答案: 斜率
為什麼: 斜率乘以輸入,因此 x 每增加 1,預測值就增加 3。
均方誤差對哪類誤差懲罰最重?
答案: 較大的誤差
為什麼: 平方會讓較大的殘差比較小的殘差貢獻大得多。
預測前為什麼要檢查訓練輸入範圍?
答案: 範圍外的外推可能不可靠
為什麼: 配適直線在任何位置都能算出數字,但證據只覆蓋觀察到的範圍。
執行結果是什麼?
xs = [1, 2, 3]
ys = [1, 3, 5]
mean_x = sum(xs) / len(xs)
mean_y = sum(ys) / len(ys)
slope = sum((x - mean_x) * (y - mean_y) for x, y in zip(xs, ys)) / sum((x - mean_x) ** 2 for x in xs)
print(round(slope, 1))答案: 2.0
為什麼: 這些點落在 y = 2x 上,所以中心化協方差除以方差得到斜率 2.0。
補全預測公式。
def predict(x, slope, intercept):
return ____ * x + intercept
print(predict(2, 3, 1))答案: slope
為什麼: 預測先把輸入乘以斜率,再加上截距。
補全方差分母中的指數。
xs = [1, 2, 3]
mean_x = sum(xs) / len(xs)
print(sum((x - mean_x) ** ____ for x in xs))答案: 2
為什麼: 與平均值距離的平方,指數是 2。
補全均方誤差的除數。
xs = [1, 2, 3]
ys = [2, 4, 5]
slope = 1.5
intercept = 2 / 3
total = sum((y - (slope * x + intercept)) ** 2 for x, y in zip(xs, ys))
mse = total / ____
print(round(mse, 2))答案: len(xs)
為什麼: 總平方誤差除以觀測數量。
補全範圍保護條件。
def within_range(x, xs):
return min(xs) <= x <= ____(xs)
print(within_range(2, [1, 2, 3]))答案: max
為什麼: 上界來自觀察到的最大輸入。
這段程式列印出什麼?
def predict(x, slope, intercept):
return slope * x + intercept
print(predict(3, 2.0, 1.0))答案: 7.0
為什麼: 直線計算 2.0 * 3 + 1.0,結果是 7.0。
程式碼的輸出結果是什麼?
xs = [1, 2, 3]
ys = [2, 4, 6]
mean_x = sum(xs) / len(xs)
mean_y = sum(ys) / len(ys)
slope = sum((x - mean_x) * (y - mean_y) for x, y in zip(xs, ys)) / sum((x - mean_x) ** 2 for x in xs)
intercept = mean_y - slope * mean_x
print(round(slope, 1), round(intercept, 1))答案: 2.0 0.0
為什麼: 這些點正好落在 y = 2x 上,所以斜率是 2.0,截距是 0.0。
螢幕上會顯示什麼?
xs = [1, 2, 3]
ys = [2, 4, 6]
slope = 2.0
intercept = 0.0
mse = sum((y - (slope * x + intercept)) ** 2 for x, y in zip(xs, ys)) / len(xs)
print(mse)答案: 0.0
為什麼: 每個殘差都是零,所以均方誤差是 0.0。
這段程式碼會輸出什麼?
def within_range(x, xs):
return min(xs) <= x <= max(xs)
print(within_range(4, [1, 2, 3]))答案: False
為什麼: 4 大於訓練輸入的最大值,所以範圍檢查回傳 False。
先試一遍題目
打開 Python 線性回歸:從直線到誤差 練習頁,用即時回饋回答同樣的 12 道題。