刚开始学习谷歌的机器学习速成课程,然后照着他给的代码打后,报错了,请问朋友们有解决办法吗5555
以下是我的代码:
from __future__ import print_function
import math
from IPython import display
from matplotlib import cm
from matplotlib import gridspec
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
from sklearn import metrics
import tensorflow as tf
from tensorflow.python.data import Dataset
tf.compat.v1.logging.set_verbosity(tf.compat.v1.logging.ERROR)
pd.options.display.max_rows = 10
pd.options.display.float_format = '{:.1f}'.format
# 加载数据集
california_housing_dataframe = pd.read_csv(
"https://download.mlcc.google.cn/mledu-datasets/california_housing_train.csv", sep=",")
# 对数据集进行随机化处理
california_housing_dataframe = california_housing_dataframe.reindex(
np.random.permutation(california_housing_dataframe.index))
# 将 median_house_value 调整以千为单位
california_housing_dataframe["median_house_value"] /= 1000
# 构建输入函数
def my_input_function(features, targets, batch_size=1, shuffle=True, num_epochs=None):
"""
Train a linear regression model of one feature.
:param features: pandas DataFrame of features
:param targets: pandas DataFrame of targets
:param batch_size: Size of batches to be passed to the model
:param shuffle: True or False. Whether to shuffle the data.
:param num_epochs: Number of epochs for which data should be repeated. None = repeat indefinitely.
:return: Tuple of (features, labels) for next data batch
"""
# 将 Pandas 特征数据转换成 NumPy 数组字典
features = {key: np.array(value) for key, value in dict(features).items()}
# 构建 Dataset 对象
ds = Dataset.from_tensor_slices((features, targets))
# 设定批量和周期
ds = ds.batch(batch_size).repeat(num_epochs)
# 根据需要对数据进行随机化处理
if shuffle:
ds = ds.shuffle(buffer_size=10000)
# 返回下一批数据
features, labels = ds.make_one_shot_iterator().get_next()
return features, labels
# 构建训练模型函数
def train_model(learning_rate, steps, batch_size, input_feature="total_rooms"):
"""
Train a linear regression model of one feature.
:param learning_rate: A 'float' number which is the learning rate
:param steps: A non-zero 'int' number which is the total number of training steps.
A training step consists of a forward and backward pass using a single batch.
:param batch_size: A non-zero 'int' number which is the batch size
:param input_feature: A 'string' string which is specified a column from original data to use as input feature
"""
periods = 10
steps_per_period = steps / periods
my_feature = input_feature
my_feature_data = california_housing_dataframe[[my_feature]]
my_label = "median_house_value"
targets = california_housing_dataframe[my_label]
feature_columns = [tf.feature_column.numeric_column(my_feature)]
training_input_fn = lambda: my_input_function(my_feature_data, targets, batch_size=batch_size)
prediction_input_fn = lambda: my_input_function(my_feature_data, targets, num_epochs=1, shuffle=False)
my_optimizer = tf.keras.optimizers.SGD(learning_rate=learning_rate, clipvalue=5.0)
linear_regressor = tf.estimator.LinearRegressor(
feature_columns=feature_columns,
optimizer=my_optimizer
)
plt.figure(figsize=(15, 6))
plt.subplot(1, 2, 1)
plt.title("Learned Line by Period")
plt.xlabel(my_feature)
plt.ylabel(my_label)
sample = california_housing_dataframe.sample(n=300)
plt.scatter(sample[my_feature], sample[my_label])
colors = [cm.coolwarm(x) for x in np.linspace(-1, 1, periods)]
print("=========Training Model...=========")
print("RMSE (on training data): ")
predictions_final = []
root_mean_squared_errors = []
for period in range(0, periods):
linear_regressor.train(
input_fn=training_input_fn,
steps=steps_per_period
)
predictions = linear_regressor.predict(input_fn=prediction_input_fn)
predictions = np.array([item['predictions'][0] for item in predictions])
predictions_final = predictions
root_mean_squared_error = math.sqrt(
metrics.mean_squared_error(predictions, targets)
)
print(" Period %0.2f : %0.2f " % (period, root_mean_squared_error))
root_mean_squared_errors.append(root_mean_squared_error)
y_extents = np.array([0, sample[my_label].max()])
weight = linear_regressor.get_variable_value('linear/linear_model/%s/weights' % input_feature)[0]
bias = linear_regressor.get_variable_value('linear/linear_model/bias_weights')
x_extents = (y_extents - bias) / weight
x_extents = np.maximum(np.minimum(
x_extents, sample[my_feature].max()
), sample[my_feature].min())
y_extents = weight * x_extents + bias
plt.plot(x_extents, y_extents, color=colors[period])
plt.show()
print("=========Model Training Finish=========")
plt.subplot(1, 2, 2)
plt.xlabel("Periods")
plt.ylabel("RMSE")
plt.title("Root Mean Squared Error vs. Periods")
plt.tight_layout()
plt.plot(root_mean_squared_errors)
plt.show()
calibration_data = pd.DataFrame()
calibration_data["predictions"] = pd.Series(predictions_final)
calibration_data["targets"] = pd.Series(targets)
print(calibration_data.describe())
print("Final RMSE (on training data) : %0.2f" % root_mean_squared_errors[-1])
train_model(
learning_rate=0.00002,
steps=500,
batch_size=5
)
以下是我的报错:
Traceback (most recent call last):
File "C:/Users/we/Desktop/GoogleMachineLearning/TensorFlowPractice/FirstStepFunction.py", line 162, in
train_model(
File "C:/Users/we/Desktop/GoogleMachineLearning/TensorFlowPractice/FirstStepFunction.py", line 111, in train_model
linear_regressor.train(
File "C:\Users\we\Desktop\GoogleMachineLearning\venv\lib\site-packages\tensorflow_estimator\python\estimator\estimator.py", line 349, in train
loss = self._train_model(input_fn, hooks, saving_listeners)
File "C:\Users\we\Desktop\GoogleMachineLearning\venv\lib\site-packages\tensorflow_estimator\python\estimator\estimator.py", line 1175, in _train_model
return self._train_model_default(input_fn, hooks, saving_listeners)
File "C:\Users\we\Desktop\GoogleMachineLearning\venv\lib\site-packages\tensorflow_estimator\python\estimator\estimator.py", line 1203, in _train_model_default
estimator_spec = self._call_model_fn(features, labels, ModeKeys.TRAIN,
File "C:\Users\we\Desktop\GoogleMachineLearning\venv\lib\site-packages\tensorflow_estimator\python\estimator\estimator.py", line 1163, in _call_model_fn
model_fn_results = self._model_fn(features=features, **kwargs)
File "C:\Users\we\Desktop\GoogleMachineLearning\venv\lib\site-packages\tensorflow_estimator\python\estimator\canned\linear.py", line 1355, in _model_fn
return _linear_model_fn_v2(
File "C:\Users\we\Desktop\GoogleMachineLearning\venv\lib\site-packages\tensorflow_estimator\python\estimator\canned\linear.py", line 678, in _linear_model_fn_v2
optimizer.iterations = tf.compat.v1.train.get_or_create_global_step()
File "C:\Users\we\Desktop\GoogleMachineLearning\venv\lib\site-packages\tensorflow\python\keras\optimizer_v2\optimizer_v2.py", line 856, in setattr
super(OptimizerV2, self).setattr(name, value)
File "C:\Users\we\Desktop\GoogleMachineLearning\venv\lib\site-packages\tensorflow\python\keras\optimizer_v2\optimizer_v2.py", line 995, in iterations
raise RuntimeError("Cannot set iterations
to a new Variable after "
RuntimeError: Cannot set iterations
to a new Variable after the Optimizer weights have been created