我正在尝试在第1列中的一个要素的数据集上拟合模型,并在第0列附加一个向量。无论我尝试什么,曲线都很难适应数据。
这是代码。
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
col = ['id','ri','na','mg','al','si','k','ca','ba','fe','glass_type']
data = pd.read_csv('glass.data', names=col, index_col='id')
x = np.array(data)[:, 0]
x = x.reshape(np.size(x), 1)
y = np.array(data)[:, 3]
y = y.reshape(np.size(y), 1)
# initialising
m = np.size(x)
# appending ones vector in x
one = np.ones([m, 1], dtype=float)
x1 = np.append(one, x, axis=1)
# weight matrix
theta = np.zeros([2, 1])
i_list = []
j_l = []
error = np.zeros([m, 1])
# gradient descent
for i in range(3500):
h = x1.dot(theta)
error = h - y
theta = theta - (0.0001/m) * np.sum(x1.T.dot(error)) + (1.5/m) * np.sum(np.sum((theta[:, 1:2])**2))
i_list.append(i)
j = (1/(2*m)) * np.sum((h-y)**2)
j_l.append(j)
# plotting
plt.subplot(1, 2, 1)
plt.plot(x, y, '.r')
plt.plot(x, x1.dot(theta), '-b')
plt.subplot(1,2, 2)
plt.plot(i_list, j_l, '-g')
plt.show()
This how the data fits (image) 请建议我改进它的方法。谢谢:)