Для тех, кто не знаком с частью ML, пожалуйста, взгляните на последний раздел кода. Первые коды должны спросить, есть ли какие-то проблемы с построением графика или моделью ML
Я пытаюсь изучить индивидуальное обучение, используя tf.GradientTape()
, и создал собственную модель как:
class RegressionModel(tf.keras.Model): # every new model has to use Model
'''
A Model that performs Linear Regression
'''
def __init__(self,in_units,out_units):
'''
args:
in_units: number of input neurons
out_units: number of output units
'''
super(RegressionModel,self).__init__() # constructor of Parent class
self.in_units = in_units
self.out_units = out_units
self.w = tf.Variable(tf.initializers.GlorotNormal()((self.in_units,self.out_units)))
# make weight which has initial weights according to glorot_normal distribution
self.b = tf.Variable(tf.zeros(self.out_units)) # bias is mostly zeros
self.params = [self.w,self.b] # we can use the model.params directly inside the GradientTape()
def call(self,input_tensor):
'''
execurte forward pass
args:
input_tensor: input tensor which will be fed to the network
'''
return tf.matmul(input_tensor, self.w) + self.b
Я сделал свои функции потерь и градиентов как:
def compute_loss(model,x_features,y_true):
'''
Calculate the loss. You can use RMSE or MAE
args:
model: a model that'll give predicted values
x_features: Array of data points
y_true: respective target values
'''
y_pred = model(x_features)
error = y_true - y_pred
return tf.reduce_mean(tf.square(error)) # MSE: Mean Squred Error
def compute_grad(model,x_features,y_true):
'''
Compute the Gradient here
'''
with tf.GradientTape() as tape:
loss = compute_loss(model,x_features,y_true)
return tape.gradient(loss,model.params) # you see model.params. It'll include all the params
и обучил модель как:
losses = []
optimizer = tf.keras.optimizers.SGD(lr=0.01)
model = RegressionModel(1,1) # 1 feature columns and 1 output for regression easy for plotting
print(f"Initial:\n{model.w}\n{model.b}\n\n") # model's initial weights and biases
for epoch in range(500):
gradients = compute_grad(model,X,y)
optimizer.apply_gradients(zip(gradients,model.params)) # apply back prop to all the "trainable" params
losses.append(compute_loss(model,X,y)) # make a list of loss per epoch
print(f"Final:\n{model.w}\n{model.b}")
ПРОБЛЕМА ПЕРЕДАЧИ :
Проблема в том, что я создал метод генерации точек данных согласно y=mx+c
, а затем попытался предсказать его на модели. Если вы генерируете данные как:
def generate_random_data(shape=(100,1)):
'''
Generate correlated X and y points which are correlated according to straight line y=mx+c
args:
feat_shape: {tuple} shape of the X data
'''
X = np.random.random(shape)* np.random.randn() - np.random.randn() # complete randomness
m = np.random.random((shape[1],1))
c = np.random.randn()
y = X.dot(m) + c + np.random.randn(shape[0],1)*0.13 # add some noise too
return X,y
X,y = generate_random_data() # try generating the data different times to see performance of model
X = X.astype(np.float32) # default is double or float 64 in numpy
y = y.astype(np.float32) # tf would have converted it to float32 automatically
reg_x_points = np.linspace(X.min(),X.max(),100)
reg_y_points = model.predict(reg_x_points.reshape(-1,1)).flatten()
plt.plot(reg_y_points,reg_y_points)
plt.scatter(X,y)
plt.show()
Это вообще не показывает строку? Я обучил данные для тех же X и y, но линия наилучшего соответствия находится далеко от точек данных и показывает необычное поведение. Это из-за сети, обучения, данных или графической части?