我敢问?在这一点上,这是一项新技术,我无法找到解决这个看似简单错误的方法.我正在浏览的教程可以在这里找到 - http://www.tensorflow.org/tutorials/mnist/pros/index.html#deep-mnist-for-experts
我将所有代码复制并粘贴到IPython Notebook中,并在最后一段代码中出现错误.
# To train and evaluate it we will use code that is nearly identical to that for the simple one layer SoftMax network above.
# The differences are that: we will replace the steepest gradient descent optimizer with the more sophisticated ADAM optimizer.
cross_entropy = -tf.reduce_sum(y_*tf.log(y_conv))
train_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y_conv,1), tf.argmax(y_,1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
sess.run(tf.initialize_all_variables())
for i in range(20000):
batch = mnist.train.next_batch(50)
if i%100 == 0:
train_accuracy = accuracy.eval(feed_dict={x:batch[0], y_: batch[1], keep_prob: …Run Code Online (Sandbox Code Playgroud) 我不断从以下代码中获取input_shape错误.
from keras.models import Sequential
from keras.layers.core import Dense, Activation, Dropout
from keras.layers.recurrent import LSTM
def _load_data(data):
"""
data should be pd.DataFrame()
"""
n_prev = 10
docX, docY = [], []
for i in range(len(data)-n_prev):
docX.append(data.iloc[i:i+n_prev].as_matrix())
docY.append(data.iloc[i+n_prev].as_matrix())
if not docX:
pass
else:
alsX = np.array(docX)
alsY = np.array(docY)
return alsX, alsY
X, y = _load_data(dframe)
poi = int(len(X) * .8)
X_train = X[:poi]
X_test = X[poi:]
y_train = y[:poi]
y_test = y[poi:]
input_dim = 3
Run Code Online (Sandbox Code Playgroud)
以上所有都顺利进行.这是它出错的地方.
in_out_neurons = 2
hidden_neurons …Run Code Online (Sandbox Code Playgroud) 我正在尝试将教程的专家部分应用于我自己的数据,但我一直在遇到维度错误.这是导致错误的代码.
def weight_variable(shape):
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
def bias_variable(shape):
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial)
def conv2d(x, W):
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
def max_pool_2x2(x):
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
strides=[1, 2, 2, 1], padding='SAME')
W_conv1 = weight_variable([1, 8, 1, 4])
b_conv1 = bias_variable([4])
x_image = tf.reshape(tf_in, [-1,2,8,1])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
h_pool1 = max_pool_2x2(h_conv1)
Run Code Online (Sandbox Code Playgroud)
然后当我尝试运行此命令时:
W_conv2 = weight_variable([1, 4, 4, 8])
b_conv2 = bias_variable([8])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
h_pool2 …Run Code Online (Sandbox Code Playgroud) 如果耐心达到我设定的数量,我希望分类器运行得更快并提前停止.在下面的代码中,它进行了10次迭代拟合模型.
import numpy
import pandas
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import Dropout
from keras.wrappers.scikit_learn import KerasClassifier
from keras.callbacks import EarlyStopping, ModelCheckpoint
from keras.constraints import maxnorm
from keras.optimizers import SGD
from sklearn.model_selection import cross_val_score
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import StratifiedKFold
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
# fix random seed for reproducibility
seed = 7
numpy.random.seed(seed)
# load dataset
dataframe = pandas.read_csv("sonar.csv", header=None)
dataset = dataframe.values
# split into input (X) and …Run Code Online (Sandbox Code Playgroud) 这里有一些我去过的链接并完全按照他们所说的去做.我不知道我做错了什么.
https://github.com/alexarchambault/jupyter-scala
https://github.com/ipython/ipython/wiki/IPython-kernels-for-other-languages
https://github.com/apache/incubator-toree
http://jcrudy.github.io/blog/html/2013/12/08/introduction_to_iscala.html
Run Code Online (Sandbox Code Playgroud)
这些都不起作用.可能是我的节点配置的某种方式.我只是不知道.请帮忙.谢谢!
我有一个在csv文件中构造的数据.我希望能够预测在给定所有其他列的情况下,第1列是1还是0.我如何开始训练程序(最好使用神经网络)来使用所有给定的数据来进行预测.有人可以给我看的代码吗?我试过喂它numpy.ndarray,FIF0Que(对不起,如果我拼错了),还有一个DataFrame; 什么都没有效果.这是我运行的代码,直到我收到错误 -
import tensorflow as tf
import numpy as np
from numpy import genfromtxt
data = genfromtxt('cs-training.csv',delimiter=',')
x = tf.placeholder("float", [None, 11])
W = tf.Variable(tf.zeros([11,2]))
b = tf.Variable(tf.zeros([2]))
y = tf.nn.softmax(tf.matmul(x,W) + b)
y_ = tf.placeholder("float", [None,2])
cross_entropy = -tf.reduce_sum(y_*tf.log(y))
train_step = tf.train.GradientDescentOptimizer(0.01).minimize(cross_entropy)
init = tf.initialize_all_variables()
sess = tf.Session()
sess.run(init)
for i in range(1000):
batch_xs, batch_ys = data.train.next_batch(100)
sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})
Run Code Online (Sandbox Code Playgroud)
在这一点上我遇到了这个错误 -
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-128-b48741faa01b> …Run Code Online (Sandbox Code Playgroud) 这是我试图运行的代码 -
import tensorflow as tf
import numpy as np
import input_data
filename_queue = tf.train.string_input_producer(["cs-training.csv"])
reader = tf.TextLineReader()
key, value = reader.read(filename_queue)
record_defaults = [[1], [1], [1], [1], [1], [1], [1], [1], [1], [1], [1]]
col1, col2, col3, col4, col5, col6, col7, col8, col9, col10, col11 = tf.decode_csv(
value, record_defaults=record_defaults)
features = tf.concat(0, [col2, col3, col4, col5, col6, col7, col8, col9, col10, col11])
with tf.Session() as sess:
# Start populating the filename queue.
coord = tf.train.Coordinator()
threads = tf.train.start_queue_runners(coord=coord)
for …Run Code Online (Sandbox Code Playgroud) 这是我正在使用的代码.我试图得到一个1,0,或者希望得到一个真实测试集的结果概率.当我刚刚分开训练集并在训练集上运行时,我得到了~93%的准确率,但是当我训练程序并在实际测试集上运行时(没有1和0的填充在第1列)它只返回南方的东西.
import tensorflow as tf
import numpy as np
from numpy import genfromtxt
import sklearn
# Convert to one hot
def convertOneHot(data):
y=np.array([int(i[0]) for i in data])
y_onehot=[0]*len(y)
for i,j in enumerate(y):
y_onehot[i]=[0]*(y.max() + 1)
y_onehot[i][j]=1
return (y,y_onehot)
data = genfromtxt('cs-training.csv',delimiter=',') # Training data
test_data = genfromtxt('cs-test-actual.csv',delimiter=',') # Actual test data
#This part is to get rid of the nan's at the start of the actual test data
g = 0
for i in test_data:
i[0] = 1
test_data[g] = …Run Code Online (Sandbox Code Playgroud) 我有一个简单的数据框,由一列组成.在该列中有10320个观测值(数值).我正在通过将数据插入到具有每个200个观测值的窗口的图中来模拟时间序列数据.这是绘图的代码.
import matplotlib.pyplot as plt
from IPython import display
fig_size = plt.rcParams["figure.figsize"]
import time
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
fig, axes = plt.subplots(1,1, figsize=(19,5))
df = dframe.set_index(arange(0,len(dframe)))
std = dframe[0].std() * 6
window = 200
iterations = int(len(dframe)/window)
i = 0
dframe = dframe.set_index(arange(0,len(dframe)))
while i< iterations:
frm = window*i
if i == iterations:
to = len(dframe)
else:
to = frm+window
df = dframe[frm : to]
if len(df) > 100:
df = df.set_index(arange(0,len(df)))
plt.gca().cla()
plt.plot(df.index, df[0])
plt.axhline(y=std, xmin=0, xmax=len(df[0]),c='gray',linestyle='--',lw …Run Code Online (Sandbox Code Playgroud) 这是我的代码:
from keras.callbacks import EarlyStopping
model = Sequential()
model.add(Dense(50, input_dim=33, init='uniform', activation='relu'))
for u in range(3): #how to efficiently add more layers
model.add(Dense(33, init='uniform', activation='relu'))
model.add(Dense(122, init='uniform', activation='sigmoid'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
model.fit(X_train, Y_train, nb_epoch=20, batch_size=20, callbacks=[EarlyStopping(monitor='val_loss', patience=4)])
Run Code Online (Sandbox Code Playgroud)
并且出现以下错误:
TypeError: unsupported operand type(s) for -: 'NoneType' and 'int'
Run Code Online (Sandbox Code Playgroud)
不使用时不会产生该错误EarlyStopping。
有人解决吗?
python ×8
tensorflow ×5
csv ×3
keras ×3
lstm ×2
jupyter ×1
numpy ×1
scala ×1
scikit-learn ×1
theano ×1
time-series ×1