# 预测:以模型(theta)单一样本(xi)为输入,返回预测标签
def predict(xi, theta, bias=0):
label = np.sign(xi @ theta + bias)
return label
np.sum(predict(X_test, model.coef_[0], model.intercept_[0]) == y_test)/X_test.shape[0]
def predict(xi, theta, bias=0):
label = np.sign(xi @ theta + bias)
return label
-
Function Definition: This defines a function named
predict
that takes three parameters -xi
(a single sample),theta
(model parameters), and an optionalbias
(default value is 0). -
Prediction Formula: The core of the function is the line
label = np.sign(xi @ theta + bias)
. Here's the breakdown:xi @ theta
: This represents the dot product of the input samplexi
and the model parameterstheta
.xi @ theta + bias
: This is the linear combination of the dot product and the bias term.np.sign(...)
: This function returns the sign of the result. If the result is positive, it returns 1; if it's negative, it returns -1; and if it's zero, it returns 0.label
: The final predicted label for the input sample.
np.sum(predict(X_test, model.coef_[0], model.intercept_[0]) == y_test)/X_test.shape[0]
- Testing and Evaluation:
predict(X_test, model.coef_[0], model.intercept_[0])
: This predicts labels for all samples inX_test
using the model parametersmodel.coef_[0]
(coefficients) andmodel.intercept_[0]
(bias).== y_test
: This checks where the predicted labels match the actual labels iny_test
, resulting in a boolean array of True and False.np.sum(...)
: This calculates the total number of True values, which represent correct predictions./X_test.shape[0]
: This normalizes the sum by dividing it by the total number of samples inX_test
, giving the accuracy of the model on the test data.