Trying Run Python Code Importing Tnsorflow Installed Cpu Version Gpu Version Dd Go Well Li Q26132280

I have been trying to run a python code by importing TnsorFlow.I had installed a cpu version my GPU version dd not go through verywell

This is a linear regression code

When I tried to run it it gave me errors. I have attached thecode file as well as Error file

Can a expert help me in trouble shooting the error?


# -*- coding: utf-8 -*-
Spyder Editor

This is a temporary script file.
import pandas as pd
import numpy as np
from random import sample
from sklearn.metrics import r2_score
import os.path
from sklearn.preprocessing import LabelEncoder
import tensorflow as tf

TotalFeatures = 376 # we have ‘376’ features
FeaturesInUse = 150 # number of features used for predictionstarting from feature[0]
TotalSampleSize = 4209 # there are total 4209 trainingsamples.
MiniTestSampleSize = 409 # Lets keep ‘MiniTestSampleSize’ samplesas test data

# subroutine for input data processing
def PreProcessInputData(test_data, train_data) :
# first lets process columns, apply LabelEncoder to map features tointegers
# thanks to :
for c in train_data.columns:
if train_data[c].dtype == ‘object’:
lbl = LabelEncoder()[c].values) +list(test_data[c].values))
train_data[c] = lbl.transform(list(train_data[c].values))
test_data[c] = lbl.transform(list(test_data[c].values))
# you may normalize values here if you want, but again, it didn’thelped me much
#maxVal = np.amax(pd.concat([test_data[c],train_data[c]],ignore_index=True))
#minVal = np.amin(pd.concat([test_data[c],train_data[c]],ignore_index=True))
#train_data[c] = (train_data[c] – minVal + 1)/(maxVal + 1)
#test_data[c] = (test_data[c] – minVal + 1)/(maxVal + 1)

y_train_all = train_data[‘y’].as_matrix();
y_train_all = np.reshape(y_train_all, (-1, 1));

x_train_all = train_data.drop([‘y’,’ID’] , axis = 1);
x_train_all =x_train_all.drop(x_train_all.columns[FeaturesInUse:TotalFeatures],axis = 1); # drop lat few features to keep first ‘FeaturesInUse’features
x_train_all = x_train_all.as_matrix();
x_train_all = np.reshape(x_train_all, (-1, FeaturesInUse));

# let’s randomly pick ‘MiniTestSampleSize’ samples and keep themas mini test data
indices = sample(range(len(y_train_all)),MiniTestSampleSize)
# our mini test data
y_mini_test = y_train_all[indices]
x_mini_test = x_train_all[indices]

# remaining is out training data
y_train = np.delete(y_train_all, indices, axis=0)
x_train = np.delete(x_train_all, indices, axis=0)

# lets processes master test sample data
x_test_ID = test_data[‘ID’].as_matrix();
x_test = test_data.drop(‘ID’, axis = 1);
x_test = x_test.drop(x_test.columns[FeaturesInUse:TotalFeatures],axis = 1);
x_test = x_test.as_matrix();
x_test = np.reshape(x_test, (-1, FeaturesInUse));

return (x_train, y_train, x_mini_test, y_mini_test, x_test_ID,x_test)
# read input files

# process input data
# x_data, y_data : our training set
# x_mini_test, and y_mini_test are our mini test samples to testconvergence during training
# test_data_ID and test_data are to be used predict y
(x_data, y_data, x_mini_test, y_mini_test, test_data_ID, x_test) =PreProcessInputData(test_data, train_data)

# now we can refer one row of input features as x_data[0],x_data[1]
x = tf.placeholder(tf.float32, [None, FeaturesInUse]);

# this is our model
W = tf.Variable(tf.truncated_normal(shape=[FeaturesInUse,1],stddev=0.1))
b = tf.Variable(tf.constant(0.1, shape=[1]))
y = tf.matmul(x, W) + b; # predicted values
y_ = tf.placeholder(tf.float32, [None, 1]); # true y values

cross_entropy = tf.reduce_mean(tf.square(y – y_)); # this is outcost function
# alternatively, we can define error function to be R^2, but itdidn’t helped me
#total_error = tf.reduce_sum(tf.square(tf.subtract(y_,tf.reduce_mean(y_))))
#unexplained_error = tf.reduce_sum(tf.square(tf.subtract(y_,y)))
#R_squared = tf.subtract(1.0, tf.div(total_error,unexplained_error))
#cross_entropy = R_squared

train_step = tf.train.AdamOptimizer().minimize(cross_entropy); #lets use adam optimizer

sess = tf.InteractiveSession(); # start the session

# Trainning loop
for j in range(2000):
for i in range( int((TotalSampleSize-MiniTestSampleSize)/200) ): #lets take 200 samples at time
batch_x = x_data[i*200:i*200+200]
batch_y = y_data[i*200:i*200+200], feed_dict={x: batch_x, y_: batch_y})
# let’s print prediction error for our mini test data
if 0 == (j%10) :
# test error
y_pred =, feed_dict={x: x_mini_test})
TestError = r2_score(y_mini_test, y_pred)
# training error
y_pred =, feed_dict={x: x_data})
TrainError = r2_score(y_data, y_pred)
# print
print(“for iteration : {:06d}”.format(j), ” <TestErr> :{:10.4f}”.format(TestError), ” <TrainError> :{:10.4f}”.format(TrainError))
# you might want to break loop here by some means…say you foundtest error starts increasing

# Test trained model now
y_pred =, feed_dict={x: x_test})

# store to submist.csv
sub = pd.DataFrame()
sub[‘ID’] = test_data_ID
sub[‘y’] = y_pred
sub.to_csv(‘submit.csv’, index=False)



Traceback (most recent call last):

File “<ipython-input-5-5cb79189c050>”, line 1, in<module>


File””,line 710, in runfile

    execfile(filename, namespace)

File””,line 101, in execfile

  exec(compile(, filename, ‘exec’),namespace)

File “D:/Python/Test1/”, line 13, in<module>

    import tensorflow as tf

File””,line 24, in <module>

    from tensorflow.python import *

File””,line 49, in <module>

    from tensorflow.python importpywrap_tensorflow

File””,line 72, in <module>

    raise ImportError(msg)

ImportError: Traceback (most recent call last):

File””,line 18, in swig_import_helper

    return importlib.import_module(mname)

File “”, line126, in import_module

    return _bootstrap._gcd_import(name[level:],package, level)

File “<frozen importlib._bootstrap>”, line 994, in_gcd_import

File “<frozen importlib._bootstrap>”, line 971, in_find_and_load

File “<frozen importlib._bootstrap>”, line 955, in_find_and_load_unlocked

File “<frozen importlib._bootstrap>”, line 658, in_load_unlocked

File “<frozen importlib._bootstrap>”, line 571, inmodule_from_spec

File “<frozen importlib._bootstrap_external>”, line 922,in create_module

File “<frozen importlib._bootstrap>”, line 219, in_call_with_frames_removed

ImportError: DLL load failed: The specified module could not befound.

During handling of the above exception, another exceptionoccurred:

Traceback (most recent call last):

File””,line 58, in <module>

    fromtensorflow.python.pywrap_tensorflow_internal import *

File””,line 21, in <module>

    _pywrap_tensorflow_internal =swig_import_helper()

File””,line 20, in swig_import_helper


File “”, line126, in import_module

    return _bootstrap._gcd_import(name[level:],package, level)

ModuleNotFoundError: No module named’_pywrap_tensorflow_internal’

Failed to load the native TensorFlow runtime.


for some common reasons and solutions. Include the entire stacktrace

above this error message when asking for help.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *