1.我得到了包含很大数字的theta值,无法使用。
2.您能确定它有什么问题吗?
import pandas as pdimport matplotlib.pyplot as pltdata=pd.read_csv("headbrain.csv")data.head()x=np.array(data["Head Size(cm^3)"].values)y=np.array(data["Brain Weight(grams)"].values)print(x.shape)x1=np.ones(len(y))X=np.array([x,x1])X.shape#normal equation creating (x.transpose*x)*(x.transpose*y)first=np.matmul(X,X.transpose()) #first part in normal equation(x.transpose*x)second=np.matmul(X,y) #second part in nornal equation(x.transpose*y)theta=np.matmul(first,second) #normal equation for thetaprint(theta)#i return theata values large number which includes e also```
回答:
import pandas as pdimport matplotlib.pyplot as pltdata=pd.read_csv("headbrain.csv")data.head()x=np.array(data["Head Size(cm^3)"].values)y=np.array(data["Brain Weight(grams)"].values)print(x.shape)x1=np.ones(len(y))X=np.array([x,x1])X_b = np.c_[np.ones((100, 1)), X] # add x0 = 1 to each instancetheta_best = np.linalg.inv(X_b.T.dot(X_b)).dot(X_b.T).dot(y)X_new = np.array([[0], [2]])X_new_b = np.c_[np.ones((2, 1)), X_new] # add x0 = 1 to each instancey_predict = X_new_b.dot(theta_best)y_predict