chatGPTで教科書問題を解かせた
-----------------------------------------------------------------------------
(x,y,z)のデータ列(82,97,163),(100,91,138),(125,79,138),(96,92,136),(99,92,140),(190,54,103),(186,57,121),(142,73,124),(95,94,145),(179,58,116),(139,76,141),(77,98,152)について
z=a*x+b*y+c
を最小二乗法でフィットした場合のa,b,cを求めるpythonのプログラムコードを示せ。
また、これらのデータ列と回帰式を、グラフに示せ。
-----------------------------------------------------------------------------
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
# Define the data points as a numpy array
data = np.array([(82,97,163),(100,91,138),(125,79,138),(96,92,136),(99,92,140),
(190,54,103),(186,57,121),(142,73,124),(95,94,145),(179,58,116),
(139,76,141),(77,98,152)])
# Extract the x, y, and z data from the array
x_data = data[:, 0]
y_data = data[:, 1]
z_data = data[:, 2]
# Create a design matrix A and observation vector b for the least squares method
A = np.column_stack((x_data, y_data, np.ones(len(x_data))))
b = z_data.reshape(-1, 1)
# Calculate the coefficients (a, b, c) of the regression equation z = a*x + b*y + c using the least squares method
coefficients = np.linalg.lstsq(A, b, rcond=None)[0]
a, b, c = coefficients.flatten()
# Print the regression equation
print(f"Regression equation: z = {a:.2f}x + {b:.2f}y + {c:.2f}")
# Plot the data points and the regression plane in a 3D plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(x_data, y_data, z_data, c='black', label='Data')
xx, yy = np.meshgrid(np.linspace(np.min(x_data), np.max(x_data), 10),
np.linspace(np.min(y_data), np.max(y_data), 10))
zz = a*xx + b*yy + c
ax.plot_surface(xx, yy, zz, alpha=0.2, color='red', label='Regression plane')
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')
plt.legend()
plt.show()